blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
79edfa2988a0fd5a60c381b2331c038f2012f8e8
5885fd1418db54cc4b699c809cd44e625f7e23fc
/boj/4225.cpp
e1651b2555d681a28c14bce162f08a666c9ad930
[]
no_license
ehnryx/acm
c5f294a2e287a6d7003c61ee134696b2a11e9f3b
c706120236a3e55ba2aea10fb5c3daa5c1055118
refs/heads/master
2023-08-31T13:19:49.707328
2023-08-29T01:49:32
2023-08-29T01:49:32
131,941,068
2
0
null
null
null
null
UTF-8
C++
false
false
1,471
cpp
#include <bits/stdc++.h> using namespace std; //%:include "utility/fast_input.h" //%:include "utility/output.h" %:include "geometry/convex_hull.h" %:include "geometry/lines.h" %:include "geometry/point.h" using ll = long long; using ld = long double; constexpr char nl = '\n'; constexpr int MOD = 998244353; constexpr ld EPS = 1e-9L; random_device _rd; mt19937 rng(_rd()); using pt = point<double>; //#define MULTI_TEST void solve_main([[maybe_unused]] int testnum, [[maybe_unused]] auto& cin) { for(int n, tt=1; cin >> n and n; tt++) { vector<pt> p; for(int i=0; i<n; i++) { double a, b; cin >> a >> b; p.emplace_back(a, b); } p = convex_hull<double>(EPS, p); n = size(p); double ans = 1e99; for(int i=n-1, j=0, k=0; j<n; i=j++) { while(true) { int nk = (k+1 == n ? 0 : k+1); auto dk = abs(line_point_dist(p[i], p[j], p[k])); auto dnk = abs(line_point_dist(p[i], p[j], p[nk])); if(dnk > dk) { k = nk; } else { break; } } ans = min(ans, abs(line_point_dist(p[i], p[j], p[k]))); } cout << "Case " << tt << ": " << ans + 0.005 - EPS << nl; } } int main() { cin.tie(0)->sync_with_stdio(0); cout << fixed << setprecision(2); #ifdef USING_FAST_INPUT fast_input cin; #endif int T = 1; #ifdef MULTI_TEST cin >> T; #endif for(int testnum=1; testnum<=T; testnum++) { solve_main(testnum, cin); } return 0; }
[ "henryxia9999@gmail.com" ]
henryxia9999@gmail.com
68a4d7eebb490a3059e8ab72f00ec71104e7032f
4669a0a75d9f3ef993567258a1c75729e263973a
/server/engine/wdt_replicator.cc
d465f7240e102d1b20c34f3611e2fb6b605d8725
[ "Apache-2.0" ]
permissive
qx-zhangzhi/LaserDB
33b7e807c6180e89d2adca9f775062b5b8327760
2119cfcb8051e222a21a532d23448937ab4e1ef4
refs/heads/main
2023-02-17T21:27:38.542718
2021-01-11T03:46:39
2021-01-11T03:46:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,185
cc
/* * Copyright 2020 Weibo Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author ZhongXiu Hao <nmred.hao@gmail.com> */ #include "common/metrics/metrics.h" #include "wdt_replicator.h" namespace laser { constexpr static char WDT_REPLICATOR_MONITOR_MODULE_NAME[] = "wdt_replicator"; constexpr static char WDT_REPLICATOR_MONITOR_WORK_TASK_SIZE_METRIC_NAME[] = "work_thread_pool_task_size"; void WdtReplicator::createTimeout(std::shared_ptr<WdtReplicatorManager> manager) { std::shared_ptr<WdtReplicator> replicator = shared_from_this(); folly::EventBase* evb = manager->getEventBase(); timeout_ = folly::AsyncTimeout::make(*evb, [replicator]() noexcept { replicator->abort_trigger_.store(true); }); evb->runInEventBaseThread([replicator]() { replicator->timeout_->scheduleTimeout(std::chrono::milliseconds(replicator->timeval_)); }); } void WdtReplicator::cancelTimeout(std::shared_ptr<WdtReplicatorManager> manager) { std::shared_ptr<WdtReplicator> replicator = shared_from_this(); manager->getEventBase()->runInEventBaseThread([replicator]() { replicator->timeout_->cancelTimeout(); }); } bool WdtReplicator::receiver(std::string* connect_url, const std::string& host_name, const std::string& directory, WdtNotifyCallback callback) { auto manager = weak_manager_.lock(); if (!manager) { callback(name_space_, identifier_, facebook::wdt::ErrorCode::ERROR); return false; } auto& options = manager->getWdt().getWdtOptions(); std::unique_ptr<facebook::wdt::WdtTransferRequest> reqPtr = std::make_unique<facebook::wdt::WdtTransferRequest>(options.start_port, options.num_ports, directory); reqPtr->hostName = host_name; auto abort = std::make_shared<facebook::wdt::WdtAbortChecker>(abort_trigger_); facebook::wdt::ErrorCode error = manager->getWdt().wdtReceiveStart(name_space_, *reqPtr, identifier_, abort); if (error != facebook::wdt::ErrorCode::OK) { LOG(ERROR) << "Transfer request error " << facebook::wdt::errorCodeToStr(error); callback(name_space_, identifier_, error); return false; } *connect_url = reqPtr->genWdtUrlWithSecret(); LOG(INFO) << "Parsed url as " << reqPtr->getLogSafeString(); try { std::shared_ptr<WdtReplicator> replicator = shared_from_this(); manager->addUpdateTask([ replicator, manager, callback = std::move(callback) ]() mutable { replicator->createTimeout(manager); SCOPE_EXIT { replicator->cancelTimeout(manager); }; facebook::wdt::ErrorCode error = manager->getWdt().wdtReceiveFinish(replicator->name_space_, replicator->identifier_); if (error != facebook::wdt::ErrorCode::OK) { LOG(ERROR) << "Transfer request error " << facebook::wdt::errorCodeToStr(error); } callback(replicator->name_space_, replicator->identifier_, error); }); } catch (...) { LOG(ERROR) << "Add wdt pool task fail."; callback(name_space_, identifier_, facebook::wdt::ErrorCode::ERROR); return false; } return true; } void WdtReplicator::sender(const std::string& connect_url, const std::string& directory, WdtNotifyCallback callback) { auto manager = weak_manager_.lock(); if (!manager) { callback(name_space_, identifier_, facebook::wdt::ErrorCode::ERROR); return; } std::unique_ptr<facebook::wdt::WdtTransferRequest> reqPtr = std::make_unique<facebook::wdt::WdtTransferRequest>(connect_url); reqPtr->wdtNamespace = name_space_; reqPtr->destIdentifier = identifier_; reqPtr->directory = directory; LOG(INFO) << "Parsed url as " << reqPtr->getLogSafeString(); try { std::shared_ptr<WdtReplicator> replicator = shared_from_this(); manager->addUpdateTask([ replicator, manager, req = std::move(reqPtr), callback = std::move(callback) ]() mutable { replicator->createTimeout(manager); SCOPE_EXIT { replicator->cancelTimeout(manager); }; auto abort = std::make_shared<facebook::wdt::WdtAbortChecker>(replicator->abort_trigger_); facebook::wdt::ErrorCode error = manager->getWdt().wdtSend(*req, abort); if (error != facebook::wdt::ErrorCode::OK) { LOG(ERROR) << "Transfer request error " << facebook::wdt::errorCodeToStr(error); } callback(replicator->name_space_, replicator->identifier_, error); }); } catch (...) { LOG(ERROR) << "Add wdt pool task fail."; callback(name_space_, identifier_, facebook::wdt::ErrorCode::ERROR); } } WdtReplicatorManager::WdtReplicatorManager(const std::string& app_name, uint32_t thread_nums) : app_name_(app_name) { event_thread_ = std::make_unique<WdtAbortTimerThread>(); wdt_thread_pool_ = std::make_shared<folly::CPUThreadPoolExecutor>( thread_nums, std::make_shared<folly::NamedThreadFactory>("WdtSyncPool")); std::weak_ptr<folly::CPUThreadPoolExecutor> weak_pool = wdt_thread_pool_; metrics::Metrics::getInstance()->buildGauges(WDT_REPLICATOR_MONITOR_MODULE_NAME, WDT_REPLICATOR_MONITOR_WORK_TASK_SIZE_METRIC_NAME, 1000, [weak_pool]() { auto pool = weak_pool.lock(); if (!pool) { return 0.0; } return static_cast<double>(pool->getTaskQueueSize()); }); facebook::wdt::Wdt::initializeWdt(app_name_); } void WdtReplicatorManager::stop() { if (wdt_thread_pool_) { wdt_thread_pool_->stop(); } } WdtReplicatorManager::~WdtReplicatorManager() { stop(); facebook::wdt::Wdt::releaseWdt(app_name_); } void WdtReplicatorManager::addUpdateTask(folly::Func func) { wdt_thread_pool_->add(std::move(func)); } } // namespace laser
[ "nmred.hao@gmail.com" ]
nmred.hao@gmail.com
c9c4b3f53fc7772229417b4b259bfc5294578a79
e389609f15efadaf5c8a0a47fa8276a42a78f70f
/BMS/ui_inverter_switch.h
88ec6bdd4e352ebb45469ecf6c4d93d4d5e14be5
[]
no_license
ubuntu11/BMS-6
82f586c3a0ce35ec1a618397b8036507a90e9853
eba947977379cccb587b3e0160422cf5d8486970
refs/heads/master
2022-02-24T00:16:07.916354
2019-05-29T14:16:28
2019-05-29T14:16:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,198
h
/******************************************************************************** ** Form generated from reading UI file 'inverter_switch.ui' ** ** Created by: Qt User Interface Compiler version 5.9.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_INVERTER_SWITCH_H #define UI_INVERTER_SWITCH_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QRadioButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_Inverter_Switch { public: QLabel *label; QWidget *layoutWidget; QHBoxLayout *horizontalLayout; QPushButton *Inverter_Switch_OkBtn; QPushButton *Inverter_Switch_QuitBtn; QWidget *layoutWidget_2; QVBoxLayout *verticalLayout; QRadioButton *Inverter_Open_Btn; QRadioButton *Inverter_Close_Btn; void setupUi(QDialog *Inverter_Switch) { if (Inverter_Switch->objectName().isEmpty()) Inverter_Switch->setObjectName(QStringLiteral("Inverter_Switch")); Inverter_Switch->resize(400, 300); Inverter_Switch->setStyleSheet(QStringLiteral("background-color: rgb(85, 170, 255);")); label = new QLabel(Inverter_Switch); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(130, 10, 141, 41)); label->setStyleSheet(QLatin1String("background-color: rgb(255, 170, 127);\n" "background-color: rgb(170, 170, 255);\n" "background-color: rgb(85, 255, 127);\n" "background-color: rgb(170, 170, 255);\n" "background-color: rgb(85, 170, 255);")); label->setFrameShape(QFrame::WinPanel); label->setFrameShadow(QFrame::Raised); layoutWidget = new QWidget(Inverter_Switch); layoutWidget->setObjectName(QStringLiteral("layoutWidget")); layoutWidget->setGeometry(QRect(170, 230, 211, 61)); horizontalLayout = new QHBoxLayout(layoutWidget); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); horizontalLayout->setContentsMargins(0, 0, 0, 0); Inverter_Switch_OkBtn = new QPushButton(layoutWidget); Inverter_Switch_OkBtn->setObjectName(QStringLiteral("Inverter_Switch_OkBtn")); QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(Inverter_Switch_OkBtn->sizePolicy().hasHeightForWidth()); Inverter_Switch_OkBtn->setSizePolicy(sizePolicy); Inverter_Switch_OkBtn->setMaximumSize(QSize(80, 40)); Inverter_Switch_OkBtn->setStyleSheet(QString::fromUtf8("font: 16pt \"\346\245\267\344\275\223\";")); horizontalLayout->addWidget(Inverter_Switch_OkBtn); Inverter_Switch_QuitBtn = new QPushButton(layoutWidget); Inverter_Switch_QuitBtn->setObjectName(QStringLiteral("Inverter_Switch_QuitBtn")); sizePolicy.setHeightForWidth(Inverter_Switch_QuitBtn->sizePolicy().hasHeightForWidth()); Inverter_Switch_QuitBtn->setSizePolicy(sizePolicy); Inverter_Switch_QuitBtn->setMaximumSize(QSize(80, 40)); Inverter_Switch_QuitBtn->setStyleSheet(QString::fromUtf8("font: 16pt \"\346\245\267\344\275\223\";")); horizontalLayout->addWidget(Inverter_Switch_QuitBtn); layoutWidget_2 = new QWidget(Inverter_Switch); layoutWidget_2->setObjectName(QStringLiteral("layoutWidget_2")); layoutWidget_2->setGeometry(QRect(160, 80, 91, 81)); verticalLayout = new QVBoxLayout(layoutWidget_2); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); Inverter_Open_Btn = new QRadioButton(layoutWidget_2); Inverter_Open_Btn->setObjectName(QStringLiteral("Inverter_Open_Btn")); sizePolicy.setHeightForWidth(Inverter_Open_Btn->sizePolicy().hasHeightForWidth()); Inverter_Open_Btn->setSizePolicy(sizePolicy); Inverter_Open_Btn->setStyleSheet(QString::fromUtf8("font: 16pt \"\346\245\267\344\275\223\";")); verticalLayout->addWidget(Inverter_Open_Btn); Inverter_Close_Btn = new QRadioButton(layoutWidget_2); Inverter_Close_Btn->setObjectName(QStringLiteral("Inverter_Close_Btn")); sizePolicy.setHeightForWidth(Inverter_Close_Btn->sizePolicy().hasHeightForWidth()); Inverter_Close_Btn->setSizePolicy(sizePolicy); Inverter_Close_Btn->setStyleSheet(QString::fromUtf8("font: 16pt \"\346\245\267\344\275\223\";")); verticalLayout->addWidget(Inverter_Close_Btn); retranslateUi(Inverter_Switch); Inverter_Switch_OkBtn->setDefault(true); Inverter_Switch_QuitBtn->setDefault(true); QMetaObject::connectSlotsByName(Inverter_Switch); } // setupUi void retranslateUi(QDialog *Inverter_Switch) { Inverter_Switch->setWindowTitle(QApplication::translate("Inverter_Switch", "Dialog", Q_NULLPTR)); label->setText(QApplication::translate("Inverter_Switch", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; color:#ffff00;\">\351\200\206\345\217\230\345\231\250\345\220\257\345\201\234\350\256\276\347\275\256</span></p></body></html>", Q_NULLPTR)); Inverter_Switch_OkBtn->setText(QApplication::translate("Inverter_Switch", "\347\241\256\345\256\232", Q_NULLPTR)); Inverter_Switch_QuitBtn->setText(QApplication::translate("Inverter_Switch", "\345\217\226\346\266\210", Q_NULLPTR)); Inverter_Open_Btn->setText(QApplication::translate("Inverter_Switch", "\346\211\223\345\274\200", Q_NULLPTR)); Inverter_Close_Btn->setText(QApplication::translate("Inverter_Switch", "\345\205\263\351\227\255", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class Inverter_Switch: public Ui_Inverter_Switch {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_INVERTER_SWITCH_H
[ "chenjian28731@gmail.com" ]
chenjian28731@gmail.com
200c74c249050aba5c9c9172fcdce5d626f4bb7e
196c6fb3b6b44fd46e7a09d8f0726f5c0ccd53fa
/src/Magnum/CubeMapTexture.h
9b9838189ddb18e8e490a688be7e62e80188e2c4
[ "MIT" ]
permissive
DerThorsten/magnum
b1403f2a9674c5056aec62ee566725e9f4bb058b
539e24787c6545350d47455490ae16fa45a382ec
refs/heads/master
2021-01-18T09:05:02.839446
2015-09-20T18:03:39
2015-09-20T18:03:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
44,097
h
#ifndef Magnum_CubeMapTexture_h #define Magnum_CubeMapTexture_h /* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> 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. */ /** @file * @brief Class @ref Magnum::CubeMapTexture */ #include "Magnum/AbstractTexture.h" #include "Magnum/Array.h" #include "Magnum/Math/Vector2.h" namespace Magnum { /** @brief Cube map texture Texture used mainly for environment maps. It consists of 6 square textures generating 6 faces of the cube as following. Note that all images must be turned upside down (+Y is top): +----+ | -Y | +----+----+----+----+ | -Z | -X | +Z | +X | +----+----+----+----+ | +Y | +----+ ## Basic usage See @ref Texture documentation for introduction. Common usage is to fully configure all texture parameters and then set the data from e.g. set of Image objects: @code Image2D positiveX(PixelFormat::RGBA, PixelType::UnsignedByte, {256, 256}, data); // ... CubeMapTexture texture; texture.setMagnificationFilter(Sampler::Filter::Linear) // ... .setStorage(Math::log2(256)+1, TextureFormat::RGBA8, {256, 256}) .setSubImage(CubeMapTexture::Coordinate::PositiveX, 0, {}, positiveX) .setSubImage(CubeMapTexture::Coordinate::NegativeX, 0, {}, negativeX) // ... @endcode In shader, the texture is used via `samplerCube`, `samplerCubeShadow`, `isamplerCube` or `usamplerCube`. Unlike in classic textures, coordinates for cube map textures is signed three-part vector from the center of the cube, which intersects one of the six sides of the cube map. See @ref AbstractShaderProgram for more information about usage in shaders. @see @ref Renderer::Feature::SeamlessCubeMapTexture, @ref CubeMapTextureArray, @ref Texture, @ref TextureArray, @ref RectangleTexture, @ref BufferTexture, @ref MultisampleTexture */ class MAGNUM_EXPORT CubeMapTexture: public AbstractTexture { friend Implementation::TextureState; public: /** @brief Cube map coordinate */ enum class Coordinate: GLenum { PositiveX = GL_TEXTURE_CUBE_MAP_POSITIVE_X, /**< +X cube side */ NegativeX = GL_TEXTURE_CUBE_MAP_NEGATIVE_X, /**< -X cube side */ PositiveY = GL_TEXTURE_CUBE_MAP_POSITIVE_Y, /**< +Y cube side */ NegativeY = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, /**< -Y cube side */ PositiveZ = GL_TEXTURE_CUBE_MAP_POSITIVE_Z, /**< +Z cube side */ NegativeZ = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z /**< -Z cube side */ }; /** * @brief Max supported size of one side of cube map texture * * The result is cached, repeated queries don't result in repeated * OpenGL calls. * @see @fn_gl{Get} with @def_gl{MAX_CUBE_MAP_TEXTURE_SIZE} */ static Vector2i maxSize(); /** * @brief Wrap existing OpenGL cube map texture object * @param id OpenGL cube map texture ID * @param flags Object creation flags * * The @p id is expected to be of an existing OpenGL texture object * with target @def_gl{TEXTURE_CUBE_MAP}. Unlike texture created using * constructor, the OpenGL object is by default not deleted on * destruction, use @p flags for different behavior. * @see @ref release() */ static CubeMapTexture wrap(GLuint id, ObjectFlags flags = {}) { return CubeMapTexture{id, flags}; } /** * @brief Constructor * * Creates new OpenGL texture object. If @extension{ARB,direct_state_access} * (part of OpenGL 4.5) is not available, the texture is created on * first use. * @see @ref CubeMapTexture(NoCreateT), @ref wrap(), @fn_gl{CreateTextures} * with @def_gl{TEXTURE_CUBE_MAP}, eventually @fn_gl{GenTextures} */ explicit CubeMapTexture(): AbstractTexture(GL_TEXTURE_CUBE_MAP) {} /** * @brief Construct without creating the underlying OpenGL object * * The constructed instance is equivalent to moved-from state. Useful * in cases where you will overwrite the instance later anyway. Move * another object over it to make it useful. * @see @ref CubeMapTexture(), @ref wrap() */ explicit CubeMapTexture(NoCreateT) noexcept: AbstractTexture{NoCreate, GL_TEXTURE_CUBE_MAP} {} #ifndef MAGNUM_TARGET_GLES2 /** * @copybrief Texture::setBaseLevel() * @return Reference to self (for method chaining) * * See @ref Texture::setBaseLevel() for more information. * @requires_gles30 Base level is always `0` in OpenGL ES 2.0. * @requires_webgl20 Base level is always `0` in WebGL 1.0. */ CubeMapTexture& setBaseLevel(Int level) { AbstractTexture::setBaseLevel(level); return *this; } #endif #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) /** * @copybrief Texture::setMaxLevel() * @return Reference to self (for method chaining) * * See @ref Texture::setMaxLevel() for more information. * @requires_gles30 Extension @es_extension{APPLE,texture_max_level}, * otherwise the max level is always set to largest possible value * in OpenGL ES 2.0. * @requires_webgl20 Always set to largest possible value in WebGL 1.0. */ CubeMapTexture& setMaxLevel(Int level) { AbstractTexture::setMaxLevel(level); return *this; } #endif /** * @copybrief Texture::setMinificationFilter() * @return Reference to self (for method chaining) * * See @ref Texture::setMinificationFilter() for more information. */ CubeMapTexture& setMinificationFilter(Sampler::Filter filter, Sampler::Mipmap mipmap = Sampler::Mipmap::Base) { AbstractTexture::setMinificationFilter(filter, mipmap); return *this; } /** * @copybrief Texture::setMagnificationFilter() * @return Reference to self (for method chaining) * * See @ref Texture::setMagnificationFilter() for more information. */ CubeMapTexture& setMagnificationFilter(Sampler::Filter filter) { AbstractTexture::setMagnificationFilter(filter); return *this; } #ifndef MAGNUM_TARGET_GLES2 /** * @copybrief Texture::setMinLod() * @return Reference to self (for method chaining) * * See @ref Texture::setMinLod() for more information. * @requires_gles30 Texture LOD parameters are not available in OpenGL * ES 2.0. * @requires_webgl20 Texture LOD parameters are not available in WebGL * 1.0. */ CubeMapTexture& setMinLod(Float lod) { AbstractTexture::setMinLod(lod); return *this; } /** * @copybrief Texture::setMaxLod() * @return Reference to self (for method chaining) * * See @ref Texture::setMaxLod() for more information. * @requires_gles30 Texture LOD parameters are not available in OpenGL * ES 2.0. * @requires_webgl20 Texture LOD parameters are not available in WebGL * 1.0. */ CubeMapTexture& setMaxLod(Float lod) { AbstractTexture::setMaxLod(lod); return *this; } #endif #ifndef MAGNUM_TARGET_GLES /** * @copybrief Texture::setLodBias() * @return Reference to self (for method chaining) * * See @ref Texture::setLodBias() for more information. * @requires_gl Texture LOD bias can be specified only directly in * fragment shader in OpenGL ES and WebGL. */ CubeMapTexture& setLodBias(Float bias) { AbstractTexture::setLodBias(bias); return *this; } #endif /** * @copybrief Texture::setWrapping() * @return Reference to self (for method chaining) * * See @ref Texture::setWrapping() for more information. */ CubeMapTexture& setWrapping(const Array2D<Sampler::Wrapping>& wrapping) { DataHelper<2>::setWrapping(*this, wrapping); return *this; } #ifndef MAGNUM_TARGET_WEBGL /** * @copybrief Texture::setBorderColor(const Color4&) * @return Reference to self (for method chaining) * * See @ref Texture::setBorderColor(const Color4&) for more * information. * @requires_es_extension Extension @es_extension{ANDROID,extension_pack_es31a}/ * @es_extension{EXT,texture_border_clamp} or * @es_extension{NV,texture_border_clamp} * @requires_gles Border clamp is not available in WebGL. */ CubeMapTexture& setBorderColor(const Color4& color) { AbstractTexture::setBorderColor(color); return *this; } #ifndef MAGNUM_TARGET_GLES2 /** * @copybrief Texture::setBorderColor(const Vector4ui&) * @return Reference to self (for method chaining) * * See @ref Texture::setBorderColor(const Vector4ui&) for more * information. * @requires_gl30 Extension @extension{EXT,texture_integer} * @requires_gles30 Not defined in OpenGL ES 2.0. * @requires_es_extension Extension * @es_extension{ANDROID,extension_pack_es31a}/ * @es_extension{EXT,texture_border_clamp} * @requires_gles Border clamp is not available in WebGL. */ CubeMapTexture& setBorderColor(const Vector4ui& color) { AbstractTexture::setBorderColor(color); return *this; } /** @overload * @requires_gl30 Extension @extension{EXT,texture_integer} * @requires_gles30 Not defined in OpenGL ES 2.0. * @requires_es_extension Extension * @es_extension{ANDROID,extension_pack_es31a}/ * @es_extension{EXT,texture_border_clamp} * @requires_gles Border clamp is not available in WebGL. */ CubeMapTexture& setBorderColor(const Vector4i& color) { AbstractTexture::setBorderColor(color); return *this; } #endif #endif /** * @copybrief Texture::setMaxAnisotropy() * @return Reference to self (for method chaining) * * See @ref Texture::setMaxAnisotropy() for more information. */ CubeMapTexture& setMaxAnisotropy(Float anisotropy) { AbstractTexture::setMaxAnisotropy(anisotropy); return *this; } #ifndef MAGNUM_TARGET_WEBGL /** * @copybrief Texture::setSRGBDecode() * @return Reference to self (for method chaining) * * See @ref Texture::setSRGBDecode() for more information. * @requires_extension Extension @extension{EXT,texture_sRGB_decode} * @requires_es_extension OpenGL ES 3.0 or extension * @es_extension{EXT,sRGB} and * @es_extension{ANDROID,extension_pack_es31a}/ * @es_extension2{EXT,texture_sRGB_decode,texture_sRGB_decode} * @requires_gles SRGB decode is not available in WebGL. */ CubeMapTexture& setSRGBDecode(bool decode) { AbstractTexture::setSRGBDecode(decode); return *this; } #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) /** * @copybrief Texture::setSwizzle() * @return Reference to self (for method chaining) * * See @ref Texture::setSwizzle() for more information. * @requires_gl33 Extension @extension{ARB,texture_swizzle} * @requires_gles30 Texture swizzle is not available in OpenGL ES 2.0. * @requires_gles Texture swizzle is not available in WebGL. */ template<char r, char g, char b, char a> CubeMapTexture& setSwizzle() { AbstractTexture::setSwizzle<r, g, b, a>(); return *this; } #endif #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) /** * @copybrief Texture::setCompareMode() * @return Reference to self (for method chaining) * * See @ref Texture::setCompareMode() for more information. * @requires_gles30 Extension @es_extension{EXT,shadow_samplers} and * @es_extension{NV,shadow_samplers_cube} in OpenGL ES 2.0. * @requires_webgl20 Depth texture comparison is not available in WebGL * 1.0. */ CubeMapTexture& setCompareMode(Sampler::CompareMode mode) { AbstractTexture::setCompareMode(mode); return *this; } /** * @copybrief Texture::setCompareFunction() * @return Reference to self (for method chaining) * * See @ref Texture::setCompareFunction() for more information. * @requires_gles30 Extension @es_extension{EXT,shadow_samplers} and * @es_extension{NV,shadow_samplers_cube} in OpenGL ES 2.0. * @requires_webgl20 Depth texture comparison is not available in WebGL * 1.0. */ CubeMapTexture& setCompareFunction(Sampler::CompareFunction function) { AbstractTexture::setCompareFunction(function); return *this; } #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) /** * @copybrief Texture::setDepthStencilMode() * @return Reference to self (for method chaining) * * See @ref Texture::setDepthStencilMode() for more information. * @requires_gl43 Extension @extension{ARB,stencil_texturing} * @requires_gles31 Stencil texturing is not available in OpenGL ES 3.0 * and older. * @requires_gles Stencil texturing is not available in WebGL. */ CubeMapTexture& setDepthStencilMode(Sampler::DepthStencilMode mode) { AbstractTexture::setDepthStencilMode(mode); return *this; } #endif /** * @copybrief Texture::setStorage() * @return Reference to self (for method chaining) * * See @ref Texture::setStorage() for more information. * @see @ref maxSize() */ CubeMapTexture& setStorage(Int levels, TextureFormat internalFormat, const Vector2i& size) { DataHelper<2>::setStorage(*this, levels, internalFormat, size); return *this; } #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) /** * @copybrief Texture::imageSize() * * If @extension{ARB,direct_state_access} (part of OpenGL 4.5) is not * available, it is assumed that faces have the same size and just the * size of @ref Coordinate::PositiveX face is queried. See * @ref Texture::imageSize() for more information. * @requires_gles31 Texture image size queries are not available in * OpenGL ES 3.0 and older. * @requires_gles Texture image size queries are not available in * WebGL. */ Vector2i imageSize(Int level); #ifdef MAGNUM_BUILD_DEPRECATED /** * @copybrief imageSize() * @deprecated Use @ref imageSize(Int) instead. */ CORRADE_DEPRECATED("use imageSize(Int) instead") Vector2i imageSize(Coordinate, Int level) { return imageSize(level); } #endif #endif #ifndef MAGNUM_TARGET_GLES /** * @brief Read given mip level of texture to image * * Image parameters like format and type of pixel data are taken from * given image, image size is taken from the texture using * @ref imageSize(). The storage is not reallocated if it is large * enough to contain the new data. * * The operation is protected from buffer overflow. * @see @fn_gl2{GetTextureLevelParameter,GetTexLevelParameter} with * @def_gl{TEXTURE_WIDTH}, @def_gl{TEXTURE_HEIGHT}, then * @fn_gl{PixelStore}, then @fn_gl2{GetTextureImage,GetTexImage} * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void image(Int level, Image3D& image); /** @overload * * Convenience alternative to the above, example usage: * @code * Image3D image = texture.image(0, {PixelFormat::RGBA, PixelType::UnsignedByte}); * @endcode */ Image3D image(Int level, Image3D&& image); /** * @brief Read given mip level of texture to buffer image * * See @ref image(Int, Image3D&) for more information. The storage is * not reallocated if it is large enough to contain the new data, which * means that @p usage might get ignored. * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void image(Int level, BufferImage3D& image, BufferUsage usage); /** @overload * * Convenience alternative to the above, example usage: * @code * BufferImage3D image = texture.image(0, {PixelFormat::RGBA, PixelType::UnsignedByte}, BufferUsage::StaticRead); * @endcode */ BufferImage3D image(Int level, BufferImage3D&& image, BufferUsage usage); /** * @brief Read given mip level of compressed texture to image * * Compression format and data size are taken from the texture, image * size is taken using @ref imageSize(). The storage is not reallocated * if it is large enough to contain the new data. * @see @fn_gl2{GetTextureLevelParameter,GetTexLevelParameter} with * @def_gl{TEXTURE_COMPRESSED_IMAGE_SIZE}, * @def_gl{TEXTURE_INTERNAL_FORMAT}, @def_gl{TEXTURE_WIDTH}, * @def_gl{TEXTURE_HEIGHT}, then * @fn_gl2{GetCompressedTextureImage,GetCompressedTexImage} * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void compressedImage(Int level, CompressedImage3D& image); /** @overload * * Convenience alternative to the above, example usage: * @code * CompressedImage3D image = texture.compressedImage(0, {}); * @endcode */ CompressedImage3D compressedImage(Int level, CompressedImage3D&& image); /** * @brief Read given mip level of compressed texture to buffer image * * See @ref compressedImage(Int, CompressedImage3D&) for more * information. The storage is not reallocated if it is large enough to * contain the new data, which means that @p usage might get ignored. * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void compressedImage(Int level, CompressedBufferImage3D& image, BufferUsage usage); /** @overload * * Convenience alternative to the above, example usage: * @code * CompressedBufferImage3D image = texture.compressedImage(0, {}, BufferUsage::StaticRead); * @endcode */ CompressedBufferImage3D compressedImage(Int level, CompressedBufferImage3D&& image, BufferUsage usage); /** * @brief Read given mip level and coordinate of texture to image * * Image parameters like format and type of pixel data are taken from * given image, image size is taken from the texture using * @ref imageSize(). The storage is not reallocated if it is large * enough to contain the new data. * * If neither @extension{ARB,get_texture_sub_image} (part of OpenGL * 4.5) nor @extension{EXT,direct_state_access} is available, the * texture is bound before the operation (if not already). If either * @extension{ARB,get_texture_sub_image} or @extension{ARB,robustness} * is available, the operation is protected from buffer overflow. * However, if @extension{ARB,get_texture_sub_image} is not available * and both @extension{EXT,direct_state_access} and * @extension{ARB,robustness} are available, the robust operation is * preferred over DSA. * @see @fn_gl2{GetTextureLevelParameter,GetTexLevelParameter}, * @fn_gl_extension{GetTextureLevelParameter,EXT,direct_state_access}, * eventually @fn_gl{ActiveTexture}, @fn_gl{BindTexture} and * @fn_gl{GetTexLevelParameter} with @def_gl{TEXTURE_WIDTH}, * @def_gl{TEXTURE_HEIGHT}, then @fn_gl{PixelStore}, then * @fn_gl{GetTextureSubImage}, @fn_gl_extension{GetnTexImage,ARB,robustness}, * @fn_gl_extension{GetTextureImage,EXT,direct_state_access}, * eventually @fn_gl{GetTexImage} * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void image(Coordinate coordinate, Int level, Image2D& image); /** @overload * * Convenience alternative to the above, example usage: * @code * Image2D image = texture.image(CubeMapTexture::Coordinate::PositiveX, 0, {PixelFormat::RGBA, PixelType::UnsignedByte}); * @endcode */ Image2D image(Coordinate coordinate, Int level, Image2D&& image); /** * @brief Read given mip level and coordinate of texture to buffer image * * See @ref image(Coordinate, Int, Image2D&) for more information. The * storage is not reallocated if it is large enough to contain the new * data, which means that @p usage might get ignored. * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void image(Coordinate coordinate, Int level, BufferImage2D& image, BufferUsage usage); /** @overload * * Convenience alternative to the above, example usage: * @code * BufferImage2D image = texture.image(CubeMapTexture::Coordinate::PositiveX, 0, {PixelFormat::RGBA, PixelType::UnsignedByte}, BufferUsage::StaticRead); * @endcode */ BufferImage2D image(Coordinate coordinate, Int level, BufferImage2D&& image, BufferUsage usage); /** * @brief Read given mip level and coordinate of compressed texture to image * * Compression format and data size are taken from the texture, image * size is taken using @ref imageSize(). The storage is not reallocated * if it is large enough to contain the new data. * * If neither @extension{ARB,get_texture_sub_image} (part of OpenGL * 4.5) nor @extension{EXT,direct_state_access} is available, the * texture is bound before the operation (if not already). If either * @extension{ARB,get_texture_sub_image} or @extension{ARB,robustness} * is available, the operation is protected from buffer overflow. * However, if @extension{ARB,get_texture_sub_image} is not available * and both @extension{EXT,direct_state_access} and * @extension{ARB,robustness} are available, the robust operation is * preferred over DSA. * @see @fn_gl2{GetTextureLevelParameter,GetTexLevelParameter}, * @fn_gl_extension{GetTextureLevelParameter,EXT,direct_state_access}, * eventually @fn_gl{GetTexLevelParameter} with * @def_gl{TEXTURE_COMPRESSED_IMAGE_SIZE}, * @def_gl{TEXTURE_INTERNAL_FORMAT}, @def_gl{TEXTURE_WIDTH}, * @def_gl{TEXTURE_HEIGHT}, then @fn_gl{PixelStore}, then * @fn_gl{GetCompressedTextureSubImage}, * @fn_gl_extension{GetnCompressedTexImage,ARB,robustness}, * @fn_gl_extension{GetCompressedTextureImage,EXT,direct_state_access}, * eventually @fn_gl{GetCompressedTexImage} * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void compressedImage(Coordinate coordinate, Int level, CompressedImage2D& image); /** @overload * * Convenience alternative to the above, example usage: * @code * CompressedImage2D image = texture.compressedImage(CubeMapTexture::Coordinate::PositiveX, 0, {}); * @endcode */ CompressedImage2D compressedImage(Coordinate coordinate, Int level, CompressedImage2D&& image); /** * @brief Read given mip level and coordinate of compressed texture to buffer image * * See @ref compressedImage(Coordinate, Int, CompressedImage2D&) for * more information. The storage is not reallocated if it is large * enough to contain the new data, which means that @p usage might get * ignored. * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void compressedImage(Coordinate coordinate, Int level, CompressedBufferImage2D& image, BufferUsage usage); /** @overload * * Convenience alternative to the above, example usage: * @code * CompressedBufferImage2D image = texture.compressedImage(CubeMapTexture::Coordinate::PositiveX, 0, {}, BufferUsage::StaticRead); * @endcode */ CompressedBufferImage2D compressedImage(Coordinate coordinate, Int level, CompressedBufferImage2D&& image, BufferUsage usage); /** * @copybrief Texture::subImage(Int, const RangeTypeFor<dimensions, Int>&, Image&) * * See @ref Texture::subImage(Int, const RangeTypeFor<dimensions, Int>&, Image&) * for more information. * @requires_gl45 Extension @extension{ARB,get_texture_sub_image} * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void subImage(Int level, const Range3Di& range, Image3D& image) { AbstractTexture::subImage<3>(level, range, image); } /** @overload * * Convenience alternative to the above, example usage: * @code * Image3D image = texture.subImage(0, range, {PixelFormat::RGBA, PixelType::UnsignedByte}); * @endcode */ Image3D subImage(Int level, const Range3Di& range, Image3D&& image); /** * @copybrief Texture::subImage(Int, const RangeTypeFor<dimensions, Int>&, BufferImage&, BufferUsage) * * See @ref Texture::subImage(Int, const RangeTypeFor<dimensions, Int>&, BufferImage&, BufferUsage) * for more information. * @requires_gl45 Extension @extension{ARB,get_texture_sub_image} * @requires_gl Texture image queries are not available in OpenGL ES or * WebGL. See @ref Framebuffer::read() for possible workaround. */ void subImage(Int level, const Range3Di& range, BufferImage3D& image, BufferUsage usage) { AbstractTexture::subImage<3>(level, range, image, usage); } /** @overload * * Convenience alternative to the above, example usage: * @code * BufferImage3D image = texture.subImage(0, range, {PixelFormat::RGBA, PixelType::UnsignedByte}, BufferUsage::StaticRead); * @endcode */ BufferImage3D subImage(Int level, const Range3Di& range, BufferImage3D&& image, BufferUsage usage); #endif /** * @copybrief Texture::setImage() * @return Reference to self (for method chaining) * * See @ref Texture::setImage() for more information. * @see @ref maxSize() * @deprecated_gl Prefer to use @ref setStorage() and @ref setSubImage() * instead. */ CubeMapTexture& setImage(Coordinate coordinate, Int level, TextureFormat internalFormat, const ImageView2D& image) { DataHelper<2>::setImage(*this, GLenum(coordinate), level, internalFormat, image); return *this; } #ifndef MAGNUM_TARGET_GLES2 /** @overload * @requires_gles30 Pixel buffer objects are not available in OpenGL ES * 2.0. * @requires_webgl20 Pixel buffer objects are not available in WebGL * 1.0. * @deprecated_gl Prefer to use @ref setStorage() and @ref setSubImage() * instead. */ CubeMapTexture& setImage(Coordinate coordinate, Int level, TextureFormat internalFormat, BufferImage2D& image) { DataHelper<2>::setImage(*this, GLenum(coordinate), level, internalFormat, image); return *this; } /** @overload * @requires_gles30 Pixel buffer objects are not available in OpenGL ES * 2.0. * @requires_webgl20 Pixel buffer objects are not available in WebGL * 1.0. * @deprecated_gl Prefer to use @ref setStorage() and @ref setSubImage() * instead. */ CubeMapTexture& setImage(Coordinate coordinate, Int level, TextureFormat internalFormat, BufferImage2D&& image) { return setImage(coordinate, level, internalFormat, image); } #endif /** * @copybrief Texture::setCompressedImage() * @return Reference to self (for method chaining) * * See @ref Texture::setCompressedImage() for more information. * @see @ref maxSize() * @deprecated_gl Prefer to use @ref setStorage() and * @ref setCompressedSubImage() instead. */ CubeMapTexture& setCompressedImage(Coordinate coordinate, Int level, const CompressedImageView2D& image) { DataHelper<2>::setCompressedImage(*this, GLenum(coordinate), level, image); return *this; } #ifndef MAGNUM_TARGET_GLES2 /** @overload * @requires_gles30 Pixel buffer objects are not available in OpenGL ES * 2.0. * @requires_webgl20 Pixel buffer objects are not available in WebGL * 1.0. * @deprecated_gl Prefer to use @ref setStorage() and * @ref setCompressedSubImage() instead. */ CubeMapTexture& setCompressedImage(Coordinate coordinate, Int level, CompressedBufferImage2D& image) { DataHelper<2>::setCompressedImage(*this, GLenum(coordinate), level, image); return *this; } /** @overload * @requires_gles30 Pixel buffer objects are not available in OpenGL ES * 2.0. * @requires_webgl20 Pixel buffer objects are not available in WebGL * 1.0. * @deprecated_gl Prefer to use @ref setStorage() and * @ref setCompressedSubImage() instead. */ CubeMapTexture& setCompressedImage(Coordinate coordinate, Int level, CompressedBufferImage2D&& image) { return setCompressedImage(coordinate, level, image); } #endif #ifndef MAGNUM_TARGET_GLES /** * @brief Set image subdata * @param level Mip level * @param offset Offset where to put data in the texture * @param image @ref Image3D, @ref ImageView3D or * @ref Trade::ImageData3D * @return Reference to self (for method chaining) * * @see @ref setStorage(), @fn_gl2{TextureSubImage3D,TexSubImage3D} * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl In OpenGL ES and WebGL you need to set image for each * face separately. */ CubeMapTexture& setSubImage(Int level, const Vector3i& offset, const ImageView3D& image); /** @overload * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl In OpenGL ES and WebGL you need to set image for each * face separately. */ CubeMapTexture& setSubImage(Int level, const Vector3i& offset, BufferImage3D& image); /** @overload * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl In OpenGL ES and WebGL you need to set image for each * face separately. */ CubeMapTexture& setSubImage(Int level, const Vector3i& offset, BufferImage3D&& image) { return setSubImage(level, offset, image); } /** * @brief Set compressed image subdata * @param level Mip level * @param offset Offset where to put data in the texture * @param image @ref CompressedImage3D, @ref CompressedImageView3D * or compressed @ref Trade::ImageData3D * @return Reference to self (for method chaining) * * @see @ref setStorage(), @fn_gl2{CompressedTextureSubImage3D,CompressedTexSubImage3D} * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl In OpenGL ES and WebGL you need to set image for each * face separately. */ CubeMapTexture& setCompressedSubImage(Int level, const Vector3i& offset, const CompressedImageView3D& image); /** @overload * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl In OpenGL ES and WebGL you need to set image for each * face separately. */ CubeMapTexture& setCompressedSubImage(Int level, const Vector3i& offset, CompressedBufferImage3D& image); /** @overload * @requires_gl45 Extension @extension{ARB,direct_state_access} * @requires_gl In OpenGL ES and WebGL you need to set image for each * face separately. */ CubeMapTexture& setCompressedSubImage(Int level, const Vector3i& offset, CompressedBufferImage3D&& image) { return setCompressedSubImage(level, offset, image); } #endif /** * @copybrief Texture::setSubImage() * @return Reference to self (for method chaining) * * See @ref Texture::setSubImage() for more information. */ CubeMapTexture& setSubImage(Coordinate coordinate, Int level, const Vector2i& offset, const ImageView2D& image); #ifndef MAGNUM_TARGET_GLES2 /** @overload * @requires_gles30 Pixel buffer objects are not available in OpenGL ES * 2.0. * @requires_webgl20 Pixel buffer objects are not available in WebGL * 1.0. */ CubeMapTexture& setSubImage(Coordinate coordinate, Int level, const Vector2i& offset, BufferImage2D& image); /** @overload * @requires_gles30 Pixel buffer objects are not available in OpenGL ES * 2.0. * @requires_webgl20 Pixel buffer objects are not available in WebGL * 1.0. */ CubeMapTexture& setSubImage(Coordinate coordinate, Int level, const Vector2i& offset, BufferImage2D&& image) { return setSubImage(coordinate, level, offset, image); } #endif /** * @copybrief Texture::setCompressedSubImage() * @return Reference to self (for method chaining) * * See @ref Texture::setCompressedSubImage() for more information. */ CubeMapTexture& setCompressedSubImage(Coordinate coordinate, Int level, const Vector2i& offset, const CompressedImageView2D& image); #ifndef MAGNUM_TARGET_GLES2 /** @overload * @requires_gles30 Pixel buffer objects are not available in OpenGL ES * 2.0. * @requires_webgl20 Pixel buffer objects are not available in WebGL * 1.0. */ CubeMapTexture& setCompressedSubImage(Coordinate coordinate, Int level, const Vector2i& offset, CompressedBufferImage2D& image); /** @overload * @requires_gles30 Pixel buffer objects are not available in OpenGL ES * 2.0. * @requires_webgl20 Pixel buffer objects are not available in WebGL * 1.0. */ CubeMapTexture& setCompressedSubImage(Coordinate coordinate, Int level, const Vector2i& offset, CompressedBufferImage2D&& image) { return setCompressedSubImage(coordinate, level, offset, image); } #endif /** * @copybrief Texture::generateMipmap() * @return Reference to self (for method chaining) * * See @ref Texture::generateMipmap() for more information. * @requires_gl30 Extension @extension{ARB,framebuffer_object} */ CubeMapTexture& generateMipmap() { AbstractTexture::generateMipmap(); return *this; } /** * @copybrief Texture::invalidateImage() * * See @ref Texture::invalidateImage() for more information. */ void invalidateImage(Int level) { AbstractTexture::invalidateImage(level); } /** * @copybrief Texture::invalidateSubImage() * * Z coordinate is equivalent to number of texture face, i.e. * @ref Coordinate::PositiveX is `0` and so on, in the same order as in * the enum. * * See @ref Texture::invalidateSubImage() for more information. */ void invalidateSubImage(Int level, const Vector3i& offset, const Vector3i& size) { DataHelper<3>::invalidateSubImage(*this, level, offset, size); } /* Overloads to remove WTF-factor from method chaining order */ #if !defined(DOXYGEN_GENERATING_OUTPUT) && !defined(MAGNUM_TARGET_WEBGL) CubeMapTexture& setLabel(const std::string& label) { AbstractTexture::setLabel(label); return *this; } template<std::size_t size> CubeMapTexture& setLabel(const char(&label)[size]) { AbstractTexture::setLabel<size>(label); return *this; } #endif private: explicit CubeMapTexture(GLuint id, ObjectFlags flags) noexcept: AbstractTexture{id, GL_TEXTURE_CUBE_MAP, flags} {} #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) Vector2i MAGNUM_LOCAL getImageSizeImplementationDefault(Int level); #ifndef MAGNUM_TARGET_GLES Vector2i MAGNUM_LOCAL getImageSizeImplementationDSA(Int level); Vector2i MAGNUM_LOCAL getImageSizeImplementationDSAEXT(Int level); #endif #endif #ifndef MAGNUM_TARGET_GLES void MAGNUM_LOCAL getImageImplementationDefault(Coordinate coordinate, GLint level, const Vector2i& size, PixelFormat format, PixelType type, std::size_t dataSize, GLvoid* data); void MAGNUM_LOCAL getImageImplementationDSA(Coordinate coordinate, GLint level, const Vector2i& size, PixelFormat format, PixelType type, std::size_t dataSize, GLvoid* data); void MAGNUM_LOCAL getImageImplementationDSAEXT(Coordinate coordinate, GLint level, const Vector2i& size, PixelFormat format, PixelType type, std::size_t dataSize, GLvoid* data); void MAGNUM_LOCAL getImageImplementationRobustness(Coordinate coordinate, GLint level, const Vector2i& size, PixelFormat format, PixelType type, std::size_t dataSize, GLvoid* data); void MAGNUM_LOCAL getCompressedImageImplementationDefault(Coordinate coordinate, GLint level, const Vector2i& size, std::size_t dataSize, GLvoid* data); void MAGNUM_LOCAL getCompressedImageImplementationDSA(Coordinate coordinate, GLint level, const Vector2i& size, std::size_t dataSize, GLvoid* data); void MAGNUM_LOCAL getCompressedImageImplementationDSAEXT(Coordinate coordinate, GLint level, const Vector2i& size, std::size_t dataSize, GLvoid* data); void MAGNUM_LOCAL getCompressedImageImplementationRobustness(Coordinate coordinate, GLint level, const Vector2i& size, std::size_t dataSize, GLvoid* data); #endif void MAGNUM_LOCAL subImageImplementationDefault(Coordinate coordinate, GLint level, const Vector2i& offset, const Vector2i& size, PixelFormat format, PixelType type, const GLvoid* data); #ifndef MAGNUM_TARGET_GLES void MAGNUM_LOCAL subImageImplementationDSA(Coordinate coordinate, GLint level, const Vector2i& offset, const Vector2i& size, PixelFormat format, PixelType type, const GLvoid* data); void MAGNUM_LOCAL subImageImplementationDSAEXT(Coordinate coordinate, GLint level, const Vector2i& offset, const Vector2i& size, PixelFormat format, PixelType type, const GLvoid* data); #endif void MAGNUM_LOCAL compressedSubImageImplementationDefault(Coordinate coordinate, GLint level, const Vector2i& offset, const Vector2i& size, CompressedPixelFormat format, const GLvoid* data, GLsizei dataSize); #ifndef MAGNUM_TARGET_GLES void MAGNUM_LOCAL compressedSubImageImplementationDSA(Coordinate coordinate, GLint level, const Vector2i& offset, const Vector2i& size, CompressedPixelFormat format, const GLvoid* data, GLsizei dataSize); void MAGNUM_LOCAL compressedSubImageImplementationDSAEXT(Coordinate coordinate, GLint level, const Vector2i& offset, const Vector2i& size, CompressedPixelFormat format, const GLvoid* data, GLsizei dataSize); #endif }; } #endif
[ "mosra@centrum.cz" ]
mosra@centrum.cz
c411b56c096268d9cea0779ba42b13360df8c24c
37ea674fee99e751a1d5564b9af1e085fb1f6aef
/src/process_image.cpp
3ab04169bab0212a39924d6258023b93eeae47f0
[]
no_license
santroma1/ball_chaser
099531cba951a11f72bf5201001dacc697ed979b
b06f09d57ac8f10ab83a296b7ea360557759e64c
refs/heads/master
2022-11-17T11:20:34.790747
2020-07-14T18:27:32
2020-07-14T18:27:32
279,660,219
0
0
null
null
null
null
UTF-8
C++
false
false
3,053
cpp
#include "ros/ros.h" #include "ball_chaser/DriveToTarget.h" #include <sensor_msgs/Image.h> #include <ros/console.h> #include <string.h> class ProcessImage { public: ProcessImage() { client = n.serviceClient<ball_chaser::DriveToTarget>("/ball_chaser/command_robot"); image_sub = n.subscribe("/camera/rgb/image_raw", 10, &ProcessImage::process_image_callback, this); } // This function calls the command_robot service to drive the robot in the specified direction void drive_robot(float lin_x, float ang_z) { // TODO: Request a service and pass the velocities to it to drive the robot ball_chaser::DriveToTarget srv; srv.request.linear_x = lin_x; srv.request.angular_z = ang_z; if (!client.call(srv)) ROS_ERROR("Failed to call service safe_move"); } void process_image_callback(const sensor_msgs::Image img) { int white_pixel = 255; int left_counter = 0; int middle_counter = 0; int right_counter = 0; int total_counter = 0; // TODO: Loop through each pixel in the image and check if there's a bright white one for(int i = 0; i<img.height*img.step;i+=3) { if(img.data[i] == white_pixel && img.data[i+1] == white_pixel && img.data[i+2] == white_pixel) { // Then, identify if this pixel falls in the left, mid, or right side of the image int position = i%img.step; total_counter++; if(position < img.step/3) { left_counter++; } else if(position >= img.step/3 && position<((img.step*2)/3)) { middle_counter++; }else { right_counter++; } } // Depending on the white ball position, call the drive_bot function and pass velocities to it // Request a stop when there's no white ball seen by the camera } if(left_counter> middle_counter && left_counter >right_counter) { drive_robot(0.2, 0.5); }else if(middle_counter > left_counter && middle_counter > right_counter) { drive_robot(0.2, 0.0); }else if(right_counter > middle_counter && right_counter > left_counter) { drive_robot(0.2, -0.5); } if(total_counter > (img.height*img.step)/12) { drive_robot(0.0, 0.0); } if(left_counter == 0 && right_counter == 0 && middle_counter == 0) { drive_robot(0.0, 0.0); } } private: ros::NodeHandle n; ros::Subscriber image_sub; ros::ServiceClient client; }; int main(int argc, char** argv) { //initialize node ros::init(argc, argv, "process_image"); ProcessImage process_image; ROS_INFO("CAMERA READY"); //HANDLE ROS COMmunication events ros::spin(); return 0; }
[ "santroma1@gmail.com" ]
santroma1@gmail.com
846f8837ee2c551083d54ed61d35d361431e52a7
0397dc3ade646ae5e9a001aca5528fea3371fafe
/10.cpp
a96f83696171f6871b8da0e4da5246d01d5b6049
[]
no_license
MakinoRuki/LeetCode
51e0289769a7091f1d4b0854b22d04e0c702e799
eab700635f65a6f02b6933733429602f8f74491a
refs/heads/master
2022-03-04T06:27:35.983043
2019-10-20T05:09:01
2019-10-20T05:09:01
104,713,887
0
0
null
null
null
null
UTF-8
C++
false
false
1,251
cpp
class Solution { public: int dp[1000][1000]; bool dfs(string& s, int si, string& p, int pi) { if (dp[si][pi] >= 0) return dp[si][pi]; if (si == s.size()) { if (pi == p.size()) return dp[si][pi] = 1; int i = pi; while (i < p.size()) { if (p[i] != '*') { if (i + 1 < p.size() && p[i + 1] == '*') i++; else return dp[si][pi] = 0; } else { i++; } } return dp[si][pi] = 1; } else { if (pi == p.size()) { return dp[si][pi] = 0; } if (pi + 1 < p.size() && p[pi + 1] == '*') { if (dfs(s, si, p, pi + 2)) return dp[si][pi] = 1; if ((s[si] == p[pi] || p[pi] == '.') && dfs(s, si + 1, p, pi)) return dp[si][pi] = 1; return dp[si][pi] = 0; } else { if (s[si] == p[pi] || p[pi] == '.') return dp[si][pi] = dfs(s, si + 1, p, pi + 1); return dp[si][pi] = 0; } } } bool isMatch(string s, string p) { memset(dp, -1, sizeof(dp)); dfs(s, 0, p, 0); return dp[0][0]; } };
[ "noreply@github.com" ]
MakinoRuki.noreply@github.com
9e10be6919974c5e0cef8dceb5de777316975560
1e1b3e4c8113190175a9d7e17c68ca810c1237be
/IntegerFactorization.cpp
9f8c10dd54c8f525985a17fa6b13e8fbc2245488
[]
no_license
DionysiosB/CodeAbbey
f591908d45cedfa0d351300643dc87cf3d532a69
d997686c55d7bbfdabf90123eced991721ddc8a7
refs/heads/master
2021-01-18T23:06:18.775840
2016-05-25T09:49:02
2016-05-25T09:49:02
48,652,944
0
0
null
null
null
null
UTF-8
C++
false
false
489
cpp
#include <iostream> #include <vector> int main(){ int t; std::cin >> t; while(t--){ long x; std::cin >> x; long div(2); std::vector<long> divisors; while(x > 1){ if(x % div == 0){x /= div; divisors.push_back(div);} else{++div;} } for(int p = 0; p < divisors.size() - 1; p++){std::cout << divisors[p] << "*";} std::cout << divisors.back() << " "; } std::cout << std::endl; return 0; }
[ "barmpoutis@gmail.com" ]
barmpoutis@gmail.com
c23c10706e3fc31c56bde8fd5b2e25a06781e8c5
77cf860172de4e72afd39799c45ad82d7652b23d
/Chapter 1/1.3.cpp
70a65bc7518c8106a400a8f0800091d6c8aab23d
[]
no_license
roycefanproxy/CPP_Primer_5th
ed8c515ff27ed304c71668899a7f3fea65a302e8
449191713d449eb24be394103b73e2b417d52973
refs/heads/master
2021-05-31T08:26:41.242545
2016-01-24T16:33:22
2016-01-24T16:33:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
89
cpp
#include <iostream> int main() { std::cout<<"Hello World !"<<std::endl; return 0; }
[ "fchunhuei@gmail.com" ]
fchunhuei@gmail.com
825994b86335c565781b6f3249ab34833f8355f6
eaee32f3bebb3505835141644ec7a76ae5f4e523
/Dumper/utils.cpp
23385d42e22379feae5d4ce337270f7049e2bd32
[]
no_license
Milxnor/UnrealDumper-4.25
28bdf0ae309324b9e7bcb8a971aecf1f69467394
f3d717d5bbbf37c96c1ab865b9ccffa87be1a87d
refs/heads/main
2023-08-19T12:14:02.098646
2021-10-15T00:17:25
2021-10-15T00:17:25
401,733,388
2
1
null
2021-08-31T14:27:58
2021-08-31T14:27:57
null
UTF-8
C++
false
false
2,648
cpp
#include <windows.h> #include <TlHelp32.h> #include <psapi.h> #include "utils.h" uint32 GetProcessId(std::wstring name) { uint32 pid = 0; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot != INVALID_HANDLE_VALUE) { PROCESSENTRY32W entry = {sizeof(entry)}; while (Process32NextW(snapshot, &entry)) { if (name == entry.szExeFile) { pid = entry.th32ProcessID; break; } } CloseHandle(snapshot); } return pid; } std::pair<uint8*, uint32> GetModuleInfo(uint32 pid, std::wstring name) { std::pair<uint8*, uint32> info; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid); if (snapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32W modEntry = {sizeof(modEntry)}; while (Module32NextW(snapshot, &modEntry)) { if (name == modEntry.szModule) { info = {modEntry.modBaseAddr, modEntry.modBaseSize}; break; } } } return info; } bool Compare(uint8* data, uint8 *sig, uint32 size) { for (uint32 i = 0; i < size; i++) { if (data[i] != sig[i] && sig[i] != 0x00) { return false; } } return true; } uint8* FindSignature(uint8* start, uint8* end, const char* sig, uint32 size) { for (uint8* it = start; it < end - size; it++) { if (Compare(it, (uint8*)sig, size)) { return it; }; } return nullptr; } void* FindPointer(uint8* start, uint8* end, const char* sig, uint32 size, int32 addition) { uint8* address = FindSignature(start, end, sig, size); if (!address) return nullptr; int32 k = 0; for (; sig[k]; k++); int32 offset = *(int32*)(address + k); return address + k + 4 + offset + addition; } std::vector<std::pair<uint8*, uint8*>> GetExSections(void* data) { std::vector<std::pair<uint8*, uint8*>> sections; auto dos = (PIMAGE_DOS_HEADER)data; auto nt = (PIMAGE_NT_HEADERS)((uint8*)data + dos->e_lfanew); auto s = IMAGE_FIRST_SECTION(nt); for (auto i = 0; i < nt->FileHeader.NumberOfSections; i++, s++) { if (s->Characteristics & IMAGE_SCN_CNT_CODE) { auto start = (uint8*)data + s->PointerToRawData; auto end = start + s->SizeOfRawData; sections.push_back({start, end}); } } return sections; } uint32 GetProccessPath(uint32 pid, wchar_t* processName, uint32 size) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); if (!QueryFullProcessImageNameW(hProcess, 0, processName, (DWORD*)(&size))) { size = 0; }; CloseHandle(hProcess); return size; } extern "C" NTSTATUS NtQuerySystemTime(uint64* SystemTime); uint64 GetTime() { uint64 ret; NtQuerySystemTime(&ret); return ret; }
[ "vianove13@yandex.ru" ]
vianove13@yandex.ru
58b56e106201553659b58120e8e043314fa908f7
924049378ea1e986b5b2f09c7c99ee5577b4675e
/src/qt/receivecoinsdialog.cpp
ba336a2ab6bf0c9639a17713585034088471b831
[ "MIT" ]
permissive
wincash/WincashGold
06bc94246b23d1931076067b2b8ef509d2fb6541
ff5935c021acde8b78d10cff7dce2fcfadc3518a
refs/heads/master
2022-11-22T00:45:47.164233
2020-07-20T22:20:57
2020-07-20T22:20:57
271,636,521
1
0
null
null
null
null
UTF-8
C++
false
false
10,717
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2017-2018 The WINCASHGOLD developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "receivecoinsdialog.h" #include "ui_receivecoinsdialog.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "receiverequestdialog.h" #include "recentrequeststablemodel.h" #include "walletmodel.h" #include <QAction> #include <QCursor> #include <QItemSelection> #include <QMessageBox> #include <QScrollBar> #include <QTextDocument> #include <QSettings> ReceiveCoinsDialog::ReceiveCoinsDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::ReceiveCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->clearButton->setIcon(QIcon()); ui->receiveButton->setIcon(QIcon()); ui->receivingAddressesButton->setIcon(QIcon()); ui->showRequestButton->setIcon(QIcon()); ui->removeRequestButton->setIcon(QIcon()); #endif // context menu actions QAction* copyLabelAction = new QAction(tr("Copy label"), this); QAction* copyMessageAction = new QAction(tr("Copy message"), this); QAction* copyAmountAction = new QAction(tr("Copy amount"), this); QAction* copyAddressAction = new QAction(tr("Copy address"), this); // context menu contextMenu = new QMenu(); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyMessageAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyAddressAction); // context menu signals connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); } void ReceiveCoinsDialog::setModel(WalletModel* model) { this->model = model; if (model && model->getOptionsModel()) { model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); QTableView* tableView = ui->recentRequestsView; tableView->verticalHeader()->hide(); tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); tableView->setModel(model->getRecentRequestsTableModel()); tableView->setAlternatingRowColors(true); tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->setSelectionMode(QAbstractItemView::ContiguousSelection); tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH); tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH); connect(tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection))); // Last 2 columns are set by the columnResizingFixer, when the table geometry is ready. columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH); // Init address field QSettings settings; address = settings.value("current_receive_address").toString(); if (address.isEmpty()) address = getAddress(); ui->reqAddress->setText(address); connect(model, SIGNAL(notifyReceiveAddressChanged()), this, SLOT(receiveAddressUsed())); } } ReceiveCoinsDialog::~ReceiveCoinsDialog() { QSettings settings; settings.setValue("current_receive_address", address); delete ui; } void ReceiveCoinsDialog::clear() { ui->reqAmount->clear(); ui->reqAddress->setText(address); ui->reqLabel->setText(""); ui->reqMessage->setText(""); ui->reuseAddress->setChecked(false); updateDisplayUnit(); } void ReceiveCoinsDialog::reject() { clear(); } void ReceiveCoinsDialog::accept() { clear(); } void ReceiveCoinsDialog::updateDisplayUnit() { if (model && model->getOptionsModel()) { ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } QString ReceiveCoinsDialog::getAddress(QString label) { if (ui->reuseAddress->isChecked()) { /* Choose existing receiving address */ AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { return dlg.getReturnValue(); } else { return ""; } } else { /* Generate new receiving address */ return model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, ""); } } void ReceiveCoinsDialog::on_receiveButton_clicked() { if (!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel()) return; QString label = ui->reqLabel->text(); address = getAddress(label); if (address.isEmpty()) return; if (ui->reuseAddress->isChecked() && label.isEmpty()) { label = model->getAddressTableModel()->labelForAddress(address); } SendCoinsRecipient info(address, label, ui->reqAmount->value(), ui->reqMessage->text()); ReceiveRequestDialog* dialog = new ReceiveRequestDialog(this); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModel(model->getOptionsModel()); dialog->setInfo(info); dialog->show(); clear(); /* Store request for later reference */ model->getRecentRequestsTableModel()->addNewRequest(info); } void ReceiveCoinsDialog::on_receivingAddressesButton_clicked() { if (!model) return; AddressBookPage dlg(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); dlg.exec(); } void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex& index) { const RecentRequestsTableModel* submodel = model->getRecentRequestsTableModel(); ReceiveRequestDialog* dialog = new ReceiveRequestDialog(this); dialog->setModel(model->getOptionsModel()); dialog->setInfo(submodel->entry(index.row()).recipient); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { // Enable Show/Remove buttons only if anything is selected. bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty(); ui->showRequestButton->setEnabled(enable); ui->removeRequestButton->setEnabled(enable); } void ReceiveCoinsDialog::on_showRequestButton_clicked() { if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); foreach (QModelIndex index, selection) { on_recentRequestsView_doubleClicked(index); } } void ReceiveCoinsDialog::on_removeRequestButton_clicked() { if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if (selection.empty()) return; // correct for selection mode ContiguousSelection QModelIndex firstIndex = selection.at(0); model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent()); } // We override the virtual resizeEvent of the QWidget to adjust tables column // sizes as the tables width is proportional to the dialogs width. void ReceiveCoinsDialog::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message); } void ReceiveCoinsDialog::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Return) { // press return -> submit form if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus()) { event->ignore(); on_receiveButton_clicked(); return; } } this->QDialog::keyPressEvent(event); } // copy column of selected row to clipboard void ReceiveCoinsDialog::copyColumnToClipboard(int column) { if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if (selection.empty()) return; // correct for selection mode ContiguousSelection QModelIndex firstIndex = selection.at(0); GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString()); } // context menu void ReceiveCoinsDialog::showMenu(const QPoint& point) { if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if (selection.empty()) return; contextMenu->exec(QCursor::pos()); } // context menu action: copy label void ReceiveCoinsDialog::copyLabel() { copyColumnToClipboard(RecentRequestsTableModel::Label); } // context menu action: copy message void ReceiveCoinsDialog::copyMessage() { copyColumnToClipboard(RecentRequestsTableModel::Message); } // context menu action: copy amount void ReceiveCoinsDialog::copyAmount() { copyColumnToClipboard(RecentRequestsTableModel::Amount); } // context menu action: copy address void ReceiveCoinsDialog::copyAddress() { copyColumnToClipboard(RecentRequestsTableModel::Address); } void ReceiveCoinsDialog::receiveAddressUsed() { if ((!ui->reuseAddress->isChecked()) && model && model->isUsed(CBitcoinAddress(address.toStdString()))) { address = getAddress(); clear(); } }
[ "52337058+wincash@users.noreply.github.com" ]
52337058+wincash@users.noreply.github.com
f286284a69cfc41ee4556b39f5c8206d34c39465
13ca0b6930f9c17684d0065c0dab34bfd1e0cca1
/include/ircd/ctx/this_ctx.h
ebae88bab8f326148757b1b83260a0f6f2b0ff68
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
InspectorDidi/construct
064ea432c30a71a5e0ba100e623d334418234588
64a5eec565ab8664a010de31ba72a569206f3eef
refs/heads/master
2020-07-03T13:57:32.453475
2019-08-09T02:58:44
2019-08-09T03:01:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,721
h
// Matrix Construct // // Copyright (C) Matrix Construct Developers, Authors & Contributors // Copyright (C) 2016-2018 Jason Volk <jason@zemos.net> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice is present in all copies. The // full license for this software is available in the LICENSE file. #pragma once #define HAVE_IRCD_CTX_THIS_CTX_H /// Interface to the currently running context namespace ircd::ctx { inline namespace this_ctx { struct ctx &cur() noexcept; ///< Assumptional reference to *current const uint64_t &id(); // Unique ID for cur ctx string_view name(); // Optional label for cur ctx ulong cycles() noexcept; // misc profiling related bool interruption_requested() noexcept; // interruption(cur()) void interruption_point(); // throws if interruption_requested() void wait(); // Returns when context is woken up. void yield(); // Allow other contexts to run before returning. // Return remaining time if notified; or <= 0 if not, and timeout thrown on throw overloads microseconds wait(const microseconds &, const std::nothrow_t &); template<class E, class duration> nothrow_overload<E, duration> wait(const duration &); template<class E = timeout, class duration> throw_overload<E, duration> wait(const duration &); // Returns false if notified; true if time point reached, timeout thrown on throw_overloads bool wait_until(const steady_point &tp, const std::nothrow_t &); template<class E> nothrow_overload<E, bool> wait_until(const steady_point &tp); template<class E = timeout> throw_overload<E> wait_until(const steady_point &tp); // Ignores notes. Throws if interrupted. void sleep_until(const steady_point &tp); template<class duration> void sleep(const duration &); void sleep(const int &secs); }} namespace ircd::ctx { /// Points to the currently running context or null for main stack (do not modify) extern __thread ctx *current; } /// This overload matches ::sleep() and acts as a drop-in for ircd contexts. /// interruption point. inline void ircd::ctx::this_ctx::sleep(const int &secs) { sleep(seconds(secs)); } /// Yield the context for a period of time and ignore notifications. sleep() /// is like wait() but it only returns after the timeout and not because of a /// note. /// interruption point. template<class duration> void ircd::ctx::this_ctx::sleep(const duration &d) { sleep_until(steady_clock::now() + d); } /// Wait for a notification until a point in time. If there is a notification /// then context continues normally. If there's never a notification then an /// exception (= timeout) is thrown. /// interruption point. template<class E> ircd::throw_overload<E> ircd::ctx::this_ctx::wait_until(const steady_point &tp) { if(wait_until<std::nothrow_t>(tp)) throw E{}; } /// Wait for a notification until a point in time. If there is a notification /// then returns true. If there's never a notification then returns false. /// interruption point. this is not noexcept. template<class E> ircd::nothrow_overload<E, bool> ircd::ctx::this_ctx::wait_until(const steady_point &tp) { return wait_until(tp, std::nothrow); } /// Wait for a notification for at most some amount of time. If the duration is /// reached without a notification then E (= timeout) is thrown. Otherwise, /// returns the time remaining on the duration. /// interruption point template<class E, class duration> ircd::throw_overload<E, duration> ircd::ctx::this_ctx::wait(const duration &d) { const auto ret { wait<std::nothrow_t>(d) }; return ret <= duration(0)? throw E{}: ret; } /// Wait for a notification for some amount of time. This function returns /// when a context is notified. It always returns the duration remaining which /// will be <= 0 to indicate a timeout without notification. /// interruption point. this is not noexcept. template<class E, class duration> ircd::nothrow_overload<E, duration> ircd::ctx::this_ctx::wait(const duration &d) { const auto ret { wait(duration_cast<microseconds>(d), std::nothrow) }; return duration_cast<duration>(ret); } inline ulong ircd::ctx::this_ctx::cycles() noexcept { return cycles(cur()) + prof::cur_slice_cycles(); } /// Reference to the currently running context. Call if you expect to be in a /// context. Otherwise use the ctx::current pointer. inline ircd::ctx::ctx & ircd::ctx::this_ctx::cur() noexcept { assert(current); return *current; }
[ "jason@zemos.net" ]
jason@zemos.net
207ce0a59a4464a9273d9791163845c5b5ae7378
41579ed1d70b6f9dc25aff9e21eed36b63e86e4e
/build/generated/AndroidaudiostreamerBootstrap.cpp
68b2cf61cc831d86c17479261a62cc45d15b0957
[]
no_license
trevorf/ti-android-streamer
5f30203f84c87d16dcfda1d8ea5d42b1a41df6c9
9331c4f92e9210f526cd8675e517ea2877c2f15b
refs/heads/master
2021-01-21T05:03:06.052570
2015-10-06T08:24:46
2015-10-06T08:24:46
41,795,332
10
9
null
2016-04-28T12:25:09
2015-09-02T10:33:24
Makefile
UTF-8
C++
false
false
3,198
cpp
/** * Appcelerator Titanium Mobile * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. * * Warning: This file is GENERATED, and should not be modified */ #include <jni.h> #include <v8.h> #include <AndroidUtil.h> #include <KrollBindings.h> #include <V8Util.h> #include "BootstrapJS.cpp" #include "KrollGeneratedBindings.cpp" #define TAG "com.woohoo.androidaudiostreamer" using namespace v8; static Persistent<Object> bindingCache; static Handle<Value> Androidaudiostreamer_getBinding(const Arguments& args) { HandleScope scope; if (args.Length() == 0) { return ThrowException(Exception::Error(String::New("Androidaudiostreamer.getBinding requires 1 argument: binding"))); } if (bindingCache.IsEmpty()) { bindingCache = Persistent<Object>::New(Object::New()); } Handle<String> binding = args[0]->ToString(); if (bindingCache->Has(binding)) { return bindingCache->Get(binding); } String::Utf8Value bindingValue(binding); LOGD(TAG, "Looking up binding: %s", *bindingValue); titanium::bindings::BindEntry *extBinding = ::AndroidaudiostreamerBindings::lookupGeneratedInit( *bindingValue, bindingValue.length()); if (!extBinding) { LOGE(TAG, "Couldn't find binding: %s, returning undefined", *bindingValue); return Undefined(); } Handle<Object> exports = Object::New(); extBinding->bind(exports); bindingCache->Set(binding, exports); return exports; } static void Androidaudiostreamer_init(Handle<Object> exports) { HandleScope scope; for (int i = 0; titanium::natives[i].name; ++i) { Local<String> name = String::New(titanium::natives[i].name); Handle<String> source = IMMUTABLE_STRING_LITERAL_FROM_ARRAY( titanium::natives[i].source, titanium::natives[i].source_length); exports->Set(name, source); } exports->Set(String::New("getBinding"), FunctionTemplate::New(Androidaudiostreamer_getBinding)->GetFunction()); } static void Androidaudiostreamer_dispose() { HandleScope scope; if (bindingCache.IsEmpty()) { return; } Local<Array> propertyNames = bindingCache->GetPropertyNames(); uint32_t length = propertyNames->Length(); for (uint32_t i = 0; i < length; ++i) { String::Utf8Value binding(propertyNames->Get(i)); int bindingLength = binding.length(); titanium::bindings::BindEntry *extBinding = ::AndroidaudiostreamerBindings::lookupGeneratedInit(*binding, bindingLength); if (extBinding && extBinding->dispose) { extBinding->dispose(); } } bindingCache.Dispose(); bindingCache = Persistent<Object>(); } static titanium::bindings::BindEntry AndroidaudiostreamerBinding = { "com.woohoo.androidaudiostreamer", Androidaudiostreamer_init, Androidaudiostreamer_dispose }; // Main module entry point extern "C" JNIEXPORT void JNICALL Java_com_woohoo_androidaudiostreamer_AndroidaudiostreamerBootstrap_nativeBootstrap (JNIEnv *env, jobject self) { titanium::KrollBindings::addExternalBinding("com.woohoo.androidaudiostreamer", &AndroidaudiostreamerBinding); titanium::KrollBindings::addExternalLookup(&(::AndroidaudiostreamerBindings::lookupGeneratedInit)); }
[ "trevor.fifield@gmail.com" ]
trevor.fifield@gmail.com
873f98f6809868731e10bb5738f936e4fce3bc32
391c7660e9c7c8df556fbca85c85426fc4c0ce75
/SchoolMap/src/map_nav/my_data.h
e421e2a5459d14b8949c54967a169ad7276b6d4f
[]
no_license
snyh/toy
d5f8ba4f3bd593fdc427856f2c58a755a288c587
803742a959c9bf4348b98ff8cbb0447bce1354d1
refs/heads/master
2016-09-06T12:36:01.614939
2014-08-28T03:03:57
2014-08-28T03:03:57
3,593,746
0
1
null
null
null
null
UTF-8
C++
false
false
2,489
h
#ifndef MYDATA_H #define MYDATA_H // link either with -lboost_serialization-mt or -lboost_serialization #include <wx/wx.h> #include <boost/serialization/string.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/vector.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/graph/adjacency_list.hpp> #include <vector> #include <map> #include <fstream> #include <cmath> namespace boost { namespace serialization { template<class Archive> void serialize(Archive &ar, wxPoint& p, const unsigned int version) { ar & p.x & p.y ; } } } struct Edge { int begin; int end; long length; std::vector<wxPoint> points; protected: friend class boost::serialization::access; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & begin & end & length & points; } }; struct PointInterpt { std::string name; std::string image; std::string value; protected: friend class boost::serialization::access; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & name & image & value; } }; struct MyData { std::vector<Edge> edges; std::map<int, wxPoint> points; std::map<int, PointInterpt> interpts; void _genAdjTable(); void _genGraph(); std::map<int, std::vector<Edge> > adjTable; void dijkstra(std::list<int>& path, int v1, int v2); void primTree(int v1, std::vector<std::pair<int,int> >& e); std::string map_name; double scale; std::string image; //path; wxBitmap *m_bit; long count; // used for, we can correctly generate Number when load data and create new node private: typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, long> > Graph; Graph *g; protected: friend class boost::serialization::access; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & map_name & image & edges & points & interpts & count & scale; } }; void DataSaveTo(const char *filename, MyData& data); void DataLoadFrom(const char *filename, MyData& data); int WhichPoint(std::map<int, wxPoint>& points, wxPoint p); void DataRemovePointAndEdge(MyData& d, wxPoint p); long CalEdgeLength (Edge& e); void DataSaveTo(wxString filename, MyData& data); void DataLoadFrom(wxString filename, MyData& data); wxBitmap* Load4Zip(wxString filename, wxString entry_name); #endif // MYDATA_H
[ "snyh@snyh.org" ]
snyh@snyh.org
ceb792b22f263ec514cfa676cdc9598de6b5c9b5
222b34018c785388eadecb41abc7e155def62a16
/client/ApartmentRentals/FilterWidget.h
ad4767b523924f091e388537c1dec2d6f103dccb
[]
no_license
baghoyanlevon/toptal_2
1d77ee4253371c19a94b6dfc5d85c4abeb98d127
32d6c5568e459182cfe27983dce5cda67de6e876
refs/heads/master
2023-06-20T17:14:04.137682
2021-07-13T14:37:55
2021-07-13T14:37:55
385,598,115
0
0
null
null
null
null
UTF-8
C++
false
false
979
h
#pragma once #include <QWidget> #include <QDate> #include <QString> class QLabel; class QLineEdit; class QDateEdit; class QSpinBox; class QDoubleSpinBox; class FilterWidget : public QWidget { Q_OBJECT public: FilterWidget(QWidget* parent = nullptr); ~FilterWidget(); public slots: void onFilter(); void clearValues(); private: void createMembers(); void initializeMembers(); void setupLayouts(); void makeConnections(); void checkAndCorrectValuse(); signals: void reset(); void filterApplied(); void filter(const QString& filterParams); private: QLabel* m_sizeMinLabel; QLabel* m_sizeMaxLabel; QLabel* m_priceMinLabel; QLabel* m_priceMaxLabel; QLabel* m_numberOfRoomsMinLabel; QLabel* m_numberOfRoomsMaxLabel; QDoubleSpinBox* m_sizeMinSpinBox; QDoubleSpinBox* m_sizeMaxSpinBox; QDoubleSpinBox* m_priceMinSpinBox; QDoubleSpinBox* m_priceMaxSpinBox; QSpinBox* m_numberOfRoomsMinSpinBox; QSpinBox* m_numberOfRoomsMaxSpinBox; bool m_isActivated; };
[ "levon.baghoyan@improvismail.com" ]
levon.baghoyan@improvismail.com
25efdf9fe58e067579dc9017437d4a3e23d4268a
10320cbdebef1b731a0e3c5efc0f1d43c62f74fd
/app/src/main/cpp/dlib/opencv_dlib_bridge.h
9a0a90f1e3f61815d47652ba0009311088127983
[ "BSL-1.0" ]
permissive
kongxs/face
72c19f6df77d95464d20d5fe6ab2288c7f931737
1d6011367fe9819452223b693a6535ceae3ba360
refs/heads/master
2022-09-28T16:29:15.175705
2020-05-28T06:34:25
2020-05-28T06:34:25
267,259,711
0
0
null
null
null
null
UTF-8
C++
false
false
313
h
#include <string> #include <sstream> using namespace std; namespace std{ template <typename T> std::string to_string(const T& n) { std::ostringstream stm; stm << n; return stm.str(); } template <typename T> T round(T v) { return (v>0)?(v+0.5):(v-0.5); } }
[ "kongxiangshu@jd.com" ]
kongxiangshu@jd.com
d8328a4c4bac10b0b91692caa3aa35614cf278d7
4de76d236f1f6ff1f8bdf1d2430192bb4906b758
/Plugins/UnrealFastNoisePlugin/Source/UnrealFastNoisePlugin/Public/FastNoise/FastNoise.h
e1110092c839003767572f813d2c9a6905ee7249
[ "MIT" ]
permissive
bbtarzan12/UE4-Procedural-Voxel-Terrain
49e920114d2528abd97d105e0320fd8b1c3d08a5
cad6b8e09b34586ce74295ae59b15c4738fa267e
refs/heads/master
2020-11-30T13:19:55.817464
2019-12-31T13:28:01
2019-12-31T13:28:01
230,404,190
8
4
null
null
null
null
UTF-8
C++
false
false
15,266
h
// FastNoise.h // // MIT License // // Copyright(c) 2016 Jordan Peck // // 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. // // The developer's email is jorzixdan.me2@gzixmail.com (for great email, take // off every 'zix'.) // // UnrealEngine-ified by Chris Ashworth 2016 // #pragma once #include "CoreMinimal.h" //#include "Object.h" #include "UFNNoiseGenerator.h" #include "FastNoise.generated.h" UENUM(BlueprintType) enum class ENoiseType : uint8 { Value, ValueFractal, Gradient, GradientFractal, Simplex, SimplexFractal, Cellular, WhiteNoise }; UENUM(BlueprintType) enum class ESimpleNoiseType : uint8 { SimpleValue UMETA(DisplayName="Value"), SimpleGradient UMETA(DisplayName = "Gradient"), SimpleSimplex UMETA(DisplayName = "Simplex"), SimpleWhiteNoise UMETA(DisplayName = "WhiteNoise") }; UENUM(BlueprintType) enum class EFractalNoiseType : uint8 { FractalValue UMETA(DisplayName = "Value"), FractalGradient UMETA(DisplayName = "Gradient"), FractalSimplex UMETA(DisplayName = "Simplex") }; UENUM(BlueprintType) enum class EInterp : uint8 { InterpLinear UMETA(DisplayName = "Linear"), InterpHermite UMETA(DisplayName = "Hermite"), InterpQuintic UMETA(DisplayName = "Quintic") }; UENUM(BlueprintType) enum EFractalType { FBM, Billow, RigidMulti }; UENUM(BlueprintType) enum ECellularDistanceFunction { Euclidean, Manhattan, Natural }; UENUM(BlueprintType) enum ECellularReturnType { CellValue, NoiseLookup, Distance, Distance2, Distance2Add, Distance2Sub, Distance2Mul, Distance2Div}; UENUM(BlueprintType) enum EPositionWarpType { None, Regular, Fractal }; UENUM(BlueprintType) enum class ESelectInterpType : uint8 { None, CircularIn, CircularOut, CircularInOut, ExponentialIn, ExponentialOut, ExponentialInOut, SineIn, SineOut, SineInOut, Step, Linear }; UCLASS() class UNREALFASTNOISEPLUGIN_API UFastNoise : public UUFNNoiseGenerator { GENERATED_UCLASS_BODY() public: //FastNoise(int seed = 1337) { SetSeed(seed); }; ~UFastNoise() { delete m_cellularNoiseLookup; } // Returns seed used for all noise types void SetSeed(int seed); // Sets seed used for all noise types // Default: 1337 int GetSeed(void) const { return m_seed; } // Sets frequency for all noise types // Default: 0.01 void SetFrequency(float frequency) { m_frequency = frequency; } // Changes the interpolation method used to smooth between noise values // Possible interpolation methods (lowest to highest quality) : // - Linear // - Hermite // - Quintic // Used in Value, Gradient Noise and Position Warping // Default: Quintic void SetInterp(EInterp interp) { m_interp = interp; } // Sets noise return type of GetNoise(...) // Default: Simplex void SetNoiseType(ENoiseType noiseType) { m_noiseType = noiseType; } // Sets octave count for all fractal noise types // Default: 3 void SetFractalOctaves(unsigned int octaves) { m_octaves = octaves; CalculateFractalBounding(); } // Sets octave lacunarity for all fractal noise types // Default: 2.0 void SetFractalLacunarity(float lacunarity) { m_lacunarity = lacunarity; } // Sets octave gain for all fractal noise types // Default: 0.5 void SetFractalGain(float gain) { m_gain = gain; CalculateFractalBounding(); } // Sets method for combining octaves in all fractal noise types // Default: FBM void SetFractalType(EFractalType fractalType) { m_fractalType = fractalType; } // Sets return type from cellular noise calculations // Note: NoiseLookup requires another FastNoise object be set with SetCellularNoiseLookup() to function // Default: CellValue void SetCellularDistanceFunction(ECellularDistanceFunction cellularDistanceFunction) { m_cellularDistanceFunction = cellularDistanceFunction; } // Sets distance function used in cellular noise calculations // Default: Euclidean void SetCellularReturnType(ECellularReturnType cellularReturnType) { m_cellularReturnType = cellularReturnType; } // Noise used to calculate a cell value if cellular return type is NoiseLookup // The lookup value is acquired through GetNoise() so ensure you SetNoiseType() on the noise lookup, value, gradient or simplex is recommended void SetCellularNoiseLookup(UFastNoise* noise) { m_cellularNoiseLookup = noise; } // Sets the maximum warp distance from original location when using PositionWarp{Fractal}(...) // Default: 1.0 void SetPositionWarpAmp(float positionWarpAmp) { m_positionWarpAmp = positionWarpAmp / 0.45f; } void SetPositionWarpType(EPositionWarpType positionWarpType) { m_positionWarpType = positionWarpType; } //2D float GetValue(float x, float y); float GetValueFractal(float x, float y); float GetGradient(float x, float y); float GetGradientFractal(float x, float y); float GetSimplex(float x, float y); float GetSimplexFractal(float x, float y); float GetCellular(float x, float y); float GetWhiteNoise(float x, float y); float GetWhiteNoiseInt(int x, int y); FORCEINLINE float GetNoise(float x, float y) { x *= m_frequency; y *= m_frequency; switch (m_noiseType) { case ENoiseType::Value: return SingleValue(0, x, y); case ENoiseType::ValueFractal: switch (m_fractalType) { case EFractalType::FBM: return SingleValueFractalFBM(x, y); case EFractalType::Billow: return SingleValueFractalBillow(x, y); case EFractalType::RigidMulti: return SingleValueFractalRigidMulti(x, y); default: return 0.0f; } case ENoiseType::Gradient: return SingleGradient(0, x, y); case ENoiseType::GradientFractal: switch (m_fractalType) { case EFractalType::FBM: return SingleGradientFractalFBM(x, y); case EFractalType::Billow: return SingleGradientFractalBillow(x, y); case EFractalType::RigidMulti: return SingleGradientFractalRigidMulti(x, y); default: return 0.0f; } case ENoiseType::Simplex: return SingleSimplex(0, x, y); case ENoiseType::SimplexFractal: switch (m_fractalType) { case EFractalType::FBM: return SingleSimplexFractalFBM(x, y); case EFractalType::Billow: return SingleSimplexFractalBillow(x, y); case EFractalType::RigidMulti: return SingleSimplexFractalRigidMulti(x, y); default: return 0.0f; } case ENoiseType::Cellular: switch (m_cellularReturnType) { case ECellularReturnType::CellValue: case ECellularReturnType::NoiseLookup: case ECellularReturnType::Distance: return SingleCellular(x, y); default: return SingleCellular2Edge(x, y); } case ENoiseType::WhiteNoise: return GetWhiteNoise(x, y); default: return 0.0f; } } FORCEINLINE float GetNoise2D(float x, float y) { switch (m_positionWarpType) { default: case EPositionWarpType::None: return GetNoise(x, y); case EPositionWarpType::Fractal: PositionWarpFractal(x, y); return GetNoise(x, y); case EPositionWarpType::Regular: PositionWarp(x, y); return GetNoise(x, y); } } FORCEINLINE FVector GetNoise2DDeriv(float x, float y) { FVector2D p = FVector2D(x, y); p.X = FMath::FloorToFloat(p.X); p.Y = FMath::FloorToFloat(p.Y); FVector2D f = FVector2D(x, y) - p; FVector2D u = f*f*f; float a = GetNoise2D(p.X, p.Y); float b = GetNoise2D(p.X + 1.f, p.Y); float c = GetNoise2D(p.X, p.Y + 1.f); float d = GetNoise2D(p.X + 1.0f, p.Y + 1.0f); FVector result; const FVector2D Intermediate = 6.0f*f*(f)*(FVector2D(b - a, c - a) + (a - b - c + d)*(FVector2D(u.Y, u.X))); result = FVector(a + (b - a)*u.X + (c - a)*u.Y + (a - b - c + d)*u.X*u.Y, Intermediate.X, Intermediate.Y); //result = FVector(a + (b - a)*u.X + (c - a)*u.Y + (a - b - c + d)*u.X*u.Y, //6.0*f*(1.0 - f)*(FVector2D(b - a, c - a) + (a - b - c + d)*(FVector2D(u.Y, u.X)))); return result; } void PositionWarp(float& x, float& y); void PositionWarpFractal(float& x, float& y); //3D float GetValue(float x, float y, float z); float GetValueFractal(float x, float y, float z); float GetGradient(float x, float y, float z); float GetGradientFractal(float x, float y, float z); float GetSimplex(float x, float y, float z); float GetSimplexFractal(float x, float y, float z); float GetCellular(float x, float y, float z); float GetWhiteNoise(float x, float y, float z); float GetWhiteNoiseInt(int x, int y, int z); FORCEINLINE float GetNoise(float x, float y, float z) { x *= m_frequency; y *= m_frequency; z *= m_frequency; switch (m_noiseType) { case ENoiseType::Value: return SingleValue(0, x, y, z); case ENoiseType::ValueFractal: switch (m_fractalType) { case EFractalType::FBM: return SingleValueFractalFBM(x, y, z); case EFractalType::Billow: return SingleValueFractalBillow(x, y, z); case EFractalType::RigidMulti: return SingleValueFractalRigidMulti(x, y, z); default: return 0.0f; } case ENoiseType::Gradient: return SingleGradient(0, x, y, z); case ENoiseType::GradientFractal: switch (m_fractalType) { case EFractalType::FBM: return SingleGradientFractalFBM(x, y, z); case EFractalType::Billow: return SingleGradientFractalBillow(x, y, z); case EFractalType::RigidMulti: return SingleGradientFractalRigidMulti(x, y, z); default: return 0.0f; } case ENoiseType::Simplex: return SingleSimplex(0, x, y, z); case ENoiseType::SimplexFractal: switch (m_fractalType) { case EFractalType::FBM: return SingleSimplexFractalFBM(x, y, z); case EFractalType::Billow: return SingleSimplexFractalBillow(x, y, z); case EFractalType::RigidMulti: return SingleSimplexFractalRigidMulti(x, y, z); default: return 0.0f; } case ENoiseType::Cellular: switch (m_cellularReturnType) { case ECellularReturnType::CellValue: case ECellularReturnType::NoiseLookup: case ECellularReturnType::Distance: return SingleCellular(x, y, z); default: return SingleCellular2Edge(x, y, z); } case ENoiseType::WhiteNoise: return GetWhiteNoise(x, y, z); default: return 0.0f; } } FORCEINLINE float GetNoise3D(float x, float y, float z) { switch (m_positionWarpType) { default: case EPositionWarpType::None: return GetNoise(x, y, z); case EPositionWarpType::Fractal: PositionWarpFractal(x, y, z); return GetNoise(x, y, z); case EPositionWarpType::Regular: PositionWarp(x, y, z); return GetNoise(x, y, z); } } void PositionWarp(float& x, float& y, float& z); void PositionWarpFractal(float& x, float& y, float& z); //4D float GetSimplex(float x, float y, float z, float w); float GetWhiteNoise(float x, float y, float z, float w); float GetWhiteNoiseInt(int x, int y, int z, int w); protected: unsigned char m_perm[512]; unsigned char m_perm12[512]; int m_seed = 1337; float m_frequency = 0.01f; EInterp m_interp = EInterp::InterpQuintic; ENoiseType m_noiseType = ENoiseType::Simplex; EPositionWarpType m_positionWarpType = EPositionWarpType::None; unsigned int m_octaves = 3; float m_lacunarity = 2.0f; float m_gain = 0.5f; EFractalType m_fractalType = EFractalType::FBM; float m_fractalBounding; void CalculateFractalBounding() { float amp = m_gain; float ampFractal = 1.0f; for (unsigned int i = 1; i < m_octaves; i++) { ampFractal += amp; amp *= m_gain; } m_fractalBounding = 1.0f / ampFractal; } ECellularDistanceFunction m_cellularDistanceFunction = ECellularDistanceFunction::Euclidean; ECellularReturnType m_cellularReturnType = ECellularReturnType::CellValue; UFastNoise* m_cellularNoiseLookup = nullptr; float m_positionWarpAmp = 1.0f / 0.45f; //2D float SingleValueFractalFBM(float x, float y); float SingleValueFractalBillow(float x, float y); float SingleValueFractalRigidMulti(float x, float y); float SingleValue(unsigned char offset, float x, float y); float SingleGradientFractalFBM(float x, float y); float SingleGradientFractalBillow(float x, float y); float SingleGradientFractalRigidMulti(float x, float y); float SingleGradient(unsigned char offset, float x, float y); float SingleSimplexFractalFBM(float x, float y); float SingleSimplexFractalBillow(float x, float y); float SingleSimplexFractalRigidMulti(float x, float y); float SingleSimplex(unsigned char offset, float x, float y); float SingleCellular(float x, float y); float SingleCellular2Edge(float x, float y); void SinglePositionWarp(unsigned char offset, float warpAmp, float frequency, float& x, float& y); //3D float SingleValueFractalFBM(float x, float y, float z); float SingleValueFractalBillow(float x, float y, float z); float SingleValueFractalRigidMulti(float x, float y, float z); float SingleValue(unsigned char offset, float x, float y, float z); float SingleGradientFractalFBM(float x, float y, float z); float SingleGradientFractalBillow(float x, float y, float z); float SingleGradientFractalRigidMulti(float x, float y, float z); float SingleGradient(unsigned char offset, float x, float y, float z); float SingleSimplexFractalFBM(float x, float y, float z); float SingleSimplexFractalBillow(float x, float y, float z); float SingleSimplexFractalRigidMulti(float x, float y, float z); float SingleSimplex(unsigned char offset, float x, float y, float z); float SingleCellular(float x, float y, float z); float SingleCellular2Edge(float x, float y, float z); void SinglePositionWarp(unsigned char offset, float warpAmp, float frequency, float& x, float& y, float& z); //4D float SingleSimplex(unsigned char offset, float x, float y, float z, float w); private: inline unsigned char Index2D_12(unsigned char offset, int x, int y); inline unsigned char Index3D_12(unsigned char offset, int x, int y, int z); inline unsigned char Index4D_32(unsigned char offset, int x, int y, int z, int w); inline unsigned char Index2D_256(unsigned char offset, int x, int y); inline unsigned char Index3D_256(unsigned char offset, int x, int y, int z); inline unsigned char Index4D_256(unsigned char offset, int x, int y, int z, int w); inline float ValCoord2DFast(unsigned char offset, int x, int y); inline float ValCoord3DFast(unsigned char offset, int x, int y, int z); inline float GradCoord2D(unsigned char offset, int x, int y, float xd, float yd); inline float GradCoord3D(unsigned char offset, int x, int y, int z, float xd, float yd, float zd); inline float GradCoord4D(unsigned char offset, int x, int y, int z, int w, float xd, float yd, float zd, float wd); };
[ "bbtarzan12@gmail.com" ]
bbtarzan12@gmail.com
2a3c705902d48a1cb424bd962efbefd264018c26
b134abbcc8776871245592cf0956fe21013b6876
/OpenGL-Tutorial/MovementManager.cpp
27bff1b26f6ba22da038ea252483d5ed018bf637
[]
no_license
GriffinBabe/ARSWA3D
01116bcfdedb6b4be5259592f08cdbef081aba7c
a3a74e82904e62666276ecffc98ee496dbdde4e2
refs/heads/master
2020-04-12T05:12:40.840838
2019-08-10T15:07:33
2019-08-10T15:07:33
162,318,480
0
0
null
null
null
null
UTF-8
C++
false
false
1,135
cpp
#include "MovementManager.h" MovementManager::MovementManager() { } MovementManager::MovementManager(float bottom, float left, float right, float top) : bottomMap(bottom), leftMap(left), rightMap(right), topMap(top) { } MovementManager::~MovementManager() { } void MovementManager::loop(std::vector<Entity*>* entities, float delta_time) { int movingEntitiesCount = 0; for (Entity* entity : *entities) { if (MovingEntity* m_entity = dynamic_cast<MovingEntity*>(entity)) { movingEntitiesCount++; m_entity->accelerate(delta_time); // Changes the speedX with the acceleration direction etc. m_entity->move(delta_time); // Changes the position m_entity->checkMapBoundaries(bottomMap, leftMap, rightMap, topMap); // Checks if it hasn't crossed the map boundaries for (Entity* entity_to_collide : *entities) { // Checks collisions. if (SolidEntity* solidEntity = dynamic_cast<SolidEntity*>(entity_to_collide)) { if (solidEntity != entity) { if (solidEntity->check_collision(m_entity)) { m_entity->hit(solidEntity); } } } } } } }
[ "darius.couchard@hotmail.com" ]
darius.couchard@hotmail.com
ec4e08fc3089a6e9bdb2c250e00ef4a3b43dd478
aae79375bee5bbcaff765fc319a799f843b75bac
/atcoder/arc_125/b.cpp
a65c8c9723f8587b3d441764bb4ebc23c209f4cf
[]
no_license
firewood/topcoder
b50b6a709ea0f5d521c2c8870012940f7adc6b19
4ad02fc500bd63bc4b29750f97d4642eeab36079
refs/heads/master
2023-08-17T18:50:01.575463
2023-08-11T10:28:59
2023-08-11T10:28:59
1,628,606
21
6
null
null
null
null
UTF-8
C++
false
false
1,432
cpp
#include <algorithm> #include <cctype> #include <cmath> #include <cstring> #include <iostream> #include <sstream> #include <numeric> #include <map> #include <set> #include <queue> #include <vector> using namespace std; static const int64_t MOD = 998244353; struct modint { int64_t x; modint() { } modint(int _x) : x(_x) { } operator int() const { return (int)x; } modint operator+(int y) { return (x + y + MOD) % MOD; } modint operator+=(int y) { x = (x + y + MOD) % MOD; return *this; } modint operator-(int y) { return (x - y + MOD) % MOD; } modint operator-=(int y) { x = (x - y + MOD) % MOD; return *this; } modint operator*(int y) { return (x * y) % MOD; } modint operator*=(int y) { x = (x * y) % MOD; return *this; } modint operator/(int y) { return (x * modpow(y, MOD - 2)) % MOD; } modint operator/=(int y) { x = (x * modpow(y, MOD - 2)) % MOD; return *this; } static modint modinv(int a) { return modpow(a, MOD - 2); } static modint modpow(int a, int b) { modint x = a, r = 1; for (; b; b >>= 1, x *= x) if (b & 1) r *= x; return r; } }; int64_t solve(int64_t N) { // x * x - y = z * z // (x - z) * (x + z) = y // p = x + z, q = x - z => p >= q // pq <= N => q <= sqrt(N) modint ans = 0; for (int64_t q = 1; q * q <= N; ++q) { int64_t cnt = (N / q - q) / 2; ans += int((cnt + 1) % MOD); } return ans; } int main() { int64_t N; std::cin >> N; cout << solve(N) << endl; return 0; }
[ "karamaki@gmail.com" ]
karamaki@gmail.com
08576bae765ea2eb761695f38d435dd448d94f10
b5b2d1aeca28b6a2e62dfa9aa632c659a288ba3a
/user.h
58b62d49c8e0283b49015c3603bee6a5053f7066
[]
no_license
DrozdDominik/adress_book
88a77141d62fe9c9ed93cb5db5ec0f5ef3f51eef
8e78ae25d873671bb0500262b07df51d4074a199
refs/heads/master
2020-06-22T04:31:15.946321
2019-08-02T11:14:23
2019-08-02T11:14:23
197,633,550
0
0
null
null
null
null
UTF-8
C++
false
false
391
h
#include <iostream> #include <vector> #include <fstream> #include <windows.h> using namespace std; class User { int id; string name, password; public: User(int=0, string="brak", string=""); void registration(vector <User> &users); void loadUsers(vector<User> &users); int LogIn (vector <User> &users); void editPassword(vector<User> &users, int idToEdit); };
[ "dominik_drozd@vp.pl" ]
dominik_drozd@vp.pl
65da0293babc4e08bae3868d25b28eb8d1146cb6
bce8a68a5311539db3644958c3e89b18bf05d158
/C++ 2/project_1b_grade_report/Project1/ExceptionHandler.cpp
0a027eebf473d7ec83c6e7cc6598bd178d441124
[]
no_license
gleny4001/C-exercises-projects
9e04bd32528eab41b4d54c7322ec066d3d7a3714
c7a86fa228daa0efdc41d004a06a9bfe9133579b
refs/heads/master
2022-04-30T18:57:29.532645
2022-03-08T10:13:26
2022-03-08T10:13:26
242,616,332
0
0
null
null
null
null
UTF-8
C++
false
false
1,571
cpp
#include "ExceptionHandler.h" using namespace std; int ExceptionHandler::validateSelection(const string& input) const { if (input.length() > 1) return 0; else { int id = input[0] - 48; if (id >= 1 && id <= 6) return id; else return 0; } } bool ExceptionHandler::lastNameValid(string& input) const { for (auto it = input.begin(); it != input.end(); ++it) if (isspace(*it)) return false; input[0] = toupper(input[0]); for_each(input.begin() + 1, input.end(), [](char& c) { c = ::tolower(c); }); return true; } bool ExceptionHandler::validateID (const string& input, int& id) const { // your code here... int len = static_cast<int>(input.length()); if (len != 6) { cout << "Invalid output. ID is 6 digits. Try again." << endl; return false; } for (auto c : input) { if (!isdigit(c)) { cout << "Invalid output. ID is 6 digits. Try again." << endl; return false; } } id = stoi(input); return true; } bool ExceptionHandler::validateCoursePrefix(string& input) const { if (input.length() != 3) { cout << "Invalid input. Course prefix is 3 letters. " << "Try again." << endl; input = ""; return false; } else { // your code here... for_each(input.begin(), input.end(), [](char c) {c = toupper(c);}); } return true; } bool ExceptionHandler::validateCourseNo (const string& input, int& courseNo) const { if (input.length() != 3) { cout << "Invalid input. Course number is 3 digits. " << "Try again." << endl; return false; } else { courseNo = stoi(input); return true; } }
[ "gleny4001@gmail.com" ]
gleny4001@gmail.com
7b2b1903a3b1106a45240d327c55816bb699b7af
407a5cb0cdb7a7904242895855af180f8dee8f6c
/src/systems/player_control_system.cpp
63dd32b258179656408eaa71d2ea7e02a1147bf8
[]
no_license
euiko/platchamer
38647edecff8a9be6b1ee1b3b3eaa7bbc59f39d8
b353d5a6048a64fe04232c81154ccbb454e0ce01
refs/heads/master
2020-04-23T03:48:29.757183
2019-06-28T17:45:59
2019-06-28T17:45:59
170,888,628
0
0
null
null
null
null
UTF-8
C++
false
false
3,450
cpp
extern "C" { #include <sdl_bgi/graphics.h> } #include "player_control_system.hpp" #include "../core/game.hpp" #include "../core/factories.hpp" #include "../components/position_component.hpp" #include "../components/rigid_body_component.hpp" #include "../components/ui/game_ui_component.hpp" #include "../tags/player_tag.hpp" #include "../tags/ground_tag.hpp" #include "../tags/thorn_tag.hpp" PlayerControlSystem::~PlayerControlSystem() { } void PlayerControlSystem::configure(std::shared_ptr<entcosy::Registry> registry) { registry->subscribe<ResetPlayerStateEvent>(this); registry->subscribe<KeyboardEvent>(this); registry->subscribe<CollideEvent>(this); } void PlayerControlSystem::unconfigure(std::shared_ptr<entcosy::Registry> registry) { registry->unsubscribeAll(this); } void PlayerControlSystem::update(std::shared_ptr<entcosy::Registry> registry, float deltaTime) { const Uint8 *keyboards = SDL_GetKeyboardState(NULL); registry->each<PlayerTag, RigidBodyComponent>( [&](std::shared_ptr<entcosy::Entity> entity, PlayerTag* playerTag, RigidBodyComponent* rigidBody) { if(keyboards[SDL_SCANCODE_W] && playerTag->is_ground) rigidBody->velocity.y = -300.0f; // position_component->pos.y -= 20; if(keyboards[SDL_SCANCODE_A] && rigidBody->velocity.x > -200.0f) rigidBody->velocity.x -= 10.0f; if(keyboards[SDL_SCANCODE_D] && rigidBody->velocity.y < 200.0f) rigidBody->velocity.x += 10.0f; // std::cout << playerTag->is_ground << " = "; // if(rigidBody->velocity.y < -200.0f) rigidBody->velocity.y = -200.0f; // if(rigidBody->velocity.x > 200.0f) rigidBody->velocity.y = 200.0f; // if(rigidBody->velocity.x < -200.0f) rigidBody->velocity.y = 200.0f; // if(rigidBody->velocity.x > 0) // rigidBody->velocity.x -= 2; // if(rigidBody->velocity.x < 0) // rigidBody->velocity.x += 2; if(keyboards[SDLK_SPACE]) makeBullet(registry, entity); } ); } void PlayerControlSystem::receive(std::shared_ptr<entcosy::Registry> registry, const KeyboardEvent& event) { } void PlayerControlSystem::receive(std::shared_ptr<entcosy::Registry> registry, const CollideEvent& event) { if( (event.entityA->has<PlayerTag>() && event.entityB->has<GroundTag>()) || (event.entityB->has<PlayerTag>() && event.entityA->has<GroundTag>()) ) { registry->each<PlayerTag>([&](std::shared_ptr<entcosy::Entity> entity, PlayerTag *playerTag) { playerTag->is_ground = playerTag->is_ground || event.isCollide; // std::cout << playerTag->is_ground << " "; }); } if( (event.entityA->has<PlayerTag>() && event.entityB->has<ThornTag>()) || (event.entityB->has<PlayerTag>() && event.entityA->has<ThornTag>()) ) { std::cout << event.isCollide << "\n"; if(event.isCollide) registry->changeUi<GameUiComponent>(); } } void PlayerControlSystem::receive(std::shared_ptr<entcosy::Registry> registry, const ResetPlayerStateEvent& event) { // std::cout << "\n===================================\n"; registry->each<PlayerTag>([&](std::shared_ptr<entcosy::Entity> entity, PlayerTag *playerTag) { playerTag->is_ground = 0; }); }
[ "candra.kharista@gmail.com" ]
candra.kharista@gmail.com
f6b11a93db09308e8696530ce8463eeafc68a8e4
8584afff21c31c843f520bd28587a741e6ffd402
/AtCoder/ABC/091/d.cpp
9a806c9ef107afc3ebc2b18f6118a05030bbda87
[]
no_license
YuanzhongLi/CompetitiveProgramming
237e900f1c906c16cbbe3dd09104a1b7ad53862b
f9a72d507d4dda082a344eb19de22f1011dcee5a
refs/heads/master
2021-11-20T18:35:35.412146
2021-08-25T11:39:32
2021-08-25T11:39:32
249,442,987
0
0
null
null
null
null
UTF-8
C++
false
false
1,103
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i,s,n) for (int i = (int)s; i < (int)n; i++) #define ll long long #define pb push_back #define All(x) x.begin(), x.end() #define Range(x, i, j) x.begin() + i, x.begin() + j #define lbidx(x, y) lower_bound(x.begin(), x.end(), y) - x.begin() #define ubidx(x, y) upper_bound(x.begin(), x.end(), y) - x.begin() #define BiSearchRangeNum(x, y, z) lower_bound(x.begin(), x.end(), z) - lower_bound(x.begin(), x.end(), y) int main() { int N; cin >> N; vector<int> A(N); vector<int> B(N); rep(i, 0, N) { cin >> A[i]; } rep(i, 0, N) { cin >> B[i]; } int ans = 0; int T = 1; rep(k, 0, 30) { int mod = 2 * T; vector<int> Amod(N); vector<int> Bmod(N); rep(i, 0, N) { Amod[i] = A[i] % mod; Bmod[i] = B[i] % mod; } sort(All(Amod)); ll counter = 0; rep(i, 0, N) { int bi = Bmod[i]; counter += BiSearchRangeNum(Amod, T - bi, 2 * T - bi) + BiSearchRangeNum(Amod, 3 * T - bi, 4 * T - bi); } if (counter % 2 == 1) ans += T; T *= 2; } cout << ans << endl; };
[ "liyuanzhongutokyos1@gmail.com" ]
liyuanzhongutokyos1@gmail.com
a3bda6a19577ea5ede1bc65516c94ff63171d246
3bc5e39a45ec7ab52383f632069830fdffc662f9
/mav_trajectory_generation_ros/src/waypoint_node.cpp
08ccf8c4e7b6ed6c065fd0674dc2428a4c35f3a8
[ "Apache-2.0" ]
permissive
G-KUMAR/mav_trajectory_generation
5048c37ea2221d79d6e512f05ae866142243d93c
9a8a805dea11d11beb626cb6979e5af2ac177202
refs/heads/master
2020-04-13T04:31:19.694814
2018-07-16T22:54:34
2018-07-16T22:54:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,507
cpp
#include <mav_trajectory_generation/polynomial_optimization_linear.h> #include <mav_trajectory_generation/trajectory.h> #include <mav_trajectory_generation_ros/ros_visualization.h> #include <geometry_msgs/PoseArray.h> #include <nav_msgs/Path.h> #include <math.h> #include <tf/transform_datatypes.h> #define PI 3.14159265 nav_msgs::Path way_; geometry_msgs::PoseArray traj_with_yaw; geometry_msgs::Pose traj_pose; tf::Quaternion q; void waycb(const nav_msgs::Path::ConstPtr &msg) { way_ = *msg; } int main(int argc, char **argv) { ros::init(argc, argv, "waypoint_node"); ros::NodeHandle n; ros::Subscriber way_sub = n.subscribe("/costmap_node/planner/plan", 10, waycb); ros::Publisher vis_pub = n.advertise<visualization_msgs::MarkerArray>("/trajectory_vis", 10); ros::Publisher traj_with_yaw_pub = n.advertise<geometry_msgs::PoseArray>("/trajectory_with_yaw", 10); ros::Rate sleep_rate(10); while (ros::ok()) { mav_trajectory_generation::Vertex::Vector vertices; const int dimension = 3; const int derivative_to_optimize = mav_trajectory_generation::derivative_order::ANGULAR_ACCELERATION; mav_trajectory_generation::Vertex start(dimension), middle(dimension), end(dimension); // Time count ros::Time t0 = ros::Time::now(); if(way_.poses.size()>0) { start.makeStartOrEnd(Eigen::Vector3d(way_.poses[0].pose.position.x, way_.poses[0].pose.position.y,0), derivative_to_optimize); vertices.push_back(start); // std::cout << "debug=" << "," << way_.poses.size() << std::endl; for(int ii=1;ii < way_.poses.size()-1; ii = ii+10 ) { middle.addConstraint(mav_trajectory_generation::derivative_order::POSITION, Eigen::Vector3d(way_.poses[ii].pose.position.x, way_.poses[ii].pose.position.y, 0)); vertices.push_back(middle); } end.makeStartOrEnd(Eigen::Vector3d(way_.poses[way_.poses.size() - 1].pose.position.x, way_.poses[way_.poses.size() - 1].pose.position.y,0), derivative_to_optimize); vertices.push_back(end); //compute the segment times std::vector<double> segment_times; const double v_max = 1.0; const double a_max = 3.0; const double magic_fabian_constant = 6.5; // A tuning parameter segment_times = estimateSegmentTimes(vertices, v_max, a_max, magic_fabian_constant); //N denotes the number of coefficients of the underlying polynomial //N has to be even. //If we want the trajectories to be snap-continuous, N needs to be at least 10. const int N = 10; mav_trajectory_generation::PolynomialOptimization<N> opt(dimension); opt.setupFromVertices(vertices, segment_times, derivative_to_optimize); opt.solveLinear(); //ROS_INFO("Take %f sec to get optimal traject", (ros::Time::now() - t0).toSec()); //Obtain the polynomial segments mav_trajectory_generation::Segment::Vector segments; opt.getSegments(&segments); //creating Trajectories mav_trajectory_generation::Trajectory trajectory; opt.getTrajectory(&trajectory); mav_trajectory_generation::Trajectory x_trajectory = trajectory.getTrajectoryWithSingleDimension(1); //evaluating the trajectory at particular instances of time // Single sample: double sampling_time = 2.0; int derivative_order = mav_trajectory_generation::derivative_order::POSITION; Eigen::VectorXd sample = trajectory.evaluate(sampling_time, derivative_order); // Sample range: double t_start = 2.0; double t_end = 10.0; double dt = 0.01; std::vector<Eigen::VectorXd> result; std::vector<double> sampling_times; // Optional. trajectory.evaluateRange(t_start, t_end, dt, derivative_order, &result, &sampling_times); //std::cout << result.size() << std::endl; //std::cout << sampling_times.size() << std::endl; //visualizing Trajectories visualization_msgs::MarkerArray markers; double distance = 1.6; // Distance by which to seperate additional markers. Set 0.0 to disable. std::string frame_id = "world"; traj_with_yaw.header.stamp = ros::Time::now(); traj_with_yaw.header.frame_id = "world"; // From Trajectory class: mav_trajectory_generation::drawMavTrajectory(trajectory, distance, frame_id, &markers); float traj_marker_size = markers.markers.size(); float trajectory_size = markers.markers[traj_marker_size - 1].points.size(); for(int ii=0; ii < trajectory_size; ii++) { traj_pose.position.x = markers.markers[traj_marker_size - 1].points[ii].x; traj_pose.position.y = markers.markers[traj_marker_size - 1].points[ii].y; if(ii<trajectory_size-1) { float y_diff = (markers.markers[traj_marker_size - 1].points[ii+1].y - markers.markers[traj_marker_size - 1].points[ii].y); float x_diff = (markers.markers[traj_marker_size - 1].points[ii+1].x - markers.markers[traj_marker_size - 1].points[ii].x); float yaw = atan2(y_diff,x_diff); q.setRPY(0, 0, yaw); } else { float y_diff = (markers.markers[traj_marker_size - 1].points[ii].y - markers.markers[traj_marker_size - 1].points[ii-1].y); float x_diff = (markers.markers[traj_marker_size - 1].points[ii].x - markers.markers[traj_marker_size - 1].points[ii-1].x); float yaw = atan2(y_diff,x_diff); q.setRPY(0, 0, yaw); } traj_pose.orientation.z = q.z(); traj_pose.orientation.w = q.w(); //yaw set traj_with_yaw.poses.push_back(traj_pose); } vis_pub.publish(markers); traj_with_yaw_pub.publish(traj_with_yaw); traj_with_yaw.poses.clear(); } ros::spinOnce(); vertices.clear(); sleep_rate.sleep(); } return 0; }
[ "gajena@iitk.ac.in" ]
gajena@iitk.ac.in
8d685bccee6b5d87615b7b39fdbb3d914f0d305f
ca470ed29f14e3fe34671db4a8fba47ec264036d
/test/matrix2020/test-005-fovhamming.cpp
0b018c7367513be04c29f55d02b5b38c3ebd76ff
[]
no_license
snowgoon88/ChuchuGL
6ad0ae784d8a6400377751c5e6ebb9a2b224a149
3741225e48af282ca5263304385e4e84185cffa4
refs/heads/master
2023-08-18T20:18:06.310623
2018-12-30T12:41:55
2018-12-30T12:41:55
35,823,653
2
0
null
null
null
null
UTF-8
C++
false
false
1,266
cpp
/* -*- coding: utf-8 -*- */ /** * test Field of View using hamming distance */ #include <matrix2020/fov_hamming.hpp> #include <iostream> using namespace matrix2020; /** * Print some FoV of various max_dist */ void test_no_env() { Environment env; env.load_from_txt( "data/matrix00.txt" ); std::cout << env.str_display() << std::endl; Pos pos(5,3); FOVHamming fov( env, pos, 1 /* max dist */); std::cout << "__INIT" << std::endl; std::cout << fov.str_dump() << std::endl; for( int max_dist = 0; max_dist < 4; ++max_dist) { std::cout << "__FOV at " << pos << " max=" << max_dist << std::endl; fov = FOVHamming( env, pos, max_dist ); std::cout << fov.str_dump() << std::endl; std::cout << fov.str_display() << std::endl; std::cout << fov.str_view() << std::endl; } pos = {3,3}; std::cout << "__POS " << pos << std::endl; for( int max_dist = 0; max_dist < 4; ++max_dist) { std::cout << "__FOV at " << pos << " max=" << max_dist << std::endl; fov = FOVHamming( env, pos, max_dist ); std::cout << fov.str_dump() << std::endl; std::cout << fov.str_display() << std::endl; std::cout << fov.str_view() << std::endl; } } int main(int argc, char *argv[]) { test_no_env(); return 0; }
[ "snowgoon88@gmail.com" ]
snowgoon88@gmail.com
315f305d6be452bae16064655e947289109ccdc8
fbb9d8e533f31c8f3d303516cb96b3d7675039e3
/RWM-P5/RWM-P5/include/BombBird.h
75dd9e8a12573a94ea0504e513446a02ee4d1734
[]
no_license
suprememetalfire/RWM-P5
db90e1a433ddf75efd9508b6ef3c9b73b7bb6703
76129c77c9f108f7b2a9634d16078f7734ca0cbf
refs/heads/master
2020-05-26T21:28:51.060028
2012-03-04T02:37:19
2012-03-04T02:37:19
3,613,637
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
h
#ifndef BOMBBIRD_H #define BOMBBIRD_H #include "BaseBirdObject.h" #include "Level.h" namespace GameEntities { class BombBird : public BaseBirdObject { private: float m_timeToExplode; GameUtilities::Level* m_level; public: /*! Constructor. * * Creates an instance of the SphereObject, and sets up its varies properties. * * @param sceneManager A pointer to the SceneManager, used for creating Ogre * Entities and SceneNodes. * @param world The Box2D World object, used for creating bodies and fixtures. * @param objectID The unique ID for this instance. * @param position Initial position for this object. * @param radius Half the desired width of the sphere. * @param halfHeight Half the desired height of the sphere. * @param fixtureDefinition Fixture definition describing the properties of the * sphere. */ BombBird(Ogre::SceneManager * sceneManager, hkpWorld* world, long objectID, Ogre::Vector3 position, const hkReal radius, const hkReal sphereMass, hkpRigidBodyCinfo & info, EntityType type); ~BombBird(); void update(float timeSinceLastFrame); void explode(); }; // class SphereObject } // namespace GameEntities #endif
[ "suprememetalice@gmail.com" ]
suprememetalice@gmail.com
ba0f651c08afd7cb7c132b121ffd2eb31af40c3f
e6dd2d5c23648874c35675f4b8c98d6dab9d07a0
/unit/component/unittest_transform.cpp
ede0c7a63d9d5b68e387a6b6160c1055941debc9
[ "Apache-2.0" ]
permissive
arunjeetsingh/apl-core-library
90fcf45dfaa6666f8d844c3a0e6a7b253e107789
b1dd5cad90340cc2b29957752cce5d022ca44c5f
refs/heads/master
2023-05-10T07:28:57.773485
2021-06-02T15:40:31
2021-06-04T15:39:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,256
cpp
/** * Copyright 2019 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 "rapidjson/document.h" #include "gtest/gtest.h" #include <cmath> #include "apl/engine/evaluate.h" #include "apl/engine/builder.h" #include "../testeventloop.h" using namespace apl; class ComponentTransformTest : public DocumentWrapper {}; template<class T> std::shared_ptr<T> as(const ComponentPtr &component) { return std::static_pointer_cast<T>(component); } static const char *CHILD_IN_PARENT = R"apl({ "type": "APL", "version": "1.4", "mainTemplate": { "items": { "type": "Container", "width": 400, "height": 400, "items": [ { "type": "TouchWrapper", "id": "TouchWrapper", "position": "absolute", "left": 40, "top": 50, "width": "100", "height": "100", "item": { "type": "Frame", "id": "Frame", "width": "100%", "height": "100%" } } ] } } } )apl"; TEST_F(ComponentTransformTest, ChildInParent) { loadDocument(CHILD_IN_PARENT); auto touchWrapper = as<CoreComponent>(component->findComponentById("TouchWrapper")); auto frame = as<CoreComponent>(component->findComponentById("Frame")); ASSERT_TRUE(touchWrapper); ASSERT_TRUE(frame); ASSERT_EQ(Transform2D(), component->getGlobalToLocalTransform()); ASSERT_EQ(Transform2D::translate(-40, -50), touchWrapper->getGlobalToLocalTransform()); ASSERT_EQ(Transform2D::translate(-40, -50), frame->getGlobalToLocalTransform()); } static const char *TRANSFORMATIONS = R"apl({ "type": "APL", "version": "1.4", "mainTemplate": { "items": { "type": "Container", "width": 400, "height": 400, "items": [ { "type": "TouchWrapper", "id": "TouchWrapper", "position": "absolute", "left": 40, "top": 50, "width": "100", "height": "100", "transform": [ {"scale": 0.5} ], "item": { "type": "Frame", "id": "Frame", "width": "100%", "height": "100%", "transform": [ {"translateX": 25} ] } } ] } } } )apl"; TEST_F(ComponentTransformTest, Transformations) { loadDocument(TRANSFORMATIONS); auto touchWrapper = as<CoreComponent>(component->findComponentById("TouchWrapper")); auto frame = as<CoreComponent>(component->findComponentById("Frame")); ASSERT_TRUE(touchWrapper); ASSERT_TRUE(frame); ASSERT_EQ(Transform2D({2,0, 0, 2, -130, -150}), touchWrapper->getGlobalToLocalTransform()); ASSERT_EQ(Transform2D({2,0, 0, 2, -155, -150}), frame->getGlobalToLocalTransform()); } TEST_F(ComponentTransformTest, ToLocalPoint) { loadDocument(TRANSFORMATIONS); auto touchWrapper = as<CoreComponent>(component->findComponentById("TouchWrapper")); auto frame = as<CoreComponent>(component->findComponentById("Frame")); ASSERT_TRUE(touchWrapper); ASSERT_TRUE(frame); ASSERT_EQ(Transform2D({2,0, 0, 2, -130, -150}), touchWrapper->getGlobalToLocalTransform()); ASSERT_EQ(Transform2D({2,0, 0, 2, -155, -150}), frame->getGlobalToLocalTransform()); ASSERT_EQ(Point(-130, -150), touchWrapper->toLocalPoint({0,0})); ASSERT_EQ(Point(-110, -130), touchWrapper->toLocalPoint({10,10})); ASSERT_EQ(Point(-155, -150), frame->toLocalPoint({0,0})); ASSERT_EQ(Point(-135, -130), frame->toLocalPoint({10,10})); ASSERT_TRUE(TransformComponent(root, "Frame", "scale", 0)); auto singularPoint = frame->toLocalPoint({0, 0}); ASSERT_TRUE(std::isnan(singularPoint.getX())); ASSERT_TRUE(std::isnan(singularPoint.getY())); } static const char *SCROLL_VIEW = R"apl({ "type": "APL", "version": "1.4", "mainTemplate": { "parameters": [], "item": { "type": "ScrollView", "width": "100vw", "height": "100vh", "items": { "type": "Container", "items": { "type": "Frame", "width": 200, "height": 200 }, "data": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] } } } } )apl"; TEST_F(ComponentTransformTest, ScrollView) { loadDocument(SCROLL_VIEW); auto container = as<CoreComponent>(component->getChildAt(0)); ASSERT_EQ(Transform2D(), component->getGlobalToLocalTransform()); ASSERT_EQ(Transform2D(), container->getGlobalToLocalTransform()); for (auto i = 0 ; i < container->getChildCount() ; i++) { auto child = as<CoreComponent>(container->getChildAt(i)); ASSERT_EQ(Transform2D::translateY(-200 * i), child->getGlobalToLocalTransform()); } component->update(kUpdateScrollPosition, 300); ASSERT_EQ(Transform2D(), component->getGlobalToLocalTransform()); ASSERT_EQ(Transform2D::translateY(300), container->getGlobalToLocalTransform()); for (auto i = 0 ; i < container->getChildCount() ; i++) { auto child = as<CoreComponent>(container->getChildAt(i)); ASSERT_EQ(Transform2D::translateY(-200 * i + 300), child->getGlobalToLocalTransform()); } } static const char *VERTICAL_SEQUENCE = R"apl({ "type": "APL", "version": "1.4", "mainTemplate": { "parameters": [], "item": { "type": "Sequence", "scrollDirection": "vertical", "width": 200, "height": 500, "items": { "type": "Frame", "width": 200, "height": 200 }, "data": [ 1, 2, 3, 4, 5 ] } } } )apl"; TEST_F(ComponentTransformTest, VerticalSequence) { loadDocument(VERTICAL_SEQUENCE); ASSERT_EQ(Transform2D(), component->getGlobalToLocalTransform()); for (auto i = 0 ; i < component->getChildCount() ; i++) { auto child = as<CoreComponent>(component->getChildAt(i)); ASSERT_EQ(Transform2D::translateY(-200 * i), child->getGlobalToLocalTransform()); } component->update(kUpdateScrollPosition, 300); ASSERT_EQ(Transform2D(), component->getGlobalToLocalTransform()); for (auto i = 0 ; i < component->getChildCount() ; i++) { auto child = as<CoreComponent>(component->getChildAt(i)); ASSERT_EQ(Transform2D::translateY(-200 * i + 300), child->getGlobalToLocalTransform()); } } static const char *HORIZONTAL_SEQUENCE = R"apl({ "type": "APL", "version": "1.4", "mainTemplate": { "parameters": [], "item": { "type": "Sequence", "scrollDirection": "horizontal", "width": 500, "height": 200, "items": { "type": "Frame", "width": 200, "height": 200 }, "data": [ 1, 2, 3, 4, 5 ] } } } )apl"; TEST_F(ComponentTransformTest, HorizontalSequence) { loadDocument(HORIZONTAL_SEQUENCE); ASSERT_EQ(Transform2D(), component->getGlobalToLocalTransform()); for (auto i = 0 ; i < component->getChildCount() ; i++) { auto child = as<CoreComponent>(component->getChildAt(i)); ASSERT_EQ(Transform2D::translateX(-200 * i), child->getGlobalToLocalTransform()); } component->update(kUpdateScrollPosition, 300); ASSERT_EQ(Transform2D(), component->getGlobalToLocalTransform()); for (auto i = 0 ; i < component->getChildCount() ; i++) { auto child = as<CoreComponent>(component->getChildAt(i)); ASSERT_EQ(Transform2D::translateX(-200 * i + 300), child->getGlobalToLocalTransform()); } } static const char *STALENESS_PROPAGATION = R"apl({ "type": "APL", "version": "1.4", "layouts": { "Subcontainer": { "parameters": [ "containerIndex" ], "item": { "type": "Container", "width": 200, "height": 300, "items": { "type": "Text", "text": "${data}", "height": "50" }, "data": [ "item ${containerIndex}.1", "item ${containerIndex}.2", "item ${containerIndex}.3", "item ${containerIndex}.4", "item ${containerIndex}.5" ] } } }, "mainTemplate": { "parameters": [], "item": { "type": "Sequence", "id": "top", "scrollDirection": "vertical", "width": 200, "height": 500, "items": [ { "type": "Subcontainer", "containerIndex": "1" }, { "type": "Subcontainer", "containerIndex": "2" }, { "type": "Subcontainer", "containerIndex": "3" } ] } } } )apl"; TEST_F(ComponentTransformTest, StalenessPropagation) { loadDocument(STALENESS_PROPAGATION); ASSERT_EQ(Transform2D(), component->getGlobalToLocalTransform()); ASSERT_EQ(3, component->getChildCount()); for (auto i = 0 ; i < component->getChildCount(); i++) { auto subcontainer = component->getCoreChildAt(i); ASSERT_EQ(Transform2D::translateY(-300 * i), subcontainer->getGlobalToLocalTransform()); ASSERT_EQ(5, subcontainer->getChildCount()); for (auto j = 0; j < subcontainer->getChildCount(); j++) { auto text = subcontainer->getCoreChildAt(j); ASSERT_EQ(Transform2D::translateY(-300 * i - 50 * j), text->getGlobalToLocalTransform()); } } component->update(kUpdateScrollPosition, 400); ASSERT_EQ(Transform2D(), component->getGlobalToLocalTransform()); ASSERT_EQ(3, component->getChildCount()); for (auto i = 0 ; i < component->getChildCount(); i++) { auto subcontainer = component->getCoreChildAt(i); ASSERT_EQ(Transform2D::translateY(-300 * i + 400), subcontainer->getGlobalToLocalTransform()); ASSERT_EQ(5, subcontainer->getChildCount()); for (auto j = 0; j < subcontainer->getChildCount(); j++) { auto text = subcontainer->getCoreChildAt(j); ASSERT_EQ(Transform2D::translateY(-300 * i + 400 - 50 * j), text->getGlobalToLocalTransform()); } } ASSERT_TRUE(TransformComponent(root, "top", "translateX", 100)); ASSERT_EQ(Transform2D::translateX(-100), component->getGlobalToLocalTransform()); ASSERT_EQ(3, component->getChildCount()); for (auto i = 0 ; i < component->getChildCount(); i++) { auto subcontainer = component->getCoreChildAt(i); ASSERT_EQ(Transform2D::translate(-100, -300 * i + 400), subcontainer->getGlobalToLocalTransform()); ASSERT_EQ(5, subcontainer->getChildCount()); for (auto j = 0; j < subcontainer->getChildCount(); j++) { auto text = subcontainer->getCoreChildAt(j); ASSERT_EQ(Transform2D::translate(-100, -300 * i + 400 - 50 * j), text->getGlobalToLocalTransform()); } } }
[ "bddufour@amazon.com" ]
bddufour@amazon.com
ef0bedb9cf72da7b16e052064af77b8f0e40092e
b1b281d17572e71b7e1d4401a3ec6b780f46b43e
/BOJ/14868/14868.cpp
b7888b33eaf27f3fc69408de819f3b564f1b2a4a
[]
no_license
sleepyjun/PS
dff771429a506d7ce90d89a3f7e4e184c51affed
70e77616205c352cc4a23b48fa2d7fde3d5786de
refs/heads/master
2022-12-21T23:25:38.854489
2022-12-12T07:55:26
2022-12-12T07:55:26
208,694,798
0
0
null
null
null
null
UTF-8
C++
false
false
2,187
cpp
// https://www.acmicpc.net/problem/14868 #include <iostream> #include <algorithm> #include <limits> #include <vector> #include <string> #include <queue> #include <tuple> #include <cmath> using std::cin; using std::cout; using ull = unsigned long long; using pii = std::pair<int, int>; const int INF = std::numeric_limits<int>::max(); using std::make_tuple; const int DIST[4][2] = { {0,1}, {0,-1}, {1,0}, {-1,0} }; int visited[2001][2001]; // idx'll be 1-2000 int arr[100001]; int find(int n) { if(arr[n] < 0) return n; return arr[n] = find(arr[n]); } void merge(int p, int c) { p = find(p); c = find(c); if(p == c) return; arr[p] += arr[c]; arr[c] = p; } int main() { std::ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, k; cin >> n >> k; std::fill(arr, arr+k+1, -1); //init order must y x! int cnt=1; std::queue<std::tuple<int,int,int> > q; for(int i = 0; i < k; ++i) { int x,y; cin >> x >> y; q.push(make_tuple(y,x,cnt)); visited[y][x] = cnt; for(int j = 0; j < 4; ++j) { int ny = y + DIST[j][0]; int nx = x + DIST[j][1]; if(ny < 1 || ny > n || nx < 1 || nx > n) continue; if(visited[ny][nx] != 0 && visited[ny][nx] != cnt) merge(cnt, visited[ny][nx]); } cnt++; } //bfs int res=0; cnt=k; while(!q.empty()) { int qSize = q.size(); if(abs(arr[find(1)]) == cnt) break; for(int i = 0; i < qSize; ++i) { auto curr = q.front(); q.pop(); int cy = std::get<0>(curr); int cx = std::get<1>(curr); int cg = std::get<2>(curr); for(int j = 0; j < 4; ++j) { int ny = cy + DIST[j][0]; int nx = cx + DIST[j][1]; if(ny < 1 || ny > n || nx < 1 || nx > n) continue; if(visited[ny][nx] == 0) { visited[ny][nx] = cg; arr[find(cg)]--; cnt++; q.push(make_tuple(ny,nx,cg)); for(int h = 0; h < 4; ++h) { int nny = ny + DIST[h][0]; int nnx = nx + DIST[h][1]; if(nny < 1 || nny > n || nnx < 1 || nnx > n) continue; if(visited[nny][nnx] != 0 && visited[nny][nnx] != cg) merge(cg, visited[nny][nnx]); } } } } res++; } cout << res << '\n'; }//find . -type f -name "*.cpp" -exec g++ {} -o a -std=c++11 \;
[ "sleepyjunh@gmail.com" ]
sleepyjunh@gmail.com
46812e06e57ad3b1a3b1c7e00738d7abee1e1bd2
4c382ec76996f80c37087038fe3f65497edecca8
/stdio/writer.cc
90de65482e32b5d0fddee531ff5e7f5de0048d12
[]
no_license
Conzxy/APUE
55e1ba9819873f4bdd20789071e1d305310e4f78
e956cc4ef63eda6004202fa7d4254a9b7dfdd3ca
refs/heads/master
2023-06-12T21:33:11.471998
2021-07-11T14:47:03
2021-07-11T14:47:03
361,752,494
0
0
null
null
null
null
UTF-8
C++
false
false
333
cc
#include "/home/conzxy/zxy/IO/myio.h" #include <memory> #include <noncopyable.h> #include <vector> using namespace zxy; struct A : public noncopyable{ A(){} }; int main() { auto pw = std::make_unique<FileWriter>("file"); std::vector<FileWriter> vec{}; vec.emplace_back("file"); std::vector<A> vec2{}; vec2.emplace_back(); }
[ "1967933844@qq.com" ]
1967933844@qq.com
98748d68a6d2e56c590247fb27e31d140e2119f0
8dc84558f0058d90dfc4955e905dab1b22d12c08
/chrome/browser/vr/elements/invisible_hit_target.cc
2db584b2d0f4f6f34248625b2e3eebb8b7268c72
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
739
cc
// 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 "chrome/browser/vr/elements/invisible_hit_target.h" namespace vr { InvisibleHitTarget::InvisibleHitTarget() { set_hit_testable(true); } InvisibleHitTarget::~InvisibleHitTarget() = default; void InvisibleHitTarget::Render(UiElementRenderer* renderer, const CameraModel& model) const {} void InvisibleHitTarget::OnHoverEnter(const gfx::PointF& position) { UiElement::OnHoverEnter(position); hovered_ = true; } void InvisibleHitTarget::OnHoverLeave() { UiElement::OnHoverLeave(); hovered_ = false; } } // namespace vr
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
f318fd5debe2fd853fe45a4b92b7f9089c6a4a37
f249cdd0ff50f6d663ddbe275de787f43d37fc49
/day1.cpp
bcd71525f3b60c19a6716ff4e97f100da918e215
[]
no_license
ShrutiAggarwal99/Quaren-Ten-Code
3c84bbaaf0777e457acc67da3568bd2da700e886
f2bfcdd47419d73bdb82dc34819d3cc26faad8e3
refs/heads/master
2021-05-26T03:01:13.175062
2020-04-12T06:29:43
2020-04-12T06:29:43
254,025,654
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
// Link to problem : https://www.linkedin.com/posts/women-who-code-delhi_hi-everyone-here-is-the-question-for-day-activity-6652452326193881088-Wl7Z int threeSumClosest(vector<int>& nums, int target) { int n = nums.size(), minDiff = INT_MAX, ans = 0; sort(nums.begin(),nums.end()); for(int i=0;i<n;i++){ int st = i+1, en = n-1; while(st<en){ int curSum = nums[i] + nums[st] +nums[en]; int curDiff = abs(curSum-target); if(minDiff > curDiff){ minDiff = curDiff; ans = curSum; } if(curSum<target) st++; else if(curSum>target) en--; else return target; } } return ans; }
[ "noreply@github.com" ]
ShrutiAggarwal99.noreply@github.com
7b13c4ab1643c2422ca0f839b301add59a00e982
25668cffd1e5a1717eb07b665ce983910bfa9a56
/clientserver/test/projserver.cc
ded1c3d32bfa343fa4f0aedc316d7d7460204ba5
[]
no_license
LinneaSN/Projekt_eda031
ff8814225cfcd9e6f624389c740be0f931cf4f7a
75a5999a591e3c3b7a4f99438faf398d77dbb4b7
refs/heads/master
2021-01-10T17:01:16.649360
2016-04-18T11:01:50
2016-04-18T11:01:50
54,546,569
0
0
null
null
null
null
UTF-8
C++
false
false
2,429
cc
/* myserver.cc: sample server program */ #include "server.h" #include "connection.h" #include "connectionclosedexception.h" #include "messageHandler.h" #include "protocol.h" #include "newsgroup.h" #include "article.h" #include <memory> #include <iostream> #include <string> #include <stdexcept> #include <cstdlib> #include <algorithm> using namespace std; int main(int argc, char* argv[]){ if (argc != 2) { cerr << "Usage: myserver port-number" << endl; exit(1); } int port = -1; try { port = stoi(argv[1]); } catch (exception& e) { cerr << "Wrong port number. " << e.what() << endl; exit(1); } Server server(port); if (!server.isReady()) { cerr << "Server initialization error." << endl; exit(1); } vector<Newsgroup> newsgroups; while (true) { auto conn = server.waitForActivity(); if (conn != nullptr) { try { messageHandler m(*conn); // Read message type unsigned char type = conn->read(); switch (type) { case Protocol::COM_LIST_NG: m.serverListNG(newsgroups); break; case Protocol::COM_CREATE_NG: m.serverCreateNG(newsgroups); break; case Protocol::COM_DELETE_NG: m.serverDeleteNG(newsgroups); break; case Protocol::COM_LIST_ART: m.serverListArt(newsgroups); break; case Protocol::COM_CREATE_ART: m.serverCreateArt(newsgroups); break; case Protocol::COM_DELETE_ART: m.serverDeleteArt(newsgroups); break; case Protocol::COM_GET_ART: m.serverGetArt(newsgroups); break; default: // throw exception cerr << "If you see this, something is wrong!" << endl; break; } } catch (ConnectionClosedException&) { server.deregisterConnection(conn); cout << "Client closed connection" << endl; } } else { conn = make_shared<Connection>(); server.registerConnection(conn); cout << "New client connects" << endl; } } }
[ "elt12mgr@student.lth.se" ]
elt12mgr@student.lth.se
44aa4367113bb66a71f705c1384f05b74317890a
107d130d6bea2716c6dea82a9cb6e1434f8c631a
/main.h
5d29397d2df56d8be45073c1ec311e8588f92316
[]
no_license
jwiegley/haskell-to-c
92af600c18d3022e6fa183df562cc856e717a17a
eccb718b9a94b24ddac994c6739cc8624d31d217
refs/heads/master
2021-01-11T14:01:18.171061
2017-06-22T00:59:01
2017-06-22T00:59:01
94,927,729
15
0
null
null
null
null
UTF-8
C++
false
false
562
h
#include <stdio.h> #include <time.h> #include "HsFFI.h" struct Point { time_t moment; double latitude; double longitude; }; #ifdef __cplusplus #include <vector> class Track { std::vector<Point> points; public: Track(const std::vector<Point>& _points) : points(_points) {} }; #else struct Track { struct Point *points; }; #endif #ifdef __cplusplus extern "C" #endif void *c_initState(int); #ifdef __cplusplus extern "C" #endif void c_freeState(void *); #ifdef __cplusplus extern "C" #endif char *c_processTrack(struct Track *, void *, void **);
[ "johnw@newartisans.com" ]
johnw@newartisans.com
c3af8f2b8408a7820c3341580d87e3238fea4858
11220cdbb9643e61d71529f34d054ffc9cd79404
/Client/src/gui/MainWindow.h
d684c88e7a192004e8886614c5aee0278cff612e
[]
no_license
MagnusDrumsTrumpet/JamTaba
bc6ebbb4896c903e64f10e87d8f2b7cf3d3eed45
ec9f41962e60f1730544b25dac6394fa183697cd
refs/heads/master
2021-01-15T08:31:01.341355
2015-11-17T15:53:41
2015-11-17T15:53:41
46,359,666
0
0
null
2015-11-17T16:23:45
2015-11-17T16:23:45
null
UTF-8
C++
false
false
5,764
h
#pragma once #include <QtWidgets/QMainWindow> #include <QMessageBox> #include <QFutureWatcher> #include "ui_MainWindow.h" #include "BusyDialog.h" #include "../ninjam/Server.h" #include "../loginserver/LoginService.h" #include "../persistence/Settings.h" #include "../LocalTrackGroupView.h" #include "../performance/PerformanceMonitor.h" class PluginScanDialog; class NinjamRoomWindow; namespace Controller{ class MainController; } namespace Ui{ class MainFrameClass; class MainFrame; } namespace Login { class LoginServiceParser; //class AbstractJamRoom; } namespace Audio { class Plugin; class PluginDescriptor; } namespace Vst { class PluginDescriptor; } class JamRoomViewPanel; class PluginGui; class LocalTrackGroupView; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(Controller::MainController* mainController, QWidget *parent=0); ~MainWindow(); virtual void closeEvent(QCloseEvent *); virtual void changeEvent(QEvent *); virtual void timerEvent(QTimerEvent *); virtual void resizeEvent(QResizeEvent*); void detachMainController(); Persistence::InputsSettings getInputsSettings() const; inline int getChannelGroupsCount() const{return localChannels.size();} inline QString getChannelGroupName(int index) const{return localChannels.at(index)->getGroupName();} void highlightChannelGroup(int index) const; void addChannelsGroup(QString name); void removeChannelsGroup(int channelGroupIndex); void refreshTrackInputSelection(int inputTrackIndex); void enterInRoom(Login::RoomInfo roomInfo); void exitFromRoom(bool normalDisconnection); bool isRunningAsVstPlugin() const; inline bool isRunningInMiniMode() const{return !fullViewMode;} inline bool isRunningInFullViewMode() const{return fullViewMode;} protected: Controller::MainController* mainController; virtual void initializePluginFinder(); void restorePluginsList(); void centerDialog(QWidget* dialog); QList<LocalTrackGroupView*> localChannels; virtual NinjamRoomWindow* createNinjamWindow(Login::RoomInfo, Controller::MainController*) = 0; virtual void setFullViewStatus(bool fullViewActivated); bool eventFilter(QObject *target, QEvent *event); protected slots: void on_tabCloseRequest(int index); void on_tabChanged(int index); void on_localTrackAdded(); void on_localTrackRemoved(); //themes //void on_newThemeSelected(QAction*); //main menu void on_preferencesClicked(QAction *action); void on_IOPreferencesChanged(QList<bool>, int audioDevice, int firstIn, int lastIn, int firstOut, int lastOut, int sampleRate, int bufferSize); void on_ninjamCommunityMenuItemTriggered(); void on_ninjamOfficialSiteMenuItemTriggered(); void on_privateServerMenuItemTriggered(); //view mode menu void on_menuViewModeTriggered(QAction* action); //help menu void on_reportBugMenuItemTriggered(); void on_wikiMenuItemTriggered(); void on_UsersManualMenuItemTriggered(); //private server void on_privateServerConnectionAccepted(QString server, int serverPort, QString password); //login service void on_roomsListAvailable(QList<Login::RoomInfo> publicRooms); void on_newVersionAvailableForDownload(); void on_incompatibilityWithServerDetected(); virtual void on_errorConnectingToServer(QString errorMsg); //+++++ ROOM FEATURES ++++++++ void on_startingRoomStream(Login::RoomInfo roomInfo); void on_stoppingRoomStream(Login::RoomInfo roomInfo); void on_enteringInRoom(Login::RoomInfo roomInfo, QString password = ""); //plugin finder void onScanPluginsStarted(); void onScanPluginsFinished(); void onPluginFounded(QString name, QString group, QString path); void onScanPluginsStarted(QString pluginPath); //collapse local controls void on_localControlsCollapseButtonClicked(); //channel name changed void on_channelNameChanged(); //xmit void on_xmitButtonClicked(bool checked); //room streamer void on_RoomStreamerError(QString msg); private: BusyDialog busyDialog; void showBusyDialog(QString message); void showBusyDialog(); void hideBusyDialog(); void centerBusyDialog(); void stopCurrentRoomStream(); void showMessageBox(QString title, QString text, QMessageBox::Icon icon); int timerID; QPointF computeLocation() const; QMap<long long, JamRoomViewPanel*> roomViewPanels; QScopedPointer<PluginScanDialog> pluginScanDialog; Ui::MainFrameClass ui; QScopedPointer<NinjamRoomWindow> ninjamWindow; QScopedPointer<Login::RoomInfo> roomToJump;//store the next room reference when jumping from on room to another QString passwordToJump; void showPluginGui(Audio::Plugin* plugin); static bool jamRoomLessThan(Login::RoomInfo r1, Login::RoomInfo r2); void initializeWindowState(); void initializeLoginService(); void initializeLocalInputChannels(); //void initializeVstFinderStuff(); //void initializeMainControllerEvents(); void initializeMainTabWidget(); void initializeViewModeMenu(); QStringList getChannelsNames() const; LocalTrackGroupView* addLocalChannel(int channelGroupIndex, QString channelName, bool createFirstSubchannel); bool fullViewMode;//full view or mini view mode? void refreshPublicRoomsList(QList<Login::RoomInfo> publicRooms); void showPeakMetersOnlyInLocalControls(bool showPeakMetersOnly); void recalculateLeftPanelWidth(); PerformanceMonitor performanceMonitor;//cpu and memmory usage qint64 lastPerformanceMonitorUpdate; static const int PERFORMANCE_MONITOR_REFRESH_TIME; };
[ "elieserdejesus@gmail.com" ]
elieserdejesus@gmail.com
68a862b4cd8d34bfb6d8192efa2a868a7ebd8979
43466493fd6fb5d81b4419564674d79d43cfc693
/src/ImageProcessing/MovementDetectorMOG2.cpp
581e5ab9ca4d253e4b05f109733f9774ad662f3e
[ "MIT" ]
permissive
concurs-program/SecMon
4ede568d52ef945e4be1e59c4fd1f2389da947ac
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
refs/heads/master
2021-12-23T06:56:23.220320
2017-11-03T14:38:50
2017-11-03T14:38:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,346
cpp
/* * MovementDetectorMOG2.cpp * * Created on: Oct 18, 2017 * Author: richard */ #include "MovementDetectorMOG2.h" #include <opencv2/opencv.hpp> #include <memory> #include <vector> #include "../Frame.h" MovementDetectorMOG2::MovementDetectorMOG2() : pMOG2(cv::createBackgroundSubtractorMOG2(25,10)) { // TODO Auto-generated constructor stub } MovementDetectorMOG2::~MovementDetectorMOG2() { // TODO Auto-generated destructor stub } void MovementDetectorMOG2::process_next_frame(std::shared_ptr<Frame>& current_frame) { cv::Mat& image_current = current_frame->get_original_image(); cv::Mat& difference_image = current_frame->get_new_image("difference"); difference_image.reshape(CV_8UC1); cv::Mat& foreground_image = current_frame->get_new_blank_image("foreground"); // foreground_image.zeros(image_current.size(), CV_8UC1); // cv::Mat temp; // temp.zeros(image_current.size(), CV_8UC1); pMOG2->apply(image_current, difference_image); refineSegments(difference_image, foreground_image); } void MovementDetectorMOG2::refineSegments(const cv::Mat& mask, cv::Mat& dst) { int niters = 3; std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::Mat temp; cv::dilate(mask, temp, cv::Mat(), cv::Point(-1,-1), niters); cv::erode(temp, temp, cv::Mat(), cv::Point(-1,-1), niters*2); cv::dilate(temp, temp, cv::Mat(), cv::Point(-1,-1), niters); cv::findContours( temp, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE ); if( contours.empty() ) { std::cout << "NO contours found!!" << std::endl; return; } // iterate through all the top-level contours, // draw each connected component with its own random color int idx = 0;//, largestComp = 0; // double maxArea = 0; for( ; idx >= 0; idx = hierarchy[idx][0] ) { cv::drawContours( dst, contours, idx, cv::Scalar(255,0,0), cv::FILLED, cv::LINE_8, hierarchy ); // const std::vector<cv::Point>& c = contours[idx]; // double area = std::fabs(cv::contourArea(cv::Mat(c))); // if( area > maxArea ) // { // maxArea = area; // largestComp = idx; // } } // cv::Scalar color( 255, 255, 255 ); // cv::drawContours( dst, contours, largestComp, color, cv::FILLED, cv::LINE_8, hierarchy ); }
[ "rcstilborn@gmail.com" ]
rcstilborn@gmail.com
091d88cb36f81f1871ced48a7f448e0df2648b53
e88590d79aa886234035a8ac48ef915e89ca8e1b
/leetcode/[883] Projection Area of 3D Shapes/883.projection-area-of-3d-shapes.cpp
1bdb4626f28074126ccd7945e24f2f3da928d2fd
[]
no_license
ymytheresa/algo-practices
cd659e0a16e14f75ebc7e13b472ef0e8da881347
c34ca06ca74ca7d96a3469add3b7446b836872e8
refs/heads/master
2022-11-22T23:14:38.173232
2020-07-28T14:26:29
2020-07-28T14:38:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,899
cpp
/* * @lc app=leetcode id=883 lang=cpp * * [883] Projection Area of 3D Shapes */ // @lc code=start /*** [vim-leetcode] For Local Syntax Checking ***/ #define DEPENDENCIES #ifdef DEPENDENCIES #include <iostream> #include <iomanip> #include <istream> #include <ostream> #include <sstream> #include <stdio.h> #include <vector> #include <stack> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <list> #include <forward_list> #include <array> #include <deque> #include <queue> #include <bitset> #include <utility> #include <algorithm> #include <string> #include <limits> using namespace std; #endif class Solution { public: int projectionArea(vector<vector<int>>& grid) { int topShadow = 0, frontShadow = 0, sideShadow = 0; vector<int> greatestHeightOnRows, greatestHeightOnCols; for (int rowIdx = 0; rowIdx < grid.size(); rowIdx++){ vector<int> row = grid[rowIdx]; greatestHeightOnRows.resize(greatestHeightOnRows.size() + 1, 0); for (int colIdx = 0; colIdx < row.size(); colIdx++){ int height = row[colIdx]; if (height > 0) topShadow++; greatestHeightOnRows[rowIdx] = max(greatestHeightOnRows[rowIdx], height); if (greatestHeightOnCols.size() <= colIdx + 1) greatestHeightOnCols.resize(greatestHeightOnCols.size() + 1, 0); greatestHeightOnCols[colIdx] = max(greatestHeightOnCols[colIdx], height); } } for (auto height = greatestHeightOnRows.cbegin(); height != greatestHeightOnRows.cend(); height++) frontShadow += *height; for (auto height = greatestHeightOnCols.cbegin(); height != greatestHeightOnCols.cend(); height++) sideShadow += *height; return topShadow + frontShadow + sideShadow; } }; // @lc code=end
[ "ben.cky.workspace@gmail.com" ]
ben.cky.workspace@gmail.com
166b97b5b0e02344f40c795972b8bc9a472c5cf0
5381e854df6714faaa52385a8d8c082ce6199e1f
/zad79/zad79.cpp
7ea5c2d82aa0cadf8400679f77df9b5dcb722de1
[]
no_license
adrianjekiel/zadania
4d288d6cf9db6bfa81a1873c40dc434772055fdb
f0a1a645d144d0fe857116d1be9122ca8d6fcd79
refs/heads/master
2020-08-06T01:27:21.761509
2020-06-06T09:39:05
2020-06-06T09:39:05
212,783,983
1
1
null
2022-11-06T19:18:22
2019-10-04T09:53:29
C++
UTF-8
C++
false
false
5,163
cpp
#include <iostream> #include <fstream> #include <vector> #include <string> #include <cmath> using namespace std; struct okrag //nazwy structur duza litera { double x; double y; double r; }; vector<okrag> wczytaj (const string& nazwa) { vector<okrag> okregi; ifstream input(nazwa); if(input.is_open()) { for(int i=0;i<2000;i++) { okrag temp; input>>temp.x; input>>temp.y; input>>temp.r; okregi.push_back(temp); } } input.close(); return okregi; } void zapisz (const string& nazwa, const vector<string> odp) { string temp; ofstream output(nazwa); if(output.is_open()) { for(auto s: odp) { output << s <<endl; } } output.close(); } vector<string> zad1 (const vector<okrag> okregi) { vector<string> odp; int Icw=0; int IIcw=0; int IIIcw=0; int IVcw=0; int zadna=0; for(okrag temp:okregi) { if(temp.x>0 and temp.y >0) //Icw { if((temp.x-temp.r)>0 and (temp.y-temp.r)>0) { Icw++; } else { zadna++; } } if(temp.x<0 and temp.y>0)//IIcw { if(((temp.x*-1)-temp.r)>0 and (temp.y-temp.r)>0) { IIcw++; } else { zadna++; } } if(temp.x<0 and temp.y<0)//IIIcw { if(((temp.x*-1)-temp.r)>0 and ((temp.y*-1)-temp.r)>0) { IIIcw++; } else { zadna++; } } if(temp.x>0 and temp.y<0)//IVcw { if((temp.x-temp.r)>0 and ((temp.y*-1)-temp.r)>0) { IVcw++; } else { zadna++; } } } odp.push_back("zad1:"); odp.push_back("liczba okregow I cwartki: " + to_string(Icw)); odp.push_back("liczba okregow II cwartki: " + to_string(IIcw)); odp.push_back("liczba okregow III cwartki: " + to_string(IIIcw)); odp.push_back("liczba okregow IV cwartki: " + to_string(IVcw)); odp.push_back("liczba okregow, ktore nie zawieraja sie w zadnej cwiartce: " + to_string(zadna)); return odp; } bool czy_odbicie (const okrag& o1,const okrag& o2) { if(o1.r==o2.r) { if(o1.x == o2.x and o1.y == -o2.y or o1.x ==-o2.x and o1.y == o2.y) { return true; } } return false; } string zad2 (const vector<okrag>& okregi) { int pary=0; for(int i=1;i<okregi.size();i++) { for(int l=0;l<i;l++) { if(czy_odbicie(okregi[i],okregi[l])) { pary++; } } } return "zad2: liczba lustrzanych par: " + to_string(pary); } bool czy_prostopadle(const okrag& o1, const okrag& o2) { if(o1.r==o2.r) { if(o1.x == o2.y and o1.y == -o2.x or o1.x ==-o2.y and o1.y == o2.x) { return true; } } return false; } string zad3 (const vector<okrag>& okregi) { int pary_90=0; for(int i=1;i<okregi.size();i++) { for(int l=0;l<i;l++) { if(czy_prostopadle(okregi[i],okregi[l])) { pary_90++; } } } return "zad3: liczba prostopadlych par: " + to_string(pary_90); } bool czy_przeciecie(const okrag& o1, const okrag& o2) { double s1s2 = sqrt(pow((o2.x-o1.x),2)+pow(o2.y-o1.y,2)); double ro = abs(o1.r-o2.r); double so = o1.r+o2.r; if(ro<=s1s2 and s1s2<=so) { return true; } return false; } vector<string> zad4 (const vector<okrag>& okregi) { vector<string> odp; int max_dl=0; int dl_lancuch=1; for(int i=0; i<999 ;i++) { if(czy_przeciecie(okregi[i],okregi[i+1])) { dl_lancuch++; if(i==998) { odp.push_back("dlugosc kojenego lancucha: " + to_string(dl_lancuch)); } } else { odp.push_back("dlugosc kojenego lancucha: " + to_string(dl_lancuch)); dl_lancuch=1; } if(max_dl<dl_lancuch) { max_dl=dl_lancuch; } } odp.push_back("dlugosc najdluzszego lancucha: " + to_string(max_dl)); return odp; } int main () { vector<string> odp; vector<okrag> dane = wczytaj("okregi.txt"); vector<string> zad1_odp = zad1(dane); string zad2_odp = zad2(dane); string zad3_odp = zad3(dane); vector<string> zad4_odp = zad4(dane); odp.insert(odp.end(),zad1_odp.begin(),zad1_odp.end()); odp.push_back(zad2_odp); odp.push_back(zad3_odp); odp.insert(odp.end(),zad4_odp.begin(),zad4_odp.end()); zapisz("wyniki.txt",odp); }
[ "noreply@github.com" ]
adrianjekiel.noreply@github.com
5850b3d781603623c77d6918b2f41ddf016d86ce
89b7e4a17ae14a43433b512146364b3656827261
/testcases/CWE762_Mismatched_Memory_Management_Routines/s02/CWE762_Mismatched_Memory_Management_Routines__delete_char_calloc_84_goodB2G.cpp
df188da035adbc9ba560c911dd5209f0af9c1bc4
[]
no_license
tuyen1998/Juliet_test_Suite
7f50a3a39ecf0afbb2edfd9f444ee017d94f99ee
4f968ac0376304f4b1b369a615f25977be5430ac
refs/heads/master
2020-08-31T23:40:45.070918
2019-11-01T07:43:59
2019-11-01T07:43:59
218,817,337
0
1
null
null
null
null
UTF-8
C++
false
false
1,508
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_char_calloc_84_goodB2G.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-84_goodB2G.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: calloc Allocate data using calloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE762_Mismatched_Memory_Management_Routines__delete_char_calloc_84.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_char_calloc_84 { CWE762_Mismatched_Memory_Management_Routines__delete_char_calloc_84_goodB2G::CWE762_Mismatched_Memory_Management_Routines__delete_char_calloc_84_goodB2G(char * dataCopy) { data = dataCopy; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (char *)calloc(100, sizeof(char)); if (data == NULL) {exit(-1);} } CWE762_Mismatched_Memory_Management_Routines__delete_char_calloc_84_goodB2G::~CWE762_Mismatched_Memory_Management_Routines__delete_char_calloc_84_goodB2G() { /* FIX: Deallocate the memory using free() */ free(data); } } #endif /* OMITGOOD */
[ "35531872+tuyen1998@users.noreply.github.com" ]
35531872+tuyen1998@users.noreply.github.com
f23a80541be4772969fd8d8ba505056236f795c8
ddbdbc0ce681558fac8d0fad3a5b346bdb8db561
/libSqlData/SqlFindFacePhoto.h
d92701cd2ad58abd2305566c9d0330bb446d9d30
[]
no_license
Trisoil/Regards
9488f4ee31784490e06a24a136a76a45a09910f9
3eda6669f4d1a2043f631f747a6c36fa644c590d
refs/heads/master
2020-05-07T11:57:03.681785
2019-04-09T16:41:14
2019-04-09T16:41:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
987
h
#pragma once #include "SqlExecuteRequest.h" #include "SqlResult.h" #include <FaceDescriptor.h> #include <FaceName.h> #include <FaceFilePath.h> namespace Regards { namespace Sqlite { class CSqlFindFacePhoto : public CSqlExecuteRequest { public: CSqlFindFacePhoto(); ~CSqlFindFacePhoto(); std::vector<wxString> GetPhotoListNotProcess(); std::vector<CFaceName> GetListFaceName(); std::vector<CFaceName> GetListFaceName(const wxString &photoPath); std::vector<CFaceName> GetListFaceNameSelectable(); std::vector<CFaceFilePath> GetListPhotoFace(const int &numFace, const double &pertinence = 0.0); std::vector<CFaceDescriptor *> GetUniqueFaceDescriptor(const int &numFace); private: int TraitementResult(CSqlResult * sqlResult); std::vector<wxString> listPhoto; std::vector<CFaceDescriptor *> listFaceDescriptor; std::vector<CFaceName> listFaceName; std::vector<CFaceFilePath> listFace; int type; }; } }
[ "jfiguinha@hotmail.fr" ]
jfiguinha@hotmail.fr
b323aee36c3dbebf06533555af93831cf4340a8a
afbf80a9a3d28e967f419881dc89cc2575bea717
/week 3/lengthConvert.cpp
aa33333756e29757a59cfc39a6b934ab69775b97
[]
no_license
NerdiusMaximus/Intermediate_CPP_Programing_Fall_2015
0162eb862734a07146d86b22d48166051f68cbb7
34e17ec431eb08be1be57a365d20aa102111fae0
refs/heads/master
2021-01-10T15:52:26.127910
2015-12-16T03:30:17
2015-12-16T03:30:17
43,849,114
0
0
null
null
null
null
UTF-8
C++
false
false
4,214
cpp
/* Intermediate CPP Fall 2015 Michael Lowry 10/20/2015 Week 3 hw Programming Project #4 Problem Statement: Write a program that will read in a length in feet and inches and output the length in meters and centimeters. Use at least three functions: one for input, one for calculating, and one for output. Include a loop that lets the user repeat this computation for new input values until the user says he or she wants to end the program. There are 0.3048 meters in a foot, 100 centimeters in a meter, and 12 inches in a foot. */ #include <iostream> #define M_PER_F 0.3048 #define CM_PER_M 100 #define IN_PER_FT 12 #define MM_PER_M 1000 #define DEBUG using namespace std; void getLength(double& feet, double& inches); void computeMetric(double& feet, double& inches, double& meters, double& centimeters); void outputLength(double meters, double centimeters); int main(){ //declare variables double feet(0), inches(0), meters(0), centimeters(0); char cont = 0; cout << "Length Converter Program\n"; do{ //reset values for each loop feet = 0; inches = 0; meters = 0; centimeters = 0; cont = 0; getLength(feet, inches); computeMetric(feet, inches, meters, centimeters); outputLength(meters,centimeters); cout << "\n\nWould you like to continue?\n(Y/N): "; cin >> cont; }while ((cont== 'Y' || cont == 'y')); cout << "\n\n Program Complete! God bless the Metric System!\n"; return 0; } void getLength(double& feet, double& inches) { cout <<"\nPlease enter the lengh in feet: "; cin >> feet; cout <<"\nPlease enter the length in inches: "; cin >> inches; return; }//end getTime void computeMetric(double& feet, double& inches, double& meters, double& centimeters) { //convert feet to inches double tempFeet = (inches / IN_PER_FT) + feet; //add the feet to the fractional foot from inches meters = tempFeet * M_PER_F; //multiply by constant meters per foot #ifdef DEBUG cout << "meters = " << meters << endl; #endif centimeters = (meters - (int)meters%MM_PER_M) * CM_PER_M; #ifdef DEBUG cout << "centimeters = " << centimeters << endl; #endif } void outputLength(double meters, double centimeters) { //format the output to 0 decimal places cout.setf(ios::fixed); //cout.setf(ios::showpoint); cout.precision(0); cout << "\nThe length in Metric is: " << meters << " M "; //cout.precision(2); cout << centimeters << " cm. \n\n"; } /* Results: Length Converter Program Please enter the lengh in feet: 10 Please enter the length in inches: 6 meters = 3.2004 centimeters = 20.04 The length in Metric is: 3 M 20 cm. Would you like to continue? (Y/N): y Please enter the lengh in feet: 1 Please enter the length in inches: 6 meters = 0 centimeters = 46 The length in Metric is: 0 M 46 cm. Would you like to continue? (Y/N): y Please enter the lengh in feet: 0 Please enter the length in inches: 6 meters = 0 centimeters = 15 The length in Metric is: 0 M 15 cm. Would you like to continue? (Y/N): n Program Complete! God bless the Metric System! -------------------------------- Process exited after 43.19 seconds with return value 0 Press any key to continue . . . ****************************************************** HIGHER PRECISION IN cm VALUE IF UNCOMMENT LINE 87 Length Converter Program Please enter the lengh in feet: 10 Please enter the length in inches: 6 meters = 3.2004 centimeters = 20.04 The length in Metric is: 3 M 20.04 cm. Would you like to continue? (Y/N): y Please enter the lengh in feet: 1 Please enter the length in inches: 6 meters = 0.46 centimeters = 45.72 The length in Metric is: 0 M 45.72 cm. Would you like to continue? (Y/N): y Please enter the lengh in feet: 0 Please enter the length in inches: 6 meters = 0.15 centimeters = 15.24 The length in Metric is: 0 M 15.24 cm. Would you like to continue? (Y/N): y Please enter the lengh in feet: 150 Please enter the length in inches: 3.5 meters = 45.81 centimeters = 80.89 The length in Metric is: 46 M 80.89 cm. Would you like to continue? (Y/N): n Program Complete! God bless the Metric System! -------------------------------- Process exited after 36.83 seconds with return value 0 Press any key to continue . . . */
[ "mtl6@njit.edu" ]
mtl6@njit.edu
3769d46d8dceb403cd2b52d84e36d8fe75b9e935
146542135913a605f82fa24273ae0ebd6358d12a
/GRAPH_ALGORITHM_ASSIGNMENT/Codes/Breadth_first.search.cpp
a72881336e8cde4941ca4e6e0bd7230da3c99d09
[]
no_license
nitcse2018/daa-Yogesh-2527
36df839785939d008934e8c45b1638224f006850
135ab321cb0f3e05989b5141ce9ecd9ef18985ff
refs/heads/master
2023-02-09T05:12:11.532881
2020-12-30T08:39:21
2020-12-30T08:39:21
256,048,631
0
0
null
null
null
null
UTF-8
C++
false
false
1,258
cpp
#include<iostream> #include <list> using namespace std; class Graph { int V; list<int> *adj; public: Graph(int V); void addEdge(int v, int w); void BFS(int s); }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); } void Graph::BFS(int s) { bool *visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; list<int> queue; visited[s] = true; queue.push_back(s); list<int>::iterator i; while(!queue.empty()) { s = queue.front(); cout << s << " "; queue.pop_front(); for (i = adj[s].begin(); i != adj[s].end(); ++i) { if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } } } int main() { Graph g(7); g.addEdge(1, 2); g.addEdge(1, 3); g.addEdge(2, 4); g.addEdge(2, 5); g.addEdge(3, 6); g.addEdge(3, 7); cout << "Breadth First Traversal (starting from vertex 1) \n"; g.BFS(1); return 0; }
[ "noreply@github.com" ]
nitcse2018.noreply@github.com
ef8bcdf2da92698885f8afcf398c4795eba182f7
a1441c09bcc62f83d46f78027ad32dd00751e9e2
/app/src/main/cpp/native-lib.cpp
b1cfc49eea20f22c05a459cda9a8385b958ce3a1
[]
no_license
djc512/DNKTest
146f69af724b1853e1304d0e42ab5fe88e3b5dfc
4c16af7c56372125e36c148e2b8355748fd8c2cd
refs/heads/master
2021-01-24T23:57:27.845381
2018-03-09T12:43:04
2018-03-09T12:43:04
123,285,025
1
0
null
null
null
null
UTF-8
C++
false
false
18,885
cpp
#include <jni.h> #include <string> #include <string.h> #include <stdlib.h> #include <android/log.h> #define TAG "DJC_JNI" // 这个是自定义的LOG的标识 #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定义LOGI类型 #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) // 定义LOGD类型 #define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) // 定义LOGW类型 #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) // 定义LOGE类型 #define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) // 定义LOGF类型 char *jstringToChar(JNIEnv *env, jstring jstr) { char *rtn = NULL; jclass clsstring = env->FindClass("java/lang/String"); jstring strencode = env->NewStringUTF("GB2312"); jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B"); jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode); jsize alen = env->GetArrayLength(barr); jbyte *ba = env->GetByteArrayElements(barr, JNI_FALSE); if (alen > 0) { rtn = (char *) malloc(alen + 1); memcpy(rtn, ba, alen); rtn[alen] = 0; } env->ReleaseByteArrayElements(barr, ba, 0); return rtn; } extern "C" JNIEXPORT jstring JNICALL Java_com_example_admin_dnktest_MainActivity_stringFromJNI( JNIEnv *env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); } extern "C" JNIEXPORT jstring JNICALL Java_com_example_admin_dnktest_MainActivity_helloWorld(JNIEnv *env, jobject instance) { return env->NewStringUTF("HelloWorld"); } extern "C" JNIEXPORT jstring JNICALL Java_com_example_admin_dnktest_MainActivity_getString(JNIEnv *env, jobject instance, jstring str_) { const char *str = env->GetStringUTFChars(str_, 0); // 将java层传递的参数,转换成c语言可以识别的UTF格式,传递给底层 env->ReleaseStringUTFChars(str_, str);//释放内存 return env->NewStringUTF("传递给底层"); } extern "C" JNIEXPORT jint JNICALL Java_com_example_admin_dnktest_MainActivity_sumArray(JNIEnv *env, jobject instance, jintArray arr_) { jint i; jint sum = 0; jint len = env->GetArrayLength(arr_); jint buf[len]; // GetIntArrayRegion // 将一个int数组中的所有元素复制到一个C缓冲区中,然后本地代码在C缓冲区中的访问这些元素 env->GetIntArrayRegion(arr_, 0, 10, buf); for (i = 0; i < 10; i++) { sum += buf[i]; } return sum; } extern "C" JNIEXPORT jint JNICALL Java_com_example_admin_dnktest_MainActivity_sumArrayOther(JNIEnv *env, jobject instance, jintArray arr_) { jint len = env->GetArrayLength(arr_); //获取数组的长度 jint *arr = env->GetIntArrayElements(arr_, NULL); //获取本地代码指向基本数据类型数组的指针(相当于一个数组) //防止内存不够用,获取不到 if (arr == NULL) { return 0; } jint i, sum = 0; for (i = 0; i < len; i++) { sum += arr[i]; } env->ReleaseIntArrayElements(arr_, arr, 0); //释放所占用的内存 return sum; } extern "C" JNIEXPORT jobjectArray JNICALL Java_com_example_admin_dnktest_MainActivity_getArray(JNIEnv *env, jobject instance, jint size) { //获取数据的引用类型 jclass intArrCls = env->FindClass("[I"); //创建一个数组对象 jobjectArray result = env->NewObjectArray(size, intArrCls, NULL); //内存不够用抛出异常 if (result == NULL) { return NULL; } //size 创建数组的长度 jint i; for (i = 0; i < size; i++) { //创建一个整形数组(数组对象的元素) jintArray intArr = env->NewIntArray(size); //内存泄漏抛出异常 if (intArr == NULL) { return NULL; } jint temp[256];//创建一个足够大的整形数组,作为本地数据缓存 jint j; //给创建的整形数组赋值 for (int j = 0; j < size; j++) { temp[j] = j; } //将缓冲区的元素复制给创建的整形数组 env->SetIntArrayRegion(intArr, 0, size, temp); //给数组对象赋值 env->SetObjectArrayElement(result, i, intArr); //释放内存 env->DeleteLocalRef(intArr); } return result; //jn中无法直接创建二维数组,所以创建一个元素类型为int数组的一维数组,具体步骤:先创建一个int数组的引用,然后创建一个数组对象,在创建一个整形的数组,然后整形素组进行赋值 //赋值的时候对于基本数据类型,如果元素不是很多,可以通过GetArrayIntRegion方法先把数据复制到本地缓存,操作本地缓存操作元素数据 //对于引用数据类型,则可以使用jobjectArray,GetObjectArrayElement() 进行元素的操作,结束要释放内存 } extern "C" JNIEXPORT void JNICALL Java_com_example_admin_dnktest_MainActivity_getModifyString(JNIEnv *env, jobject instance) { //通过对象获取类的引用 jclass cls = env->GetObjectClass(instance); //获取变量的属性ID jfieldID fidStr = env->GetFieldID(cls, "str", "Ljava/lang/String;"); jfieldID fidInt = env->GetFieldID(cls, "value", "I"); if (fidStr == NULL || fidInt == NULL) { return; } env->SetIntField(instance, fidInt, 200); //通过fid获取属性的对象 jstring jstr = (jstring) env->GetObjectField(instance, fidStr); //获取UTF的字符串 const char *str = env->GetStringUTFChars(jstr, NULL); __android_log_print(ANDROID_LOG_INFO, "DJC", "jstr = %s", str); if (str == NULL) { return; } //释放掉这个字符串 env->ReleaseStringUTFChars(jstr, str); //从新创建一个字符串 jstr = env->NewStringUTF("123"); if (jstr == NULL) { return; } //通过属性ID进行赋值 env->SetObjectField(instance, fidStr, jstr); //NewStringUTF()方法创建的字符串是用于java层的使用 //NewStringUTFChar()创建的字符串是用于jni层C语言使用的 //访问一个对象字段的流程:先获取这个对象对应的类的引用,然后获取属性ID,通过获取属性ID获取属性值,获取他在本地代码中所转换成的数值,然后将其释放掉,在重新创建,然后通过属性ID赋值 //对于基本数据类型就不用这么麻烦,获取属性ID直接调用函数进行修改 } extern "C" JNIEXPORT void JNICALL Java_com_example_admin_dnktest_MainActivity_findMethod(JNIEnv *env, jobject instance) { //通过对象获取类的引用 jclass cls = env->GetObjectClass(instance); //获取方法的ID jmethodID methodID = env->GetMethodID(cls, "printLog", "()V"); if (methodID == NULL) { return; } //通过methodID访问方法 env->CallVoidMethod(instance, methodID); } extern "C" JNIEXPORT jint JNICALL Java_com_example_admin_dnktest_MainActivity_add(JNIEnv *env, jobject instance, jint a, jint b) { jint sum; sum = a + b; __android_log_print(ANDROID_LOG_INFO, "DJC", "HELLO"); __android_log_print(ANDROID_LOG_INFO, "DJC", "sum = %d", sum); return sum; //jni层输出日志,需要引入头文件(类似包)android/log.h //调用函数__android_log_print() //第一个参数表示log的类型 //第二个参数表示Tag标识 //第三个参数 "sum = %d" 表示打印的参数类型 } extern "C" JNIEXPORT jstring JNICALL Java_com_example_admin_dnktest_MainActivity_getAppendStr(JNIEnv *env, jobject instance, jstring str_) { // const char *str = env->GetStringUTFChars(str_, 0); char *str = jstringToChar(env, str_); char *add = "add i am add"; __android_log_print(ANDROID_LOG_INFO, "DJC", "add = %s", add); strcat(str, add); // strcat((char *) str, add); // env->ReleaseStringUTFChars(str_, str); return env->NewStringUTF(str); } jclass cls; jclass globalCls; jclass familyCls; jclass globalFamilyCls; jfieldID nameID; jfieldID ageID; jfieldID familyID; jmethodID methodID; jfieldID familyNameID; jfieldID familyAgeID; jmethodID familyMethodID; extern "C" JNIEXPORT jlong JNICALL Java_com_example_admin_dnktest_MainActivity_init(JNIEnv *env, jobject instance) { cls = env->FindClass("com/example/admin/dnktest/TestBean"); if (cls == NULL) { return 0; } globalCls = (jclass) env->NewGlobalRef(cls); if (globalCls == NULL) { return 0; } //获取ID nameID = env->GetFieldID(globalCls, "name", "Ljava/lang/String;"); ageID = env->GetFieldID(globalCls, "age", "I"); familyID = env->GetFieldID(globalCls, "family", "Lcom/example/admin/dnktest/Family;"); methodID = env->GetMethodID(globalCls, "<init>", "()V"); if (nameID == NULL || ageID == NULL || familyID == NULL || methodID == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "ID获取失败"); return 0; } familyCls = env->FindClass("com/example/admin/dnktest/Family"); if (familyCls == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "类创建失败"); return 0; } globalFamilyCls = (jclass) env->NewGlobalRef(familyCls); if (globalFamilyCls == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "对象创建失败"); return 0; } familyNameID = env->GetFieldID(globalFamilyCls, "familyName", "Ljava/lang/String;"); familyAgeID = env->GetFieldID(globalFamilyCls, "familyAge", "I"); familyMethodID = env->GetMethodID(globalFamilyCls, "<init>", "()V"); if (familyNameID == NULL || familyAgeID == NULL || familyMethodID == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "ID获取失败"); return 0; } return 1; } extern "C" JNIEXPORT jlong JNICALL Java_com_example_admin_dnktest_MainActivity_destory(JNIEnv *env, jobject instance) { if (globalCls != NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "释放globalCls内存"); env->DeleteGlobalRef(globalCls); } if (globalFamilyCls != NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "释放globalFamilyCls内存"); env->DeleteGlobalRef(globalFamilyCls); } return 0; } extern "C" JNIEXPORT void JNICALL Java_com_example_admin_dnktest_MainActivity_setData(JNIEnv *env, jobject instance, jobject bean) { if (globalCls == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "globalCls为NULL"); return; } jstring nameStr = (jstring) env->GetObjectField(bean, nameID); if (nameStr == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "nameStr == NULL"); return; } const char *nameStr_ = env->GetStringUTFChars(nameStr, NULL); if (nameStr_ == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "nameStr_ == NULL"); return; } env->ReleaseStringUTFChars(nameStr, nameStr_); jstring jstr = env->NewStringUTF("CCCCCC"); env->SetObjectField(bean, nameID, jstr); env->SetIntField(bean, ageID, 25); //给TestBean里面的对象赋值 jobject jobjFamily = env->NewObject(globalFamilyCls, familyMethodID); jstring familyNameStr = (jstring) env->GetObjectField(jobjFamily, familyNameID); if (familyNameStr == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "familyNameStr == NULL"); return; } const char *familyNameStr_ = env->GetStringUTFChars(familyNameStr, NULL); if (familyNameStr_ == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "familyNameStr_==NULL"); return; } env->ReleaseStringUTFChars(familyNameStr, familyNameStr_); jstring newFamilyName = env->NewStringUTF("BBBBB"); if (newFamilyName == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "newFamilyName == NULL"); return; } env->SetObjectField(jobjFamily, familyNameID, newFamilyName); env->SetIntField(jobjFamily, familyAgeID, 350); env->SetObjectField(bean, familyID, jobjFamily); } extern "C" JNIEXPORT jintArray JNICALL Java_com_example_admin_dnktest_MainActivity_addTen(JNIEnv *env, jobject instance, jintArray arr_) { //创建一个整形数组 // jint len = env->GetArrayLength(arr_); // // jintArray intArr = env->NewIntArray(len); // jint *arr = env->GetIntArrayElements(arr_, NULL); // // jint buf[len]; // // jint i; // for (i = 0; i < len; i++) { // buf[i] = arr[i] + 10; // __android_log_print(ANDROID_LOG_INFO, "DJC", "buf =%d", buf[i]); // } // // env->ReleaseIntArrayElements(arr_, arr, 0); // env->SetIntArrayRegion(intArr, 0, len, buf);//给jni创建的新数组赋值,arr_的值不变,但是要返回 // return intArr; // env->SetIntArrayRegion(arr_, 0, len, buf);直接修改arr_的值 // return NULL; jint len = env->GetArrayLength(arr_); jint *intArr = env->GetIntArrayElements(arr_, JNI_FALSE); jint i; for (int i = 0; i < len; ++i) { // *(intArr + i) += 10; intArr[i] += 10; } env->ReleaseIntArrayElements(arr_, intArr, 0); return arr_; } extern "C" JNIEXPORT jint JNICALL Java_com_example_admin_dnktest_MainActivity_getInt(JNIEnv *env, jobject instance, jstring value_) { const char *value = env->GetStringUTFChars(value_, 0); char *charValue = "123456"; jint code = strcasecmp(value, charValue); env->ReleaseStringUTFChars(value_, value); if (code == 0) { return 200; } else { return 404; } } extern "C" JNIEXPORT void JNICALL Java_com_example_admin_dnktest_JniMethod_callAddSum(JNIEnv *env, jobject instance) { //通过反射查找类 jclass cls = env->FindClass("com/example/admin/dnktest/JniMethod"); //查找调用方法的ID jmethodID methodID = env->GetMethodID(cls, "addSum", "(II)I"); //实例化类的对象 jobject jobj = env->AllocObject(cls); if (jobj == NULL) { __android_log_print(ANDROID_LOG_INFO, "DJC", "Out Of Memery"); return; } //调用java方法 jint value = env->CallIntMethod(jobj, methodID, 3, 4); LOGI("value = %d", value); }extern "C" JNIEXPORT void JNICALL Java_com_example_admin_dnktest_JniMethod_getShowToast(JNIEnv *env, jobject instance, jobject activity) { //通过对象查找类 jclass cls = env->GetObjectClass(activity); //查找方法ID jmethodID jmethodID = env->GetMethodID(cls, "showToast", "()V"); if (jmethodID == NULL) { LOGI("jmethodID = %s", jmethodID); return; } LOGI("jni层调用getShowToast"); //调用方法 env->CallVoidMethod(activity, jmethodID); } extern "C" JNIEXPORT jstring JNICALL Java_com_example_admin_dnktest_MainActivity_appendStr(JNIEnv *env, jobject instance) { //通过对象获取类 jclass _cls = env->GetObjectClass(instance); //获取属性ID jfieldID _id = env->GetFieldID(_cls, "str", "Ljava/lang/String;"); //获取属性值 jstring _str = (jstring) env->GetObjectField(instance, _id); //转换成char const char *dststr = env->GetStringUTFChars(_str, NULL); //创建一个char char oriStr[20] = "Success";//或者 char *oriStr = "success"; //拼接字符串 strcat((char *) dststr, oriStr); LOGI("dststr = %s", dststr); return env->NewStringUTF(dststr); } //定义一个比较的方法 int compare(const void *a, const void *b) { //*(int*)__lhs强制转成一个整形的指针,并且获取这个整形指针的数值 return (*(int *) a - *(int *) b); }; extern "C" JNIEXPORT void JNICALL Java_com_example_admin_dnktest_MainActivity_sortArr(JNIEnv *env, jobject instance, jintArray arr_) { jint *arr = env->GetIntArrayElements(arr_, NULL); //获取数组的长度 jint len = env->GetArrayLength(arr_); //调用函数进行排序 /** * __base arr * sizeof(int) 获取整形的内存地址 */ qsort(arr, len, sizeof(int), compare); env->ReleaseIntArrayElements(arr_, arr, 0); } extern "C" JNIEXPORT void JNICALL Java_com_example_admin_dnktest_MainActivity_getException(JNIEnv *env, jobject instance) { jstring _str; jclass _class = env->GetObjectClass(instance); //获取一个java中没有声明的属性的ID jfieldID _jfieldID = env->GetFieldID(_class, "str1", "Ljava/lang/String;"); //获取属性值 //判断是否发生异常 jthrowable _jthrowable = env->ExceptionOccurred(); if (_jthrowable != NULL) {//捕捉到异常 //清除异常 env->ExceptionClear(); _jfieldID = env->GetFieldID(_class, "str", "Ljava/lang/String;"); } _str = (jstring) env->GetObjectField(instance, _jfieldID); char *str = (char *) env->GetStringUTFChars(_str, NULL); if (strcmp(str, "WWW") != 0) { //假设异常为非法参数异常 jclass _cls = env->FindClass("java/lang/IllegalArgumentException"); env->ThrowNew(_cls, "非法参数异常"); } env->ReleaseStringChars(_str, (const jchar *) str); //javac层不能直接捕获c语言的异常,c语言可以捕获java的异常 //在java层中输出c语言捕获的异常,先判断是否发生异常,判断jthrowable的值 //如果发生异常,先清除异常,再获取正确的正确的值 } extern "C" JNIEXPORT void JNICALL Java_com_example_admin_dnktest_MainActivity_cache(JNIEnv *env, jobject instance) { //如果在java层的for循环中调用 //非空判断并没有什么用,Log日志还会继续打印,对象还会一直创建 //如果想实现缓存策略,只需要将变量声明为静态,即 static jfieldID _jfieldID; jclass _cls = env->GetObjectClass(instance); jfieldID _jfieldID; if (_jfieldID == NULL) { _jfieldID = env->GetFieldID(_cls, "str", "Ljava/lang/String;"); LOGI("---------------------"); } //实现缓存策略 //1.将属性声明为静态 //2.在类库加载的时候,声明一个初始化,在初始化中进行属性的声明,可以实现缓存策略 }
[ "djc512@126.com" ]
djc512@126.com
972e97781b19d36df0093d2b48cbf7be1397897f
fded81a37e53d5fc31cacb9a0be86377825757b3
/buhg_g/ukrshkz_m.cpp
04325da161ec782c96160f10f027015c83463284
[]
no_license
iceblinux/iceBw_GTK
7bf28cba9d994e95bab0f5040fea1a54a477b953
a4f76e1fee29baa7dce79e8a4a309ae98ba504c2
refs/heads/main
2023-04-02T21:45:49.500587
2021-04-12T03:51:53
2021-04-12T03:51:53
356,744,886
0
0
null
null
null
null
UTF-8
C++
false
false
14,598
cpp
/*$Id: ukrshkz_m.c,v 1.12 2013/09/26 09:46:56 sasa Exp $*/ /*25.03.2020 28.02.2008 Белых А.И. ukrshkz_m.c Меню для ввода реквизитов */ #include "buhg_g.h" #include "ukrshkz.h" enum { FK2, FK4, FK10, KOL_F_KL }; enum { E_DATAN, E_DATAK, E_KOD_ZAT, E_SHET, E_KOD_GR_ZAT, E_KOD_KONTR, KOLENTER }; class ukrshkz_m_data { public: class ukrshkz_data *rk; GtkWidget *entry[KOLENTER]; GtkWidget *knopka[KOL_F_KL]; GtkWidget *knopka_enter[KOLENTER]; GtkWidget *window; short kl_shift; short voz; //0-начать расчёт 1 нет ukrshkz_m_data() //Конструктор { kl_shift=0; voz=1; } void read_rek() { for(int i=0; i < KOLENTER; i++) g_signal_emit_by_name(entry[i],"activate"); } void clear_rek() { for(int i=0; i < KOLENTER; i++) gtk_entry_set_text(GTK_ENTRY(entry[i]),""); rk->clear(); } }; gboolean ukrshkz_v_key_press(GtkWidget *widget,GdkEventKey *event,class ukrshkz_m_data *data); void ukrshkz_v_vvod(GtkWidget *widget,class ukrshkz_m_data *data); void ukrshkz_v_knopka(GtkWidget *widget,class ukrshkz_m_data *data); void ukrshkz_v_e_knopka(GtkWidget *widget,class ukrshkz_m_data *data); int ukrshkz_m_provr(class ukrshkz_m_data *data); extern SQL_baza bd; int ukrshkz_m(class ukrshkz_data *rek_ras) { char strsql[512]; class ukrshkz_m_data data; data.rk=rek_ras; data.window=gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_position( GTK_WINDOW(data.window),ICEB_POS_CENTER); gtk_window_set_modal(GTK_WINDOW(data.window),TRUE); sprintf(strsql,"%s %s",iceb_get_namesystem(),gettext("Расчёт ведомости по счетам-кодам затрат")); gtk_window_set_title (GTK_WINDOW (data.window),strsql); gtk_container_set_border_width (GTK_CONTAINER (data.window), 5); g_signal_connect(data.window,"delete_event",G_CALLBACK(gtk_widget_destroy),NULL); g_signal_connect(data.window,"destroy",G_CALLBACK(gtk_main_quit),NULL); g_signal_connect_after(data.window,"key_press_event",G_CALLBACK(ukrshkz_v_key_press),&data); GtkWidget *label=NULL; label=gtk_label_new(gettext("Расчёт ведомости по счетам-кодам затрат")); GtkWidget *vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 1); gtk_box_set_homogeneous (GTK_BOX(vbox),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет GtkWidget *hbox[KOLENTER]; for(int i=0; i < KOLENTER; i++) { hbox[i] = gtk_box_new (GTK_ORIENTATION_HORIZONTAL,1); gtk_box_set_homogeneous (GTK_BOX( hbox[i]),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет } GtkWidget *hboxknop = gtk_box_new (GTK_ORIENTATION_HORIZONTAL,1); gtk_box_set_homogeneous (GTK_BOX(hboxknop),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет gtk_container_add (GTK_CONTAINER (data.window), vbox); gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE,1); for(int i=0; i < KOLENTER; i++) gtk_box_pack_start (GTK_BOX (vbox), hbox[i], TRUE, TRUE,1); gtk_box_pack_start (GTK_BOX (vbox), hboxknop, FALSE, FALSE,1); sprintf(strsql,"%s (%s)",gettext("Дата начала"),gettext("д.м.г")); data.knopka_enter[E_DATAN]=gtk_button_new_with_label(strsql); gtk_box_pack_start (GTK_BOX (hbox[E_DATAN]), data.knopka_enter[E_DATAN], FALSE, FALSE,1); g_signal_connect(data.knopka_enter[E_DATAN],"clicked",G_CALLBACK(ukrshkz_v_e_knopka),&data); gtk_widget_set_name(data.knopka_enter[E_DATAN],iceb_u_inttochar(E_DATAN)); gtk_widget_set_tooltip_text(data.knopka_enter[E_DATAN],gettext("Выбор даты начала отчёта")); data.entry[E_DATAN] = gtk_entry_new (); gtk_entry_set_max_length(GTK_ENTRY(data.entry[E_DATAN]),10); gtk_box_pack_start (GTK_BOX (hbox[E_DATAN]), data.entry[E_DATAN], TRUE, TRUE,1); g_signal_connect(data.entry[E_DATAN], "activate",G_CALLBACK(ukrshkz_v_vvod),&data); gtk_entry_set_text(GTK_ENTRY(data.entry[E_DATAN]),data.rk->datan.ravno()); gtk_widget_set_name(data.entry[E_DATAN],iceb_u_inttochar(E_DATAN)); sprintf(strsql,"%s (%s)",gettext("Дата конца"),gettext("д.м.г")); data.knopka_enter[E_DATAK]=gtk_button_new_with_label(strsql); gtk_box_pack_start (GTK_BOX (hbox[E_DATAK]), data.knopka_enter[E_DATAK], FALSE, FALSE,1); g_signal_connect(data.knopka_enter[E_DATAK],"clicked",G_CALLBACK(ukrshkz_v_e_knopka),&data); gtk_widget_set_name(data.knopka_enter[E_DATAK],iceb_u_inttochar(E_DATAK)); gtk_widget_set_tooltip_text(data.knopka_enter[E_DATAK],gettext("Выбор даты конца отчёта")); data.entry[E_DATAK] = gtk_entry_new (); gtk_entry_set_max_length(GTK_ENTRY(data.entry[E_DATAK]),10); gtk_box_pack_start (GTK_BOX (hbox[E_DATAK]), data.entry[E_DATAK], TRUE, TRUE,1); g_signal_connect(data.entry[E_DATAK], "activate",G_CALLBACK(ukrshkz_v_vvod),&data); gtk_entry_set_text(GTK_ENTRY(data.entry[E_DATAK]),data.rk->datak.ravno()); gtk_widget_set_name(data.entry[E_DATAK],iceb_u_inttochar(E_DATAK)); sprintf(strsql,"%s (,,)",gettext("Код контрагента")); data.knopka_enter[E_SHET]=gtk_button_new_with_label(strsql); gtk_box_pack_start (GTK_BOX (hbox[E_SHET]), data.knopka_enter[E_SHET], FALSE, FALSE,1); g_signal_connect(data.knopka_enter[E_SHET],"clicked",G_CALLBACK(ukrshkz_v_e_knopka),&data); gtk_widget_set_name(data.knopka_enter[E_SHET],iceb_u_inttochar(E_SHET)); gtk_widget_set_tooltip_text(data.knopka_enter[E_SHET],gettext("Выбор счёта в плане счетов")); data.entry[E_SHET] = gtk_entry_new(); gtk_box_pack_start (GTK_BOX (hbox[E_SHET]), data.entry[E_SHET], TRUE, TRUE,1); g_signal_connect(data.entry[E_SHET], "activate",G_CALLBACK(ukrshkz_v_vvod),&data); gtk_entry_set_text(GTK_ENTRY(data.entry[E_SHET]),data.rk->shet.ravno()); gtk_widget_set_name(data.entry[E_SHET],iceb_u_inttochar(E_SHET)); sprintf(strsql,"%s (,,)",gettext("Код командировочных расходов")); data.knopka_enter[E_KOD_ZAT]=gtk_button_new_with_label(strsql); gtk_box_pack_start (GTK_BOX (hbox[E_KOD_ZAT]), data.knopka_enter[E_KOD_ZAT], FALSE, FALSE,1); g_signal_connect(data.knopka_enter[E_KOD_ZAT],"clicked",G_CALLBACK(ukrshkz_v_e_knopka),&data); gtk_widget_set_name(data.knopka_enter[E_KOD_ZAT],iceb_u_inttochar(E_KOD_ZAT)); gtk_widget_set_tooltip_text(data.knopka_enter[E_KOD_ZAT],gettext("Выбор кода командировочных расходов")); data.entry[E_KOD_ZAT] = gtk_entry_new(); gtk_box_pack_start (GTK_BOX (hbox[E_KOD_ZAT]), data.entry[E_KOD_ZAT], TRUE, TRUE,1); g_signal_connect(data.entry[E_KOD_ZAT], "activate",G_CALLBACK(ukrshkz_v_vvod),&data); gtk_entry_set_text(GTK_ENTRY(data.entry[E_KOD_ZAT]),data.rk->kod_zat.ravno()); gtk_widget_set_name(data.entry[E_KOD_ZAT],iceb_u_inttochar(E_KOD_ZAT)); sprintf(strsql,"%s (,,)",gettext("Код группы затрат")); data.knopka_enter[E_KOD_GR_ZAT]=gtk_button_new_with_label(strsql); gtk_box_pack_start (GTK_BOX (hbox[E_KOD_GR_ZAT]), data.knopka_enter[E_KOD_GR_ZAT], FALSE, FALSE,1); g_signal_connect(data.knopka_enter[E_KOD_GR_ZAT],"clicked",G_CALLBACK(ukrshkz_v_e_knopka),&data); gtk_widget_set_name(data.knopka_enter[E_KOD_GR_ZAT],iceb_u_inttochar(E_KOD_GR_ZAT)); gtk_widget_set_tooltip_text(data.knopka_enter[E_KOD_GR_ZAT],gettext("Выбор группы")); data.entry[E_KOD_GR_ZAT] = gtk_entry_new(); gtk_box_pack_start (GTK_BOX (hbox[E_KOD_GR_ZAT]), data.entry[E_KOD_GR_ZAT], TRUE, TRUE,1); g_signal_connect(data.entry[E_KOD_GR_ZAT], "activate",G_CALLBACK(ukrshkz_v_vvod),&data); gtk_entry_set_text(GTK_ENTRY(data.entry[E_KOD_GR_ZAT]),data.rk->kod_gr_zat.ravno()); gtk_widget_set_name(data.entry[E_KOD_GR_ZAT],iceb_u_inttochar(E_KOD_GR_ZAT)); sprintf(strsql,"%s (,,)",gettext("Код контрагента")); data.knopka_enter[E_KOD_KONTR]=gtk_button_new_with_label(strsql); gtk_box_pack_start (GTK_BOX (hbox[E_KOD_KONTR]), data.knopka_enter[E_KOD_KONTR], FALSE, FALSE,1); g_signal_connect(data.knopka_enter[E_KOD_KONTR],"clicked",G_CALLBACK(ukrshkz_v_e_knopka),&data); gtk_widget_set_name(data.knopka_enter[E_KOD_KONTR],iceb_u_inttochar(E_KOD_KONTR)); gtk_widget_set_tooltip_text(data.knopka_enter[E_KOD_KONTR],gettext("Выбор контрагента")); data.entry[E_KOD_KONTR] = gtk_entry_new(); gtk_box_pack_start (GTK_BOX (hbox[E_KOD_KONTR]), data.entry[E_KOD_KONTR], TRUE, TRUE,1); g_signal_connect(data.entry[E_KOD_KONTR], "activate",G_CALLBACK(ukrshkz_v_vvod),&data); gtk_entry_set_text(GTK_ENTRY(data.entry[E_KOD_KONTR]),data.rk->kod_kontr.ravno()); gtk_widget_set_name(data.entry[E_KOD_KONTR],iceb_u_inttochar(E_KOD_KONTR)); sprintf(strsql,"F2 %s",gettext("Расчёт")); data.knopka[FK2]=gtk_button_new_with_label(strsql); gtk_widget_set_tooltip_text(data.knopka[FK2],gettext("Начать расчёт")); g_signal_connect(data.knopka[FK2],"clicked",G_CALLBACK(ukrshkz_v_knopka),&data); gtk_widget_set_name(data.knopka[FK2],iceb_u_inttochar(FK2)); gtk_box_pack_start(GTK_BOX(hboxknop), data.knopka[FK2], TRUE, TRUE,1); sprintf(strsql,"F4 %s",gettext("Очистить")); data.knopka[FK4]=gtk_button_new_with_label(strsql); gtk_widget_set_tooltip_text(data.knopka[FK4],gettext("Очистить меню от введенной информации")); g_signal_connect(data.knopka[FK4],"clicked",G_CALLBACK(ukrshkz_v_knopka),&data); gtk_widget_set_name(data.knopka[FK4],iceb_u_inttochar(FK4)); gtk_box_pack_start(GTK_BOX(hboxknop), data.knopka[FK4], TRUE, TRUE,1); sprintf(strsql,"F10 %s",gettext("Выход")); data.knopka[FK10]=gtk_button_new_with_label(strsql); gtk_widget_set_tooltip_text(data.knopka[FK10],gettext("Завершение работы в этом окне")); g_signal_connect(data.knopka[FK10],"clicked",G_CALLBACK(ukrshkz_v_knopka),&data); gtk_widget_set_name(data.knopka[FK10],iceb_u_inttochar(FK10)); gtk_box_pack_start(GTK_BOX(hboxknop), data.knopka[FK10], TRUE, TRUE,1); gtk_widget_grab_focus(data.entry[0]); gtk_widget_show_all (data.window); gtk_main(); return(data.voz); } /*****************************/ /*Обработчик нажатия enter кнопок */ /*****************************/ void ukrshkz_v_e_knopka(GtkWidget *widget,class ukrshkz_m_data *data) { iceb_u_str kod(""); iceb_u_str naim(""); int knop=atoi(gtk_widget_get_name(widget)); /*g_print("ukrshkz_v_e_knopka knop=%d\n",knop);*/ switch (knop) { case E_DATAN: if(iceb_calendar(&data->rk->datan,data->window) == 0) gtk_entry_set_text(GTK_ENTRY(data->entry[E_DATAN]),data->rk->datan.ravno()); return; case E_DATAK: if(iceb_calendar(&data->rk->datak,data->window) == 0) gtk_entry_set_text(GTK_ENTRY(data->entry[E_DATAK]),data->rk->datak.ravno()); return; case E_KOD_ZAT: if(l_ukrzat(1,&kod,&naim,data->window) == 0) data->rk->kod_zat.z_plus(kod.ravno()); gtk_entry_set_text(GTK_ENTRY(data->entry[E_KOD_ZAT]),data->rk->kod_zat.ravno()); return; case E_KOD_GR_ZAT: if(l_ukrgrup(1,&kod,&naim,data->window) == 0) data->rk->kod_gr_zat.z_plus(kod.ravno()); gtk_entry_set_text(GTK_ENTRY(data->entry[E_KOD_GR_ZAT]),data->rk->kod_gr_zat.ravno()); return; case E_SHET: if(iceb_l_plansh(1,&kod,&naim,data->window) == 0) data->rk->shet.z_plus(kod.ravno()); gtk_entry_set_text(GTK_ENTRY(data->entry[E_SHET]),data->rk->shet.ravno()); return; case E_KOD_KONTR: if(iceb_l_kontr(1,&kod,&naim,data->window) == 0) data->rk->kod_kontr.z_plus(kod.ravno()); gtk_entry_set_text(GTK_ENTRY(data->entry[E_KOD_KONTR]),data->rk->kod_kontr.ravno()); return; } } /*********************************/ /*Обработка нажатия клавиш */ /*********************************/ gboolean ukrshkz_v_key_press(GtkWidget *widget,GdkEventKey *event,class ukrshkz_m_data *data) { switch(event->keyval) { case GDK_KEY_F2: g_signal_emit_by_name(data->knopka[FK2],"clicked"); return(TRUE); case GDK_KEY_F4: g_signal_emit_by_name(data->knopka[FK4],"clicked"); return(TRUE); case GDK_KEY_Escape: case GDK_KEY_F10: g_signal_emit_by_name(data->knopka[FK10],"clicked"); return(FALSE); case ICEB_REG_L: case ICEB_REG_R: // printf("Нажата клавиша Shift\n"); data->kl_shift=1; return(TRUE); } return(TRUE); } /*****************************/ /*Обработчик нажатия кнопок */ /*****************************/ void ukrshkz_v_knopka(GtkWidget *widget,class ukrshkz_m_data *data) { int knop=atoi(gtk_widget_get_name(widget)); switch (knop) { case FK2: data->read_rek(); //Читаем реквизиты меню if(ukrshkz_m_provr(data) != 0) return; data->voz=0; gtk_widget_destroy(data->window); return; case FK4: data->clear_rek(); return; case FK10: data->read_rek(); //Читаем реквизиты меню data->voz=1; gtk_widget_destroy(data->window); return; } } /********************************/ /*Перевод чтение текста и перевод фокуса на следующюю строку ввода*/ /******************************************/ void ukrshkz_v_vvod(GtkWidget *widget,class ukrshkz_m_data *data) { int enter=atoi(gtk_widget_get_name(widget)); //g_print("ukrshkz_v_vvod enter=%d\n",enter); switch (enter) { case E_DATAN: data->rk->datan.new_plus(gtk_entry_get_text(GTK_ENTRY(widget))); break; case E_DATAK: data->rk->datak.new_plus(gtk_entry_get_text(GTK_ENTRY(widget))); break; case E_SHET: data->rk->shet.new_plus(gtk_entry_get_text(GTK_ENTRY(widget))); break; case E_KOD_ZAT: data->rk->kod_zat.new_plus(gtk_entry_get_text(GTK_ENTRY(widget))); break; case E_KOD_GR_ZAT: data->rk->kod_gr_zat.new_plus(gtk_entry_get_text(GTK_ENTRY(widget))); break; case E_KOD_KONTR: data->rk->kod_kontr.new_plus(gtk_entry_get_text(GTK_ENTRY(widget))); break; } enter+=1; if(enter >= KOLENTER) enter=0; gtk_widget_grab_focus(data->entry[enter]); } /**************************************/ /*Проверка реквизитов*/ /*******************************/ int ukrshkz_m_provr(class ukrshkz_m_data *data) { if(iceb_rsdatp(data->rk->datan.ravno(),data->rk->datak.ravno(),data->window) != 0) return(1); return(0); }
[ "root@calculate.local" ]
root@calculate.local
e6559015e82fdff5e0d433236a395238ae8370e7
dbad4b4924b22c3059846b87e8358610514a19a9
/gargolee.cpp
c8e0e2ac4381ababb8cabe52b3afc95351cb40f6
[]
no_license
rebesian/Lost_Vikings_2_copy
c7a833b4708d47db35b7b5a7f7adf593e13ec829
9163993c2e33fd31018045176bedf455a5f47b95
refs/heads/main
2023-08-12T20:40:31.996399
2021-09-24T18:24:54
2021-09-24T18:24:54
410,060,537
0
0
null
null
null
null
UHC
C++
false
false
7,878
cpp
#include "stdafx.h" #include "gargolee.h" #include "player.h" #include "idlestate.h" #include "gargoleeaction.h" statepatten * gargolee::handleInput(player * _player) { if (end) { _player->_gargolee = false; _player->bealogrc = RectMakeCenter(0, 0, 0, 0); _player->gargoleebody1rc = RectMakeCenter(0, 0, 0, 0); _player->gargoleebody2rc = RectMakeCenter(0, 0, 0, 0); _player->gargoleebody3rc = RectMakeCenter(0, 0, 0, 0); return new idlestate; } if (_player->bealogaction !=255) { return new gargoleeaction; } return nullptr; } void gargolee::update(player * _player) { count++; //앞으로 갈고리 if (_player->getimg() == IMAGEMANAGER->findImage("BaleogPunch")) { if (count % 10 == 0) { if (_player->isRight) { _player->setindex(_player->getindex() + 1); if (_player->getindex() > 3) _player->setindex(3); _player->getimg()->setFrameX(_player->getindex()); _player->getimg()->setFrameY(0); count = 0; } else { _player->setindex(_player->getindex() + 1); if (_player->getindex() > 3) _player->setindex(3); _player->getimg()->setFrameX(_player->getindex()); _player->getimg()->setFrameY(1); count = 0; } } if (_player->isRight) { if (_player->getindex() > 2) x -= 2; else x += 2; _player->gargoleebody3rc = RectMakeCenter(_player->getX() + x, _player->getY(), 32, 32); _player->gargoleebody2rc = RectMakeCenter(((_player->gargoleebody3rc.right + _player->gargoleebody3rc.left) / 2) + x, _player->getY(), 32, 32); _player->gargoleebody1rc = RectMakeCenter(((_player->gargoleebody2rc.right + _player->gargoleebody2rc.left) / 2) + x, _player->getY(), 32, 32); _player->bealogrc = RectMakeCenter(((_player->gargoleebody1rc.right + _player->gargoleebody1rc.left) / 2) + x, _player->getY(), 38, 38); if (x < 0) end=true; } else { if (_player->getindex() > 2) x += 2; else x -= 2; _player->gargoleebody3rc = RectMakeCenter(_player->getX() + x, _player->getY(), 32, 32); _player->gargoleebody2rc = RectMakeCenter(((_player->gargoleebody3rc.right + _player->gargoleebody3rc.left) / 2) + x, _player->getY(), 32, 32); _player->gargoleebody1rc = RectMakeCenter(((_player->gargoleebody2rc.right + _player->gargoleebody2rc.left) / 2) + x, _player->getY(), 32, 32); _player->bealogrc = RectMakeCenter(((_player->gargoleebody1rc.right + _player->gargoleebody1rc.left) / 2) + x, _player->getY(), 38, 38); if (x > 0) end = true; } } //위로갈고리 if (_player->getimg() == IMAGEMANAGER->findImage("BaleogPunchTop")) { if (count % 10 == 0) { if (_player->isRight) { _player->getimg()->setFrameX(_player->getindex()); _player->getimg()->setFrameY(0); _player->setindex(_player->getindex() + 1); if (_player->getindex() > 2) _player->setindex(1); } else { _player->getimg()->setFrameX(_player->getindex()); _player->getimg()->setFrameY(1); _player->setindex(_player->getindex() + 1); if (_player->getindex() > 2) _player->setindex(1); } } if (count < 30) y -= 2; else y += 2; _player->gargoleebody3rc = RectMakeCenter(_player->getX(), _player->getY() + y, 32, 32); _player->gargoleebody2rc = RectMakeCenter(_player->getX(), ((_player->gargoleebody3rc.bottom + _player->gargoleebody3rc.top) / 2) + y, 32, 32); _player->gargoleebody1rc = RectMakeCenter(_player->getX(), ((_player->gargoleebody2rc.bottom + _player->gargoleebody2rc.top) / 2) + y, 32, 32); _player->bealogrc = RectMakeCenter(_player->getX(), ((_player->gargoleebody1rc.bottom + _player->gargoleebody1rc.top) / 2)+y, 38, 38); if (y > 0) end = true; } //대각선갈고리 if (_player->getimg() == IMAGEMANAGER->findImage("BaleogPunchDiagonal")) { if (count % 10 == 0) { if (_player->isRight) { _player->setindex(_player->getindex() + 1); if (_player->getindex() > 3) _player->setindex(3); _player->getimg()->setFrameX(_player->getindex()); _player->getimg()->setFrameY(0); count = 0; } else { _player->setindex(_player->getindex() + 1); if (_player->getindex() > 3) _player->setindex(3); _player->getimg()->setFrameX(_player->getindex()); _player->getimg()->setFrameY(1); count = 0; } } if (_player->isRight) { if (_player->getindex() > 2) { x -= 1.5f; y += 1.5f; } else { x += 1.5f; y -= 1.5f; } _player->gargoleebody3rc = RectMakeCenter(_player->getX() + x, _player->getY() + y, 32, 32); _player->gargoleebody2rc = RectMakeCenter(((_player->gargoleebody3rc.right + _player->gargoleebody3rc.left) / 2) + x, ((_player->gargoleebody3rc.bottom + _player->gargoleebody3rc.top) / 2) + y, 32, 32); _player->gargoleebody1rc = RectMakeCenter(((_player->gargoleebody2rc.right + _player->gargoleebody2rc.left) / 2) + x, ((_player->gargoleebody2rc.bottom + _player->gargoleebody2rc.top) / 2) + y, 32, 32); _player->bealogrc = RectMakeCenter(((_player->gargoleebody1rc.right + _player->gargoleebody1rc.left) / 2) + x, ((_player->gargoleebody1rc.bottom + _player->gargoleebody1rc.top) / 2) +y, 38, 38); if (x < 0) end = true; } else { if (_player->getindex() > 2) { x += 1.5f; y += 1.5f; } else { x -= 1.5f; y -= 1.5f; } _player->gargoleebody3rc = RectMakeCenter(_player->getX() + x, _player->getY() + y, 32, 32); _player->gargoleebody2rc = RectMakeCenter(((_player->gargoleebody3rc.right + _player->gargoleebody3rc.left) / 2) + x, ((_player->gargoleebody3rc.bottom + _player->gargoleebody3rc.top) / 2) + y, 32, 32); _player->gargoleebody1rc = RectMakeCenter(((_player->gargoleebody2rc.right + _player->gargoleebody2rc.left) / 2) + x, ((_player->gargoleebody2rc.bottom + _player->gargoleebody2rc.top) / 2) + y, 32, 32); _player->bealogrc = RectMakeCenter(((_player->gargoleebody1rc.right + _player->gargoleebody1rc.left) / 2) + x, ((_player->gargoleebody1rc.bottom + _player->gargoleebody1rc.top) / 2) + y, 38, 38); if (x > 0) end = true; } } } void gargolee::enter(player * _player, int character) { count = 0; x = y = 1; _character = character; _present = _player->getpresent(); _player->_gargolee = true; end = false; if (_character == 1) { if (KEYMANAGER->isStayKeyDown(VK_LEFT) || (KEYMANAGER->isStayKeyDown(VK_RIGHT))) { _player->setimg(IMAGEMANAGER->findImage("BaleogPunch")); _player->setindex(0); if (_player->isRight) { _player->gargolee = IMAGEMANAGER->findImage("gargolee2"); _player->getimg()->setFrameX(0); _player->getimg()->setFrameY(0); } else { _player->gargolee = IMAGEMANAGER->findImage("gargolee3"); _player->getimg()->setFrameX(0); _player->getimg()->setFrameY(1); } } if (KEYMANAGER->isStayKeyDown(VK_UP)) { _player->setimg(IMAGEMANAGER->findImage("BaleogPunchTop")); _player->gargolee = IMAGEMANAGER->findImage("gargolee1"); _player->getimg()->setCenter(_player->getX(), _player->getY()); _player->setindex(0); if (_player->isRight) { _player->getimg()->setFrameX(0); _player->getimg()->setFrameY(0); } else { _player->getimg()->setFrameX(0); _player->getimg()->setFrameY(1); } } if (KEYMANAGER->isStayKeyDown(VK_UP)&& (KEYMANAGER->isStayKeyDown(VK_LEFT) || (KEYMANAGER->isStayKeyDown(VK_RIGHT)))) { _player->setimg(IMAGEMANAGER->findImage("BaleogPunchDiagonal")); _player->getimg()->setCenter(_player->getX(), _player->getY()); _player->setindex(0); if (_player->isRight) { _player->gargolee = IMAGEMANAGER->findImage("gargolee4"); _player->getimg()->setFrameX(0); _player->getimg()->setFrameY(0); } else { _player->gargolee = IMAGEMANAGER->findImage("gargolee5"); _player->getimg()->setFrameX(0); _player->getimg()->setFrameY(1); } } } }
[ "noreply@github.com" ]
rebesian.noreply@github.com
d78d75f12a72c052e4dca35fcb59665e493c6527
25abd807ca135a5c268255515f6d493c229903be
/cppwinrt/Windows.Media.AppBroadcasting.h
4c5ef6654a0a98978d13139a9097680c24adc436
[ "Apache-2.0" ]
permissive
RakeshShrestha/C-Calendar-Library
670924ae3204d8737d8f43c47e54fe113d202265
6525707089891b0710e34769f7aeaea0c79271a1
refs/heads/master
2022-05-16T15:26:37.102822
2022-04-28T08:45:58
2022-04-28T08:45:58
33,488,761
2
0
null
null
null
null
UTF-8
C++
false
false
16,350
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.200117.5 #ifndef WINRT_Windows_Media_AppBroadcasting_H #define WINRT_Windows_Media_AppBroadcasting_H #include "winrt/base.h" static_assert(winrt::check_version(CPPWINRT_VERSION, "2.0.200117.5"), "Mismatched C++/WinRT headers."); #include "winrt/Windows.Media.h" #include "winrt/impl/Windows.Foundation.2.h" #include "winrt/impl/Windows.System.2.h" #include "winrt/impl/Windows.Media.AppBroadcasting.2.h" namespace winrt::impl { template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingMonitor<D>::IsCurrentAppBroadcasting() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingMonitor)->get_IsCurrentAppBroadcasting(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(winrt::event_token) consume_Windows_Media_AppBroadcasting_IAppBroadcastingMonitor<D>::IsCurrentAppBroadcastingChanged(Windows::Foundation::TypedEventHandler<Windows::Media::AppBroadcasting::AppBroadcastingMonitor, Windows::Foundation::IInspectable> const& handler) const { winrt::event_token token{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingMonitor)->add_IsCurrentAppBroadcastingChanged(*(void**)(&handler), put_abi(token))); return token; } template <typename D> typename consume_Windows_Media_AppBroadcasting_IAppBroadcastingMonitor<D>::IsCurrentAppBroadcastingChanged_revoker consume_Windows_Media_AppBroadcasting_IAppBroadcastingMonitor<D>::IsCurrentAppBroadcastingChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Media::AppBroadcasting::AppBroadcastingMonitor, Windows::Foundation::IInspectable> const& handler) const { return impl::make_event_revoker<D, IsCurrentAppBroadcastingChanged_revoker>(this, IsCurrentAppBroadcastingChanged(handler)); } template <typename D> WINRT_IMPL_AUTO(void) consume_Windows_Media_AppBroadcasting_IAppBroadcastingMonitor<D>::IsCurrentAppBroadcastingChanged(winrt::event_token const& token) const noexcept { WINRT_VERIFY_(0, WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingMonitor)->remove_IsCurrentAppBroadcastingChanged(impl::bind_in(token))); } template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatus<D>::CanStartBroadcast() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatus)->get_CanStartBroadcast(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(Windows::Media::AppBroadcasting::AppBroadcastingStatusDetails) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatus<D>::Details() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatus)->get_Details(&value)); return Windows::Media::AppBroadcasting::AppBroadcastingStatusDetails{ value, take_ownership_from_abi }; } template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatusDetails<D>::IsAnyAppBroadcasting() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails)->get_IsAnyAppBroadcasting(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatusDetails<D>::IsCaptureResourceUnavailable() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails)->get_IsCaptureResourceUnavailable(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatusDetails<D>::IsGameStreamInProgress() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails)->get_IsGameStreamInProgress(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatusDetails<D>::IsGpuConstrained() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails)->get_IsGpuConstrained(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatusDetails<D>::IsAppInactive() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails)->get_IsAppInactive(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatusDetails<D>::IsBlockedForApp() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails)->get_IsBlockedForApp(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatusDetails<D>::IsDisabledByUser() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails)->get_IsDisabledByUser(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(bool) consume_Windows_Media_AppBroadcasting_IAppBroadcastingStatusDetails<D>::IsDisabledBySystem() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails)->get_IsDisabledBySystem(&value)); return value; } template <typename D> WINRT_IMPL_AUTO(Windows::Media::AppBroadcasting::AppBroadcastingStatus) consume_Windows_Media_AppBroadcasting_IAppBroadcastingUI<D>::GetStatus() const { void* result{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingUI)->GetStatus(&result)); return Windows::Media::AppBroadcasting::AppBroadcastingStatus{ result, take_ownership_from_abi }; } template <typename D> WINRT_IMPL_AUTO(void) consume_Windows_Media_AppBroadcasting_IAppBroadcastingUI<D>::ShowBroadcastUI() const { check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingUI)->ShowBroadcastUI()); } template <typename D> WINRT_IMPL_AUTO(Windows::Media::AppBroadcasting::AppBroadcastingUI) consume_Windows_Media_AppBroadcasting_IAppBroadcastingUIStatics<D>::GetDefault() const { void* result{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingUIStatics)->GetDefault(&result)); return Windows::Media::AppBroadcasting::AppBroadcastingUI{ result, take_ownership_from_abi }; } template <typename D> WINRT_IMPL_AUTO(Windows::Media::AppBroadcasting::AppBroadcastingUI) consume_Windows_Media_AppBroadcasting_IAppBroadcastingUIStatics<D>::GetForUser(Windows::System::User const& user) const { void* result{}; check_hresult(WINRT_IMPL_SHIM(Windows::Media::AppBroadcasting::IAppBroadcastingUIStatics)->GetForUser(*(void**)(&user), &result)); return Windows::Media::AppBroadcasting::AppBroadcastingUI{ result, take_ownership_from_abi }; } #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, Windows::Media::AppBroadcasting::IAppBroadcastingMonitor> : produce_base<D, Windows::Media::AppBroadcasting::IAppBroadcastingMonitor> { int32_t __stdcall get_IsCurrentAppBroadcasting(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().IsCurrentAppBroadcasting()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall add_IsCurrentAppBroadcastingChanged(void* handler, winrt::event_token* token) noexcept final try { zero_abi<winrt::event_token>(token); typename D::abi_guard guard(this->shim()); *token = detach_from<winrt::event_token>(this->shim().IsCurrentAppBroadcastingChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Media::AppBroadcasting::AppBroadcastingMonitor, Windows::Foundation::IInspectable> const*>(&handler))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall remove_IsCurrentAppBroadcastingChanged(winrt::event_token token) noexcept final { typename D::abi_guard guard(this->shim()); this->shim().IsCurrentAppBroadcastingChanged(*reinterpret_cast<winrt::event_token const*>(&token)); return 0; } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, Windows::Media::AppBroadcasting::IAppBroadcastingStatus> : produce_base<D, Windows::Media::AppBroadcasting::IAppBroadcastingStatus> { int32_t __stdcall get_CanStartBroadcast(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().CanStartBroadcast()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Details(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<Windows::Media::AppBroadcasting::AppBroadcastingStatusDetails>(this->shim().Details()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails> : produce_base<D, Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails> { int32_t __stdcall get_IsAnyAppBroadcasting(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().IsAnyAppBroadcasting()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_IsCaptureResourceUnavailable(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().IsCaptureResourceUnavailable()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_IsGameStreamInProgress(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().IsGameStreamInProgress()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_IsGpuConstrained(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().IsGpuConstrained()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_IsAppInactive(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().IsAppInactive()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_IsBlockedForApp(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().IsBlockedForApp()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_IsDisabledByUser(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().IsDisabledByUser()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_IsDisabledBySystem(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().IsDisabledBySystem()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, Windows::Media::AppBroadcasting::IAppBroadcastingUI> : produce_base<D, Windows::Media::AppBroadcasting::IAppBroadcastingUI> { int32_t __stdcall GetStatus(void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<Windows::Media::AppBroadcasting::AppBroadcastingStatus>(this->shim().GetStatus()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall ShowBroadcastUI() noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().ShowBroadcastUI(); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, Windows::Media::AppBroadcasting::IAppBroadcastingUIStatics> : produce_base<D, Windows::Media::AppBroadcasting::IAppBroadcastingUIStatics> { int32_t __stdcall GetDefault(void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<Windows::Media::AppBroadcasting::AppBroadcastingUI>(this->shim().GetDefault()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetForUser(void* user, void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<Windows::Media::AppBroadcasting::AppBroadcastingUI>(this->shim().GetForUser(*reinterpret_cast<Windows::System::User const*>(&user))); return 0; } catch (...) { return to_hresult(); } }; #endif } WINRT_EXPORT namespace winrt::Windows::Media::AppBroadcasting { inline AppBroadcastingMonitor::AppBroadcastingMonitor() : AppBroadcastingMonitor(impl::call_factory_cast<AppBroadcastingMonitor(*)(Windows::Foundation::IActivationFactory const&), AppBroadcastingMonitor>([](Windows::Foundation::IActivationFactory const& f) { return f.template ActivateInstance<AppBroadcastingMonitor>(); })) { } inline auto AppBroadcastingUI::GetDefault() { return impl::call_factory_cast<Windows::Media::AppBroadcasting::AppBroadcastingUI(*)(IAppBroadcastingUIStatics const&), AppBroadcastingUI, IAppBroadcastingUIStatics>([](IAppBroadcastingUIStatics const& f) { return f.GetDefault(); }); } inline auto AppBroadcastingUI::GetForUser(Windows::System::User const& user) { return impl::call_factory<AppBroadcastingUI, IAppBroadcastingUIStatics>([&](IAppBroadcastingUIStatics const& f) { return f.GetForUser(user); }); } } namespace std { #ifndef WINRT_LEAN_AND_MEAN template<> struct hash<winrt::Windows::Media::AppBroadcasting::IAppBroadcastingMonitor> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Media::AppBroadcasting::IAppBroadcastingStatus> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Media::AppBroadcasting::IAppBroadcastingStatusDetails> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Media::AppBroadcasting::IAppBroadcastingUI> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Media::AppBroadcasting::IAppBroadcastingUIStatics> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Media::AppBroadcasting::AppBroadcastingMonitor> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Media::AppBroadcasting::AppBroadcastingStatus> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Media::AppBroadcasting::AppBroadcastingStatusDetails> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Media::AppBroadcasting::AppBroadcastingUI> : winrt::impl::hash_base {}; #endif } #endif
[ "rakesh.shrestha@gmail.com" ]
rakesh.shrestha@gmail.com
ceafc2e0cf8cd5f9f6acbb73c403ae83e4b191ad
8e14c5dcdc9bbceed4713c19b3f08907a5d8a75d
/My First Program.cpp
49c7eda852a92d9dc5d218385bdf5a226da82121
[]
no_license
dbmartinez/Hello-World
03eeb596b72f7564f5d5cfcb3748dc8ed99b49c6
3015c79ed1258a832fec230348c7c52d20ebe2cd
refs/heads/master
2020-09-17T14:06:11.809580
2020-02-19T08:47:44
2020-02-19T08:47:44
224,095,351
0
0
null
null
null
null
UTF-8
C++
false
false
133
cpp
// My First Program #include<iostream> using namespace std; int main() { cout << "Hello World" << endl; return 0; }
[ "noreply@github.com" ]
dbmartinez.noreply@github.com
41460951f655cd9bcc27ac7f31689b718a82a07a
95a43c10c75b16595c30bdf6db4a1c2af2e4765d
/codecrawler/_code/hdu1846/16209349.cpp
785df32b6afa350223f9855b03583d73f27e5891
[]
no_license
kunhuicho/crawl-tools
945e8c40261dfa51fb13088163f0a7bece85fc9d
8eb8c4192d39919c64b84e0a817c65da0effad2d
refs/heads/master
2021-01-21T01:05:54.638395
2016-08-28T17:01:37
2016-08-28T17:01:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
426
cpp
#include<iostream> using namespace std; int main() { int cCase; cin >>cCase; while(cCase--){ int n,m; bool flag = true; cin >>n >>m; if(m >= n) flag = true; else if(n%(m+1)) flag = true; else flag = false; if(flag) cout <<"first" <<endl; else cout <<"second" <<endl; } return 0; }
[ "zhouhai02@meituan.com" ]
zhouhai02@meituan.com
a019c47b4de94f8ace07e177f7e9eb49e8b45575
883887c3c84bd3ac4a11ac76414129137a1b643b
/Cscl3DWS/RenderManager/Classes/LinkCollector.h
e65fc76e8c3247823b754c68d969825cdab64d3a
[]
no_license
15831944/vAcademia
4dbb36d9d772041e2716506602a602d516e77c1f
447f9a93defb493ab3b6f6c83cbceb623a770c5c
refs/heads/master
2022-03-01T05:28:24.639195
2016-08-18T12:32:22
2016-08-18T12:32:22
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
442
h
#pragma once #include "CommonRenderManagerHeader.h" // базовый класс для объекта, которому другие объекты // отдают ссылки на себя или на связанные объекты class CLinkCollector { public: CLinkCollector(); ~CLinkCollector(); void AddLink(void* pLink); void DeleteLink(void* pLink); std::vector<void*>& GetLinks(); private: MP_VECTOR<void*> m_links; };
[ "ooo.vspaces@gmail.com" ]
ooo.vspaces@gmail.com
c7da562b5e0ab1b957ef70c458dd19df6b9b2471
06831a34907809aa0fa9ef536575891a2bf94a2d
/buildings.cpp
66ed02ac2a24e540d5401cf60d8d95bca1b1667a
[]
no_license
jpdyno/missile_command_splashkit
43b208bf394b6371bacad3c3da443f98f6a02e81
3fd5e207e0af662d1625b4f668b9bc9cd1ea7318
refs/heads/main
2023-04-10T00:14:08.193485
2021-04-18T02:32:59
2021-04-18T02:32:59
359,023,335
0
0
null
null
null
null
UTF-8
C++
false
false
5,199
cpp
// Missile Command // JP Karnilowicz // buildings.cpp // procedures and functions relating to creating, updating and drawing the building objects in game #include "game.h" building_data create_building(int location) // create a new game { building_data new_building; // create new buildings to add into game_data double y; // y position of buildings double x; // x position of first building bitmap building_bitmap; // building bitmap new_building.location = location; // give building it's location building_bitmap = bitmap_named("building_" + to_string(location)); // load default building bitmap into variable new_building.building_sprite = create_sprite(building_bitmap); // assign default building bitmap sprite switch (location) // apply appropriate location of building along x axis { case 1: // First location x = 75; // 100 pixels from left edge break; // case 2: // Second locationg x = 250; // 250 pixels from left edge break; // case 3: // Third location x = 400; // 400 pixels from left edge break; // case 4: // Fourth location x = screen_width() - bitmap_width(building_bitmap) - 400; // 400 pixels from right edge break; // case 5: // Fifth location x = screen_width() - bitmap_width(building_bitmap) - 250; // 250 pixels from right edge break; // default: // Sixth x = screen_width() - bitmap_width(building_bitmap) - 75; // 100 pixels from right edge break; // } // sprite_set_x(new_building.building_sprite, x); // Assign x position of building y = screen_height() - bitmap_height(building_bitmap) - 64; // Place all buildings at bottom of screen, with 64 pixel buffer for the ground sprite_set_y(new_building.building_sprite, y); // Assign y position of building new_building.destroyed = false; // new building is not destroyed return new_building; // return new building data } void draw_buildings(const vector<building_data> &buildings) { for (int i = 0; i < buildings.size(); i++) // interate to draw all buildings { // draw_sprite(buildings[i].building_sprite); // draw appropriate sprite } } void building_sprite_destroyed(building_data &building) { if (!building.destroyed) // If building has beent tagged destroyed { // bitmap building_destroyed_bitmap; // new building destroyed bitmap sprite building_destroyed_sprite; // new building destroyed sprite point_2d building_xy = sprite_position(building.building_sprite); // get position of old building sprite building_destroyed_bitmap = bitmap_named("building_" + to_string(building.location) + "_destroyed"); // load building destroyed bitmap into variable building_destroyed_sprite = create_sprite(building_destroyed_bitmap); // create new sprite from building destroyed bitmap building_xy.y = screen_height() - bitmap_height(building_destroyed_bitmap) - 64; // compensate y axis position, since building destroyed sprite is shorter than the default building sprite sprite_set_position(building_destroyed_sprite, building_xy); // load compensated coords into building destroyed sprite building.building_sprite = building_destroyed_sprite; // replace building sprite with building destroyed sprite } } int buildings_still_standing(const vector<building_data> &buildings) { int count = 0; // start counter at zero for (int i = 0; i < buildings.size(); i++) // loop through building vector { // if (!buildings[i].destroyed) // if buidling is not tagged as destroyed { // count++; // add to count } } return count; }
[ "noreply@github.com" ]
jpdyno.noreply@github.com
e97c94e50e3fa37bdc52b0a9c0a110a534743cc5
62e7212d6c1f83921729d599f2970c81e41b5e0c
/V4.0/Src/Plugins/org.owm.terminal/PTerminal/ChildFrame.h
3a43ec53770e574be56cbf6f60180aef5880b51e
[]
no_license
safemens/Script.NET
145ec95e6ac53c21bae07e4b34faae6724facc56
3e559d1c617123019fa47d08e379a324c8606312
refs/heads/master
2021-01-15T20:38:35.227089
2018-09-11T08:30:48
2018-09-11T08:30:48
11,521,946
0
0
null
null
null
null
UTF-8
C++
false
false
1,403
h
#if !defined(AFX_CHILDFRAME_H__AA80FC30_B33E_4D69_A4F5_E9F8762C465D__INCLUDED_) #define AFX_CHILDFRAME_H__AA80FC30_B33E_4D69_A4F5_E9F8762C465D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ChildFrame.h : header file // ///////////////////////////////////////////////////////////////////////////// // CChildFrame frame class CChildFrame : public CMDIChildWnd { DECLARE_DYNCREATE(CChildFrame) protected: CChildFrame(); // protected constructor used by dynamic creation // Attributes public: // Operations public: void SwitchShell(int nShellMode); void SetShell(CString strMsg); void SetConnInfo(CString strMsg); void SetTermType(CString strType); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildFrame) //}}AFX_VIRTUAL protected: CXTPToolBar m_wndToolBar; CStatusBar m_wndStatusBar; // Implementation protected: virtual ~CChildFrame(); // Generated message map functions //{{AFX_MSG(CChildFrame) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnClose(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CHILDFRAME_H__AA80FC30_B33E_4D69_A4F5_E9F8762C465D__INCLUDED_)
[ "script.net@gmail.com" ]
script.net@gmail.com
04ce14e48f5a6ab460b1fc51a7c283a29c91df40
7888d2af010aeed43a52c9e983f1e08586e8e227
/QSS_SourceCode/QSS/Source/GUI/SpectrumPlotComponent.cpp
ba10da862cca58b10cca49c11c7981daff3e6060
[]
no_license
CreativeCodingLab/QuasarSonify
f5d4b55e3936234a8107e0ae14641d0a4c360716
2bab1445288074766a727cd77cb126c90450e201
refs/heads/master
2021-03-15T18:59:49.541446
2020-12-16T23:55:56
2020-12-16T23:55:56
246,873,374
0
0
null
null
null
null
UTF-8
C++
false
false
3,985
cpp
/* ============================================================================== This file was auto-generated! ============================================================================== */ #include "SpectrumPlotComponent.h" //============================================================================== SpectrumPlotComponent::SpectrumPlotComponent() { Random r; // for(int i = 0; i < 50; i++) // { // spectralPoint sp; // sp.wavelength = 0; // sp.flux = r.nextFloat(); // // spectralPlot.push_back(sp); // } } void SpectrumPlotComponent::formatPlotAndRepaint() { // format the plot for our view... float yMax = -999; float yMin = 999; float minMaxX[2] = {9999, -9999}; for(int i = 0; i < spectralPlot.size(); i++) { if(spectralPlot[i].flux > yMax) { yMax = spectralPlot[i].flux; } if(spectralPlot[i].flux < yMin) { yMin = spectralPlot[i].flux; } } // normalize the y-dimension of the plot for(int i = 0; i < spectralPlot.size(); i++) { float topMargin = 30; float bottomMargin = 0; float yWindow = getHeight() - topMargin - bottomMargin; spectralPlot[i].curY = topMargin + yWindow * (1 - spectralPlot[i].flux); } repaint(); } void SpectrumPlotComponent::paint(Graphics& g) { g.setColour(Colours::black.withAlpha(0.65f)); g.fillAll(); // the zero horizontal line and red shift marker g.setColour(Colours::red); g.drawHorizontalLine(30, 0, getWidth()); // draw the absorption plot if(xCenter3 > 0) { int startIndx = xCenter3 - xWidth / 2; float windowSize = xWidth; // draw the path of the plot float xIncr = (float)getWidth() / windowSize;//(float)spectralPlot.size() ; float xPos = 0; Path p; p.startNewSubPath(0, spectralPlot[startIndx].curY); xPos += xIncr; for(int i = startIndx + 1; i < startIndx + windowSize; i++) { p.lineTo(xPos, spectralPlot[i].curY); xPos += xIncr; } p = p.createPathWithRoundedCorners(5); g.setColour(Colours::white.withAlpha(0.2f)); g.strokePath(p, PathStrokeType (1.0)); } if(xCenter2 > 0) { int startIndx = xCenter2 - xWidth / 2; float windowSize = xWidth; // draw the path of the plot float xIncr = (float)getWidth() / windowSize;//(float)spectralPlot.size() ; float xPos = 0; Path p; p.startNewSubPath(0, spectralPlot[startIndx].curY); xPos += xIncr; for(int i = startIndx + 1; i < startIndx + windowSize; i++) { p.lineTo(xPos, spectralPlot[i].curY); xPos += xIncr; } p = p.createPathWithRoundedCorners(5); g.setColour(Colours::white.withAlpha(0.5f)); g.strokePath(p, PathStrokeType (1.0)); } float verticalLineX = 0; if(xCenter1 > 0) { int startIndx = xCenter1 - xWidth / 2; float windowSize = xWidth; // draw the path of the plot float xIncr = (float)getWidth() / windowSize;//(float)spectralPlot.size() ; float xPos = 0; Path p; p.startNewSubPath(0, spectralPlot[startIndx].curY); xPos += xIncr; for(int i = startIndx + 1; i < startIndx + windowSize; i++) { if(i == xCenter1) { verticalLineX = xPos; } p.lineTo(xPos, spectralPlot[i].curY); xPos += xIncr; } p = p.createPathWithRoundedCorners(5); g.setColour(Colours::white); g.strokePath(p, PathStrokeType (1.0)); } g.setColour(Colours::red); g.drawVerticalLine(verticalLineX, 0, getHeight()); } void SpectrumPlotComponent::resized() { }
[ "brian.hansen78@gmail.com" ]
brian.hansen78@gmail.com
511b8f0f742aaa6430d78c9cb2ac00a4b332e7f1
9aa2182c77a326fcd994b139903b37504b90b13b
/netapi/customtcp/tcpserver.cpp
8a2df737080d3e826caf0aee2a051fffb3d527e8
[]
no_license
shawl/qt_tcp-udp
4d9253a5e435c7889579485124973bf7dd07e974
428ebe84f86e10e42b0936185b0500d92b766b22
refs/heads/master
2023-03-18T02:11:04.074124
2020-12-08T13:48:04
2020-12-08T13:48:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,251
cpp
#include "tcpserver.h" NETAPI_NAMESPACE_BEGIN TcpServer::TcpServer(QObject *parent) : QTcpServer(parent) { } TcpServer::~TcpServer() { this->stop(); } bool TcpServer::start(TcpServerData &conf) { if (isRunning) { return true; } //验证数据 conf.verify(); //启动线程池 sessionThreads.start(conf.threadNum); //监听端口 if (!this->listen(QHostAddress::Any, (quint16)conf.port)) { return false; } isRunning = true; qDebug() << "TcpServer::Start threadID:"<< QThread::currentThreadId(); return true; } void TcpServer::stop() { if (!isRunning) { return; } //关闭监听 this->close(); //关闭线程池 sessionThreads.stop(); isRunning = false; } std::vector<uint32_t> TcpServer::getSessionSize() const { return sessionThreads.getSessionSize(); } void TcpServer::incomingConnection(qintptr handle) { qDebug() << "TcpServer::incomingConnection threadID:"<< QThread::currentThreadId(); std::shared_ptr<TcpSession> session = sessionThreads.createSession(handle); if (this->onAccepted) { this->onAccepted(session); } } bool TcpServer::getIsRunning() const { return isRunning; } NETAPI_NAMESPACE_END
[ "744763941@qq.com" ]
744763941@qq.com
b0d75d8e05c44f57875de37d15f933225c46dc4b
d2fb019e63eb66f9ddcbdf39d07f7670f8cf79de
/groups/bsl/bslmf/bslmf_ismemberfunctionpointer.cpp
b571c909272103d36360ecc8d985c854008f7f3d
[ "MIT" ]
permissive
gosuwachu/bsl
4fa8163a7e4b39e4253ad285b97f8a4d58020494
88cc2b2c480bcfca19e0f72753b4ec0359aba718
refs/heads/master
2021-01-17T05:36:55.605787
2013-01-15T19:48:00
2013-01-15T19:48:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,448
cpp
// bslmf_ismemberfunctionpointer.cpp -*-C++-*- #include <bslmf_ismemberfunctionpointer.h> #include <bsls_ident.h> BSLS_IDENT("$Id$ $CSID$") // ---------------------------------------------------------------------------- // Copyright (C) 2012 Bloomberg L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
[ "abeels@bloomberg.net" ]
abeels@bloomberg.net
0424940b01fa6c87ec3132d5440ce66bdf8aa5d5
672352cc76c4f829fa86e8baf77d085984a764d0
/ComponentUnicapImageServer/smartsoft/src-gen/ImageQueryHandlerCore.cc
a3a196e032f9238715691213f6301c66cd809031
[]
no_license
ipa-nhg/ComponentRepository
d58e692bf89da30661aaf951a2c07c34e7e8a235
336fbf6382eb88de4165fb15777429107afcf9bc
refs/heads/master
2020-08-01T05:23:00.741635
2019-09-20T13:48:08
2019-09-20T13:48:08
210,878,505
0
0
null
2019-09-25T15:25:50
2019-09-25T15:25:49
null
UTF-8
C++
false
false
1,979
cc
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #include "ImageQueryHandlerCore.hh" #include "ImageQueryHandler.hh" // include observers ImageQueryHandlerCore::ImageQueryHandlerCore(Smart::IQueryServerPattern<CommBasicObjects::CommVoid, DomainVision::CommVideoImage, SmartACE::QueryId>* server) : Smart::IQueryServerHandler<CommBasicObjects::CommVoid, DomainVision::CommVideoImage, SmartACE::QueryId>(server) { } ImageQueryHandlerCore::~ImageQueryHandlerCore() { } void ImageQueryHandlerCore::updateAllCommObjects() { } void ImageQueryHandlerCore::notify_all_interaction_observers() { std::unique_lock<std::mutex> lock(interaction_observers_mutex); // try dynamically down-casting this class to the derived class // (we can do it safely here as we exactly know the derived class) if(const ImageQueryHandler* imageQueryHandler = dynamic_cast<const ImageQueryHandler*>(this)) { for(auto it=interaction_observers.begin(); it!=interaction_observers.end(); it++) { (*it)->on_update_from(imageQueryHandler); } } } void ImageQueryHandlerCore::attach_interaction_observer(ImageQueryHandlerObserverInterface *observer) { std::unique_lock<std::mutex> lock(interaction_observers_mutex); interaction_observers.push_back(observer); } void ImageQueryHandlerCore::detach_interaction_observer(ImageQueryHandlerObserverInterface *observer) { std::unique_lock<std::mutex> lock(interaction_observers_mutex); interaction_observers.remove(observer); }
[ "lutz@hs-ulm.de" ]
lutz@hs-ulm.de
eb21625e90e3ff28c597907f7cc9d1f9076a618e
f03c72e984bc4f517616511083978231ad3c3c41
/examples/envelope_test.cpp
04be1097435381faa340c93ea5494d95e2507513
[ "MIT" ]
permissive
stonemaster/SimpleAmqpClient
dec71c285000cf7897ce8c07f23d20087e86de34
8198d7b58ca17b451e1d9173eeafbba1a8fd33e7
refs/heads/master
2021-01-16T18:52:39.766213
2012-07-06T07:44:37
2012-07-06T07:44:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,939
cpp
/* * ***** BEGIN LICENSE BLOCK ***** * Version: MIT * * Portions created by VMware are Copyright (c) 2007-2012 VMware, Inc. * All Rights Reserved. * * Portions created by Tony Garnock-Jones are Copyright (c) 2009-2010 * VMware, Inc. and Tony Garnock-Jones. All Rights Reserved. * * 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. * ***** END LICENSE BLOCK ***** */ #include <iostream> #include "SimpleAmqpClient.h" using namespace AmqpClient; int main() { const std::string EXCHANGE_NAME = "SimpleAmqpClientEnvelopeTest"; const std::string ROUTING_KEY = "SACRoutingKey"; const std::string CONSUMER_TAG = "SACConsumerTag"; try { Channel::ptr_t channel = Channel::Create(); channel->DeclareExchange(EXCHANGE_NAME, Channel::EXCHANGE_TYPE_FANOUT); std::string queue = channel->DeclareQueue(""); channel->BindQueue(queue, EXCHANGE_NAME, ROUTING_KEY); channel->BasicPublish(EXCHANGE_NAME, ROUTING_KEY, BasicMessage::Create("MessageBody")); channel->BasicPublish(EXCHANGE_NAME, ROUTING_KEY, BasicMessage::Create("MessageBody2")); channel->BasicPublish(EXCHANGE_NAME, ROUTING_KEY, BasicMessage::Create("MessageBody3")); channel->BasicConsume(queue, CONSUMER_TAG); Envelope::ptr_t env; for (int i = 0; i < 3; ++i) { if (channel->BasicConsumeMessage(env, 0)) { std::cout << "Envelope received: \n" << " Exchange: " << env->Exchange() << "\n Routing key: " << env->RoutingKey() << "\n Consumer tag: " << env->ConsumerTag() << "\n Delivery tag: " << env->DeliveryTag() << "\n Redelivered: " << env->Redelivered() << "\n Body: " << env->Message()->Body() << std::endl; } else { std::cout << "Basic Consume failed.\n"; } } } catch (AmqpResponseServerException& e) { std::cout << "Failure: " << e.what(); } return 0; }
[ "aega@med.umich.edu" ]
aega@med.umich.edu
cc707061550c0ed040e76b5de772f4c57a4bcedb
2c1b67b3af76a630681ac89c8ad8c78fa90e1c3b
/cg/cg00.cpp
089c0a627bf314d1100dcebe83f99a0197eebd97
[]
no_license
tejasmorkar/sem4
0ee5d653a166e5d62091de92248dedeaaaebeddc
aaf8e7cddc70283c2a490e9f9cb7eaa8ac96b84d
refs/heads/master
2020-11-25T08:57:21.502204
2020-02-27T05:10:02
2020-02-27T05:10:02
228,582,792
0
0
null
null
null
null
UTF-8
C++
false
false
176
cpp
#include<graphics.h> int main() { int gd = DETECT, gm; initgraph(&gd, &gm, NULL); setcolor(2); circle(100,200,50); delay(1000); return 0; }
[ "tejasmorkar@gmail.com" ]
tejasmorkar@gmail.com
df1b6976e18da173f5d5241a6ac7128fee52d161
00a2411cf452a3f1b69a9413432233deb594f914
/include/sqthird/soui/components/TaskLoop/semaphore.cpp
ca5e092e374bfd6b19b4748f99dc15d31b809928
[]
no_license
willing827/lyCommon
a16aa60cd6d1c6ec84c109c17ce2b26197a57550
206651ca3022eda45c083bbf6e796d854ae808fc
refs/heads/master
2021-06-26T21:01:21.314451
2020-11-06T05:34:23
2020-11-06T05:34:23
156,497,356
4
0
null
null
null
null
UTF-8
C++
false
false
1,190
cpp
#include <Windows.h> #include "semaphore.h" #include <cerrno> namespace SOUI { class SemaphorePrivate { public: HANDLE _hsem; }; Semaphore::Semaphore() : _private(*(new SemaphorePrivate())) { _private._hsem = ::CreateSemaphore(NULL, 0, 65535/* we need to discuss this max value*/, NULL); } Semaphore::~Semaphore() { ::CloseHandle(_private._hsem); delete &_private; } int Semaphore::wait() { DWORD ret = ::WaitForSingleObject (_private._hsem, INFINITE); if ( ret == WAIT_OBJECT_0) { return RETURN_OK; } return RETURN_ERROR; // This is a blocking wait, so any value other than WAIT_OBJECT_0 indicates an error! } int Semaphore::wait(unsigned int msec) { DWORD ret = ::WaitForSingleObject (_private._hsem, msec); if ( ret == WAIT_OBJECT_0) { return RETURN_OK; } // This is a timed wait, so WAIT_TIMEOUT value must be checked! if ( ret == WAIT_TIMEOUT ) { return RETURN_TIMEOUT; } return RETURN_ERROR; } void Semaphore::notify() { LONG previous_count; // let's just unblock one waiting thread. BOOL ret = ::ReleaseSemaphore(_private._hsem, 1, &previous_count); } }
[ "willing827@163.com" ]
willing827@163.com
caac0424514fee8236af12f5186b0362bc9f316e
5ab7032615235c10c68d738fa57aabd5bc46ea59
/russian_girl.cpp
b56ec3a2a277a7a4a77012f543c4c285feda64cc
[]
no_license
g-akash/spoj_codes
12866cd8da795febb672b74a565e41932abf6871
a2bf08ecd8a20f896537b6fbf96a2542b8ecf5c0
refs/heads/master
2021-09-07T21:07:17.267517
2018-03-01T05:41:12
2018-03-01T05:41:12
66,132,917
2
0
null
null
null
null
UTF-8
C++
false
false
521
cpp
#include<iostream> #include<vector> #include<string> using namespace std; int main() { string s; cin>>s; int sv=0,tr=0,tr1=0; for(int i=0;i<s.length()-1;i++) { if(s[i]=='0'&&s[i+1]=='0')sv++; else if(s[i]=='0'&&s[i+1]=='1')tr++; if(s[i]=='0')tr1++; } if(s[s.length()-1]=='0'&&s[0]=='0')sv++; if(s[s.length()-1]=='0'&&s[0]=='1')tr++; if(s[s.length()-1]=='0')tr1++; if(sv*(s.length()-tr1)==tr*tr1)cout<<"EQUAL"<<endl; else if(sv*(s.length()-tr1)>tr*tr1)cout<<"SHOOT"<<endl; else cout<<"ROTATE"<<endl; }
[ "akash.garg2007@gmail.com" ]
akash.garg2007@gmail.com
5837dd17754c4e6bee8b12144fbb6e044f99fcb3
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/rtorrent/gumtree/rtorrent_patch_hunk_185.cpp
a8492d2f296080a320083809e318e7c298b561cb
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
693
cpp
first = print_buffer(first, last, " [U %i/%i]", torrent::currently_unchoked(), torrent::max_unchoked()); first = print_buffer(first, last, " [S %i/%i/%i]", torrent::total_handshakes(), - torrent::open_sockets(), - torrent::max_open_sockets()); + torrent::connection_manager()->size(), + torrent::connection_manager()->max_size()); first = print_buffer(first, last, " [F %i/%i]", torrent::open_files(), torrent::max_open_files()); return first;
[ "993273596@qq.com" ]
993273596@qq.com
2d9973c5012853bd3e37adaa3a23d87f827abf02
93ce4932100b3bc984ea213f96ac99dd4d25c4cd
/test/sketch_json/sketch_json.ino
2b1e245096b1fa7846edb82e2885c8b0a4dc3efe
[]
no_license
jamehuang2012/thermostat
40e3dfea73a4710e48308ee3b3f02eabe0415567
f23c9c8a6264130bbb19a2838bbafcfa552280dc
refs/heads/master
2020-12-09T10:30:41.540259
2020-01-18T21:38:33
2020-01-18T21:38:33
233,277,898
0
0
null
null
null
null
UTF-8
C++
false
false
2,069
ino
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2020 // MIT License // // This example shows how to generate a JSON document with ArduinoJson. // // https://arduinojson.org/v6/example/generator/ #include <ArduinoJson.h> void setup() { // Initialize Serial port Serial.begin(115200); while (!Serial) continue; // Allocate the JSON document // // Inside the brackets, 200 is the RAM allocated to this document. // Don't forget to change this value to match your requirement. // Use arduinojson.org/v6/assistant to compute the capacity. StaticJsonDocument<200> doc; // StaticJsonObject allocates memory on the stack, it can be // replaced by DynamicJsonDocument which allocates in the heap. // // DynamicJsonDocument doc(200); // Add values in the document // doc["sensor"] = "gps"; doc["time"] = 1351824120; // Add an array. // JsonArray data = doc.createNestedArray("data"); data.add(48.756080); data.add(2.302038); // Generate the minified JSON and send it to the Serial port. // serializeJson(doc, Serial); // The above line prints: // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]} // Start a new line Serial.println(); // Generate the prettified JSON and send it to the Serial port. // serializeJsonPretty(doc, Serial); // The above line prints: // { // "sensor": "gps", // "time": 1351824120, // "data": [ // 48.756080, // 2.302038 // ] // } } void loop() { // not used in this example } // See also // -------- // // https://arduinojson.org/ contains the documentation for all the functions // used above. It also includes an FAQ that will help you solve any // serialization problem. // // The book "Mastering ArduinoJson" contains a tutorial on serialization. // It begins with a simple example, like the one above, and then adds more // features like serializing directly to a file or an HTTP request. // Learn more at https://arduinojson.org/book/ // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤
[ "jhuang@pivotalpayments.com" ]
jhuang@pivotalpayments.com
b7172da30a2c8d65a1b3944732d68410c8f110ae
cf9c3b6500b700488e16950f8a977f1a8c1e2496
/InformationScripting/src/python_bindings/generated/OOModel__Block.cpp
06d0a88a01267d86123116de032ff15317b030a3
[ "BSD-3-Clause" ]
permissive
dimitar-asenov/Envision
e45d2fcc8e536619299d4d9509daa23d2cd616a3
54b0a19dbef50163f2ee669e9584b854789f8213
refs/heads/development
2022-03-01T15:13:52.992999
2022-02-19T23:50:49
2022-02-19T23:50:49
2,650,576
88
17
null
2016-09-01T07:56:36
2011-10-26T12:03:58
C++
UTF-8
C++
false
false
8,800
cpp
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ // GENERATED FILE: CHANGES WILL BE LOST! #include "../AstApi.h" #include "OOModel/src/expressions/Expression.h" #include "OOModel/src/expressions/CommaExpression.h" #include "OOModel/src/expressions/UnaryOperation.h" #include "OOModel/src/expressions/MetaCallExpression.h" #include "OOModel/src/expressions/UnfinishedOperator.h" #include "OOModel/src/expressions/NullLiteral.h" #include "OOModel/src/expressions/FloatLiteral.h" #include "OOModel/src/expressions/TypeTraitExpression.h" #include "OOModel/src/expressions/SuperExpression.h" #include "OOModel/src/expressions/ConditionalExpression.h" #include "OOModel/src/expressions/TypeNameOperator.h" #include "OOModel/src/expressions/ThisExpression.h" #include "OOModel/src/expressions/BinaryOperation.h" #include "OOModel/src/expressions/EmptyExpression.h" #include "OOModel/src/expressions/MethodCallExpression.h" #include "OOModel/src/expressions/DeleteExpression.h" #include "OOModel/src/expressions/LambdaExpression.h" #include "OOModel/src/expressions/IntegerLiteral.h" #include "OOModel/src/expressions/VariableDeclarationExpression.h" #include "OOModel/src/expressions/StringLiteral.h" #include "OOModel/src/expressions/InstanceOfExpression.h" #include "OOModel/src/expressions/BooleanLiteral.h" #include "OOModel/src/expressions/types/FunctionTypeExpression.h" #include "OOModel/src/expressions/types/TypeQualifierExpression.h" #include "OOModel/src/expressions/types/TypeExpression.h" #include "OOModel/src/expressions/types/ArrayTypeExpression.h" #include "OOModel/src/expressions/types/AutoTypeExpression.h" #include "OOModel/src/expressions/types/ReferenceTypeExpression.h" #include "OOModel/src/expressions/types/PrimitiveTypeExpression.h" #include "OOModel/src/expressions/types/ClassTypeExpression.h" #include "OOModel/src/expressions/types/PointerTypeExpression.h" #include "OOModel/src/expressions/ReferenceExpression.h" #include "OOModel/src/expressions/ArrayInitializer.h" #include "OOModel/src/expressions/ThrowExpression.h" #include "OOModel/src/expressions/ErrorExpression.h" #include "OOModel/src/expressions/AssignmentExpression.h" #include "OOModel/src/expressions/GlobalScopeExpression.h" #include "OOModel/src/expressions/CharacterLiteral.h" #include "OOModel/src/expressions/CastExpression.h" #include "OOModel/src/expressions/NewExpression.h" #include "OOModel/src/declarations/Project.h" #include "OOModel/src/declarations/ExplicitTemplateInstantiation.h" #include "OOModel/src/declarations/MetaBinding.h" #include "OOModel/src/declarations/NameImport.h" #include "OOModel/src/declarations/Field.h" #include "OOModel/src/declarations/MetaCallMapping.h" #include "OOModel/src/declarations/Declaration.h" #include "OOModel/src/declarations/Method.h" #include "OOModel/src/declarations/VariableDeclaration.h" #include "OOModel/src/declarations/Module.h" #include "OOModel/src/declarations/Class.h" #include "OOModel/src/declarations/MetaDefinition.h" #include "OOModel/src/declarations/TypeAlias.h" #include "OOModel/src/elements/MemberInitializer.h" #include "OOModel/src/elements/Enumerator.h" #include "OOModel/src/elements/Modifier.h" #include "OOModel/src/elements/OOReference.h" #include "OOModel/src/elements/CatchClause.h" #include "OOModel/src/elements/FormalMetaArgument.h" #include "OOModel/src/elements/FormalResult.h" #include "OOModel/src/elements/CommentStatementItem.h" #include "OOModel/src/elements/StatementItemList.h" #include "OOModel/src/elements/FormalArgument.h" #include "OOModel/src/elements/StatementItem.h" #include "OOModel/src/elements/FormalTypeArgument.h" #include "OOModel/src/statements/SynchronizedStatement.h" #include "OOModel/src/statements/IfStatement.h" #include "OOModel/src/statements/ReturnStatement.h" #include "OOModel/src/statements/SwitchStatement.h" #include "OOModel/src/statements/CaseStatement.h" #include "OOModel/src/statements/BreakStatement.h" #include "OOModel/src/statements/TryCatchFinallyStatement.h" #include "OOModel/src/statements/DeclarationStatement.h" #include "OOModel/src/statements/ForEachStatement.h" #include "OOModel/src/statements/AssertStatement.h" #include "OOModel/src/statements/Statement.h" #include "OOModel/src/statements/ExpressionStatement.h" #include "OOModel/src/statements/ContinueStatement.h" #include "OOModel/src/statements/LoopStatement.h" #include "OOModel/src/statements/Block.h" #include "ModelBase/src/nodes/List.h" #include "ModelBase/src/nodes/Boolean.h" #include "ModelBase/src/nodes/Character.h" #include "ModelBase/src/nodes/NameText.h" #include "ModelBase/src/nodes/Float.h" #include "ModelBase/src/nodes/Text.h" #include "ModelBase/src/nodes/Reference.h" #include "ModelBase/src/nodes/UsedLibrary.h" #include "ModelBase/src/nodes/composite/CompositeNode.h" #include "ModelBase/src/nodes/Integer.h" #include "ModelBase/src/nodes/Node.h" #include "ModelBase/src/persistence/ClipboardStore.h" #include "ModelBase/src/commands/UndoCommand.h" namespace InformationScripting { using namespace boost::python; void initClassBlock() { bool (OOModel::Block::*Block_isSubtypeOf1)(const QString&) const = &OOModel::Block::isSubtypeOf; bool (OOModel::Block::*Block_isSubtypeOf2)(int) const = &OOModel::Block::isSubtypeOf; Model::CompositeIndex (*Block_registerNewAttribute1)(const Model::Attribute&) = &OOModel::Block::registerNewAttribute; Model::CompositeIndex (*Block_registerNewAttribute2)(const QString&, const QString&, bool, bool, bool) = &OOModel::Block::registerNewAttribute; auto aClass = class_<OOModel::Block, bases<OOModel::Statement>>("Block"); aClass.add_property("items", make_function(&OOModel::Block::items, return_internal_reference<>()), &OOModel::Block::setItems); aClass.def("typeName", make_function((const QString& ( OOModel::Block::*)())&OOModel::Block::typeName, return_value_policy<copy_const_reference>())); aClass.def("typeId", &OOModel::Block::typeId); aClass.def("hierarchyTypeIds", &OOModel::Block::hierarchyTypeIds); aClass.def("typeNameStatic", make_function(&OOModel::Block::typeNameStatic, return_value_policy<copy_const_reference>())); aClass.staticmethod("typeNameStatic"); aClass.def("typeIdStatic", &OOModel::Block::typeIdStatic); aClass.staticmethod("typeIdStatic"); aClass.def("initType", &OOModel::Block::initType); aClass.staticmethod("initType"); aClass.def("clone", make_function(&OOModel::Block::clone, return_internal_reference<>())); aClass.def("createDefaultInstance", make_function( &OOModel::Block::createDefaultInstance, return_internal_reference<>())); aClass.staticmethod("createDefaultInstance"); aClass.def("getMetaData", make_function(&OOModel::Block::getMetaData, return_internal_reference<>())); aClass.staticmethod("getMetaData"); aClass.def("isSubtypeOf", Block_isSubtypeOf1); aClass.def("isSubtypeOf", Block_isSubtypeOf2); aClass.def("registerNewAttribute", Block_registerNewAttribute1); aClass.def("registerNewAttribute", Block_registerNewAttribute2); } } /* namespace InformationScripting */
[ "dimitar.asenov@inf.ethz.ch" ]
dimitar.asenov@inf.ethz.ch
2c2ae17c59c6ba8f311196db5465372279bb7767
009dd29ba75c9ee64ef6d6ba0e2d313f3f709bdd
/Android/MobiVuold/MobiVU_testudp/jni/include/pv_omxcore.h
1dc8caadfb2a1f944d2ff42b5433333fa10a5ed1
[ "Apache-2.0" ]
permissive
AnthonyNystrom/MobiVU
c849857784c09c73b9ee11a49f554b70523e8739
b6b8dab96ae8005e132092dde4792cb363e732a2
refs/heads/master
2021-01-10T19:36:50.695911
2010-10-25T03:39:25
2010-10-25T03:39:25
1,015,426
3
3
null
null
null
null
UTF-8
C++
false
false
11,284
h
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #ifndef PV_OMXCORE_H_INCLUDED #define PV_OMXCORE_H_INCLUDED #ifndef PV_OMXDEFS_H_INCLUDED #include "pv_omxdefs.h" #endif #ifndef PV_OMX_QUEUE_H_INCLUDED #include "pv_omx_queue.h" #endif #ifndef OMX_Types_h #include "OMX_Types.h" #endif #ifndef OSCL_BASE_INCLUDED_H #include "oscl_base.h" #endif #ifndef OSCL_UUID_H_INCLUDED #include "oscl_uuid.h" #endif #ifndef OMX_Core_h #include "OMX_Core.h" #endif #ifndef OMX_Component_h #include "OMX_Component.h" #endif #if PROXY_INTERFACE #ifndef OMX_PROXY_INTERFACE_H_INCLUDED #include "omx_proxy_interface.h" #endif #endif #if USE_DYNAMIC_LOAD_OMX_COMPONENTS #ifndef OSCL_SHARED_LIBRARY_H_INCLUDED #include "oscl_shared_library.h" #endif #endif #define MAX_ROLES_SUPPORTED 3 #ifdef __cplusplus extern "C" { #endif OSCL_IMPORT_REF OMX_ERRORTYPE OMX_GetComponentsOfRole( OMX_IN OMX_STRING role, OMX_INOUT OMX_U32 *pNumComps, OMX_INOUT OMX_U8 **compNames); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_APIENTRY OMX_ComponentNameEnum( OMX_OUT OMX_STRING cComponentName, OMX_IN OMX_U32 nNameLength, OMX_IN OMX_U32 nIndex); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_APIENTRY OMX_FreeHandle(OMX_IN OMX_HANDLETYPE hComponent); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_APIENTRY OMX_GetHandle(OMX_OUT OMX_HANDLETYPE* pHandle, OMX_IN OMX_STRING cComponentName, OMX_IN OMX_PTR pAppData, OMX_IN OMX_CALLBACKTYPE* pCallBacks); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_GetRolesOfComponent( OMX_IN OMX_STRING compName, OMX_INOUT OMX_U32* pNumRoles, OMX_OUT OMX_U8** roles); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_SetupTunnel( OMX_IN OMX_HANDLETYPE hOutput, OMX_IN OMX_U32 nPortOutput, OMX_IN OMX_HANDLETYPE hInput, OMX_IN OMX_U32 nPortInput); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_GetContentPipe( OMX_OUT OMX_HANDLETYPE *hPipe, OMX_IN OMX_STRING szURI); OSCL_IMPORT_REF OMX_BOOL OMXConfigParser( OMX_PTR aInputParameters, OMX_PTR aOutputParameters); #ifdef __cplusplus } #endif #if USE_DYNAMIC_LOAD_OMX_COMPONENTS //Dynamic loading interface definitions #define PV_OMX_SHARED_INTERFACE OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x67) #define PV_OMX_CREATE_INTERFACE OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x68) #define PV_OMX_DESTROY_INTERFACE OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x69) #define PV_OMX_AVCDEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x6a) #define PV_OMX_M4VDEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x6b) #define PV_OMX_H263DEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x6c) #define PV_OMX_WMVDEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x6d) #define PV_OMX_AACDEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x6e) #define PV_OMX_AMRDEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x6f) #define PV_OMX_MP3DEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x70) #define PV_OMX_WMADEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x71) #define PV_OMX_AVCENC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x72) #define PV_OMX_M4VENC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x73) #define PV_OMX_H263ENC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x74) #define PV_OMX_AMRENC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x75) #define PV_OMX_AACENC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x76) #define PV_OMX_RVDEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x77) #define PV_OMX_RADEC_UUID OsclUuid(0x1d4769f0,0xca0c,0x11dc,0x95,0xff,0x08,0x00,0x20,0x0c,0x9a,0x78) #define OMX_MAX_LIB_PATH 256 class OmxSharedLibraryInterface { public: virtual OsclAny *QueryOmxComponentInterface(const OsclUuid& aOmxTypeId, const OsclUuid& aInterfaceId) = 0; }; #endif // USE_DYNAMIC_LOAD_OMX_COMPONENTS // PV additions to OMX_EXTRADATATYPE enum #define OMX_ExtraDataNALSizeArray 0x7F123321 // random value above 0x7F000000 (start of the unused range for vendors) class ComponentRegistrationType { public: // name of the component used as identifier OMX_STRING ComponentName; OMX_STRING RoleString[MAX_ROLES_SUPPORTED]; OMX_U32 NumberOfRolesSupported; // pointer to factory function to be called when component needs to be instantiated OMX_ERRORTYPE(*FunctionPtrCreateComponent)(OMX_OUT OMX_HANDLETYPE* pHandle, OMX_IN OMX_PTR pAppData, OMX_PTR pProxy, OMX_STRING aOmxLibName, OMX_PTR &aOmxLib, OMX_PTR aOsclUuid, OMX_U32 &aRefCount); // pointer to function that destroys the component and its AO OMX_ERRORTYPE(*FunctionPtrDestroyComponent)(OMX_IN OMX_HANDLETYPE pHandle, OMX_PTR &aOmxLib, OMX_PTR aOsclUuid, OMX_U32 &aRefCount); //This function will return the role string void GetRolesOfComponent(OMX_STRING* aRole_string) { for (OMX_U32 ii = 0; ii < NumberOfRolesSupported; ii++) { aRole_string[ii] = RoleString[ii]; } } // for dynamic loading OMX_STRING SharedLibraryName; OMX_PTR SharedLibraryPtr; OMX_PTR SharedLibraryOsclUuid; OMX_U32 SharedLibraryRefCounter; }; typedef struct CoreDescriptorType { QueueType* pMessageQueue; // The output queue for the messages to be send to the components } CoreDescriptorType; /** This structure contains all the fields of a message handled by the core */ struct CoreMessage { OMX_COMPONENTTYPE* pComponent; /// A reference to the main structure that defines a component. It represents the target of the message OMX_S32 MessageType; /// the flag that specifies if the message is a command, a warning or an error OMX_S32 MessageParam1; /// the first field of the message. Its use is the same as specified for the command in OpenMAX spec OMX_S32 MessageParam2; /// the second field of the message. Its use is the same as specified for the command in OpenMAX spec OMX_PTR pCmdData; /// This pointer could contain some proprietary data not covered by the standard }; typedef struct PV_OMXComponentCapabilityFlagsType { ////////////////// OMX COMPONENT CAPABILITY RELATED MEMBERS OMX_BOOL iIsOMXComponentMultiThreaded; OMX_BOOL iOMXComponentSupportsExternalOutputBufferAlloc; OMX_BOOL iOMXComponentSupportsExternalInputBufferAlloc; OMX_BOOL iOMXComponentSupportsMovableInputBuffers; OMX_BOOL iOMXComponentSupportsPartialFrames; OMX_BOOL iOMXComponentUsesNALStartCodes; OMX_BOOL iOMXComponentCanHandleIncompleteFrames; OMX_BOOL iOMXComponentUsesFullAVCFrames; OMX_BOOL iOMXComponentUsesInterleaved2BNALSizes; OMX_BOOL iOMXComponentUsesInterleaved4BNALSizes; } PV_OMXComponentCapabilityFlagsType; class OMXGlobalData { public: OMXGlobalData() : iInstanceCount(1), iOsclInit(false), iNumBaseInstance(0), iComponentIndex(0) { for (OMX_S32 ii = 0; ii < MAX_INSTANTIATED_COMPONENTS; ii++) { ipInstantiatedComponentReg[ii] = NULL; } } uint32 iInstanceCount; bool iOsclInit; //did we do OsclInit in OMX_Init? if so we must cleanup in OMX_Deinit. //Number of base instances OMX_U32 iNumBaseInstance; // Array to store component handles for future recognition of components etc. OMX_HANDLETYPE iComponentHandle[MAX_INSTANTIATED_COMPONENTS]; OMX_U32 iComponentIndex; // Array of supported component types (e.g. MP4, AVC, AAC, etc.) // they need to be registered // For each OMX Component type (e.g. Mp3, AVC, AAC) there is one entry in this table that contains info // such as component type, factory, destructor functions, library name for dynamic loading etc. // when the omx component is registered (at OMX_Init) ComponentRegistrationType* ipRegTemplateList[MAX_SUPPORTED_COMPONENTS]; // Array of pointers - For each OMX component that gets instantiated - the pointer to its registry structure // is saved here. This information is needed when the component is to be destroyed ComponentRegistrationType* ipInstantiatedComponentReg[MAX_INSTANTIATED_COMPONENTS]; // array of function pointers. For each component, a destructor function is assigned //OMX_ERRORTYPE(*ComponentDestructor[MAX_INSTANTIATED_COMPONENTS])(OMX_IN OMX_HANDLETYPE pHandle, OMX_PTR &aOmxLib, OMX_PTR aOsclUuid, OMX_U32 &aRefCount); #if PROXY_INTERFACE ProxyApplication_OMX* ipProxyTerm[MAX_INSTANTIATED_COMPONENTS]; #endif }; OSCL_IMPORT_REF OMX_ERRORTYPE OMX_MasterInit(); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_MasterDeinit(); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_MasterGetComponentsOfRole( OMX_IN OMX_STRING role, OMX_INOUT OMX_U32 *pNumComps, OMX_INOUT OMX_U8 **compNames); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_APIENTRY OMX_MasterComponentNameEnum( OMX_OUT OMX_STRING cComponentName, OMX_IN OMX_U32 nNameLength, OMX_IN OMX_U32 nIndex); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_APIENTRY OMX_MasterFreeHandle(OMX_IN OMX_HANDLETYPE hComponent); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_APIENTRY OMX_MasterGetHandle(OMX_OUT OMX_HANDLETYPE* pHandle, OMX_IN OMX_STRING cComponentName, OMX_IN OMX_PTR pAppData, OMX_IN OMX_CALLBACKTYPE* pCallBacks); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_MasterGetRolesOfComponent( OMX_IN OMX_STRING compName, OMX_INOUT OMX_U32* pNumRoles, OMX_OUT OMX_U8** roles); OSCL_IMPORT_REF OMX_BOOL OMX_MasterConfigParser( OMX_PTR aInputParameters, OMX_PTR aOutputParameters); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_SetupTunnel( OMX_IN OMX_HANDLETYPE hOutput, OMX_IN OMX_U32 nPortOutput, OMX_IN OMX_HANDLETYPE hInput, OMX_IN OMX_U32 nPortInput); OSCL_IMPORT_REF OMX_ERRORTYPE OMX_GetContentPipe( OMX_OUT OMX_HANDLETYPE *hPipe, OMX_IN OMX_STRING szURI); #endif
[ "nystrom.anthony@gmail.com" ]
nystrom.anthony@gmail.com
b367dab72fe752795069ff3744c05d9b3c35c42c
593a489a40d08287193be850416e7a6e7033b85d
/examples/uintTest/flow/audio_loop_test.cc
04e8319630eeac864ce078b57028b3b6b27c4176
[ "BSD-3-Clause" ]
permissive
xiaoshzx/rkmedia-1
e7983de87bf8a381e78287e63d13049346c3a22b
868b4f4bc160b342d7061a594af1746c814c27ba
refs/heads/master
2023-01-08T09:07:04.083554
2020-11-06T12:13:26
2020-11-06T12:13:26
310,641,071
6
1
null
null
null
null
UTF-8
C++
false
false
11,445
cc
// Copyright 2020 Fuzhou Rockchip Electronics Co., Ltd. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "assert.h" #include "signal.h" #include "stdint.h" #include "stdio.h" #include "unistd.h" #include <iostream> #include <memory> #include <string> #include "easymedia/buffer.h" #include "easymedia/control.h" #include "easymedia/flow.h" #include "easymedia/key_string.h" #include "easymedia/media_config.h" #include "easymedia/media_type.h" #include "easymedia/reflector.h" #include "easymedia/stream.h" #include "easymedia/utils.h" static bool quit = false; static void sigterm_handler(int sig) { LOG("signal %d\n", sig); quit = true; } std::shared_ptr<easymedia::Flow> create_flow(const std::string &flow_name, const std::string &flow_param, const std::string &elem_param) { auto &&param = easymedia::JoinFlowParam(flow_param, 1, elem_param); auto ret = easymedia::REFLECTOR(Flow)::Create<easymedia::Flow>( flow_name.c_str(), param.c_str()); if (!ret) fprintf(stderr, "Create flow %s failed\n", flow_name.c_str()); return ret; } std::shared_ptr<easymedia::Flow> create_alsa_flow(std::string aud_in_path, SampleInfo &info, bool capture) { std::string flow_name; std::string flow_param; std::string sub_param; std::string stream_name; if (capture) { // default sync mode flow_name = "source_stream"; stream_name = "alsa_capture_stream"; } else { flow_name = "output_stream"; stream_name = "alsa_playback_stream"; PARAM_STRING_APPEND(flow_param, KEK_THREAD_SYNC_MODEL, KEY_ASYNCCOMMON); PARAM_STRING_APPEND(flow_param, KEK_INPUT_MODEL, KEY_DROPFRONT); PARAM_STRING_APPEND_TO(flow_param, KEY_INPUT_CACHE_NUM, 5); } flow_param = ""; sub_param = ""; PARAM_STRING_APPEND(flow_param, KEY_NAME, stream_name); PARAM_STRING_APPEND(sub_param, KEY_DEVICE, aud_in_path); PARAM_STRING_APPEND(sub_param, KEY_SAMPLE_FMT, SampleFmtToString(info.fmt)); PARAM_STRING_APPEND_TO(sub_param, KEY_CHANNELS, info.channels); PARAM_STRING_APPEND_TO(sub_param, KEY_FRAMES, info.nb_samples); PARAM_STRING_APPEND_TO(sub_param, KEY_SAMPLE_RATE, info.sample_rate); auto audio_source_flow = create_flow(flow_name, flow_param, sub_param); if (!audio_source_flow) { printf("Create flow %s failed\n", flow_name.c_str()); exit(EXIT_FAILURE); } else { printf("%s flow ready!\n", flow_name.c_str()); } return audio_source_flow; } std::shared_ptr<easymedia::Flow> create_audio_filter_flow(SampleInfo &info, std::string filter_name) { std::string flow_name; std::string flow_param; std::string sub_param; flow_name = "filter"; flow_param = ""; PARAM_STRING_APPEND(flow_param, KEY_NAME, filter_name); PARAM_STRING_APPEND(flow_param, KEY_INPUTDATATYPE, SampleFmtToString(info.fmt)); PARAM_STRING_APPEND(flow_param, KEY_OUTPUTDATATYPE, SampleFmtToString(info.fmt)); sub_param = ""; PARAM_STRING_APPEND(sub_param, KEY_SAMPLE_FMT, SampleFmtToString(info.fmt)); PARAM_STRING_APPEND_TO(sub_param, KEY_CHANNELS, info.channels); PARAM_STRING_APPEND_TO(sub_param, KEY_SAMPLE_RATE, info.sample_rate); PARAM_STRING_APPEND_TO(sub_param, KEY_FRAMES, info.nb_samples); flow_param = easymedia::JoinFlowParam(flow_param, 1, sub_param); auto flow = easymedia::REFLECTOR(Flow)::Create<easymedia::Flow>( flow_name.c_str(), flow_param.c_str()); if (!flow) { fprintf(stderr, "Create flow %s failed\n", flow_name.c_str()); exit(EXIT_FAILURE); } return flow; } void usage(char *name) { LOG("\nUsage: simple mode\t%s -a default -o default -s 1 -f S16 -r 8000 -c " "1\n", name); LOG("\nUsage: complex mode\t%s -a default -o default -f S16 -r 16000 -c 2 -F " "FLTP -R " "48000 -C 1\n", name); LOG("\tNOTICE: format: -f -F [U8 S16 S32 FLT U8P S16P S32P FLTP G711A G711U]\n"); LOG("\tNOTICE: channels: -c -C [1 2]\n"); LOG("\tNOTICE: samplerate: -r -R [8000 16000 24000 32000 441000 48000]\n"); LOG("\tNOTICE: capture params: -f -c -r\n"); LOG("\tNOTICE: resample params: -F -C -R\n"); exit(EXIT_FAILURE); } SampleFormat parseFormat(std::string args) { if (!args.compare("U8")) return SAMPLE_FMT_U8; if (!args.compare("S16")) return SAMPLE_FMT_S16; if (!args.compare("S32")) return SAMPLE_FMT_S32; if (!args.compare("FLT")) return SAMPLE_FMT_FLT; if (!args.compare("U8P")) return SAMPLE_FMT_U8P; if (!args.compare("S16P")) return SAMPLE_FMT_S16P; if (!args.compare("S32P")) return SAMPLE_FMT_S32P; if (!args.compare("FLTP")) return SAMPLE_FMT_FLTP; if (!args.compare("G711A")) return SAMPLE_FMT_G711A; if (!args.compare("G711U")) return SAMPLE_FMT_G711U; else return SAMPLE_FMT_NONE; } static char optstr[] = "?a:o:s:f:r:c:F:R:C:"; int main(int argc, char **argv) { SampleFormat fmt = SAMPLE_FMT_S16; int channels = 1; int sample_rate = 8000; int nb_samples; SampleFormat res_fmt = SAMPLE_FMT_S16; int res_channels = 1; int res_sample_rate = 8000; int simple_mode = 0; int c; std::string aud_in_path = "default"; std::string output_path = "default"; std::string flow_name; std::string flow_param; std::string sub_param; std::string stream_name; easymedia::REFLECTOR(Stream)::DumpFactories(); easymedia::REFLECTOR(Flow)::DumpFactories(); opterr = 1; while ((c = getopt(argc, argv, optstr)) != -1) { switch (c) { case 'a': aud_in_path = optarg; LOG("audio device path: %s\n", aud_in_path.c_str()); break; case 'o': output_path = optarg; LOG("output device path: %s\n", output_path.c_str()); break; case 'f': fmt = parseFormat(optarg); if (fmt == SAMPLE_FMT_NONE) usage(argv[0]); break; case 'r': sample_rate = atoi(optarg); if (sample_rate != 8000 && sample_rate != 16000 && sample_rate != 24000 && sample_rate != 32000 && sample_rate != 44100 && sample_rate != 48000) { LOG("sorry, sample_rate %d not supported\n", sample_rate); usage(argv[0]); } break; case 'c': channels = atoi(optarg); if (channels < 1 || channels > 2) usage(argv[0]); break; case 's': simple_mode = atoi(optarg); break; case 'F': res_fmt = parseFormat(optarg); if (res_fmt == SAMPLE_FMT_NONE) usage(argv[0]); break; case 'R': res_sample_rate = atoi(optarg); if (res_sample_rate != 8000 && res_sample_rate != 16000 && res_sample_rate != 24000 && res_sample_rate != 32000 && res_sample_rate != 44100 && res_sample_rate != 48000) { LOG("sorry, sample_rate %d not supported\n", res_sample_rate); usage(argv[0]); } break; case 'C': res_channels = atoi(optarg); if (res_channels < 1 || res_channels > 2) usage(argv[0]); break; case '?': default: usage(argv[0]); break; } } if (simple_mode) { const int sample_time_ms = 20; // anr only support 10/16/20ms nb_samples = sample_rate * sample_time_ms / 1000; SampleInfo sample_info = {fmt, channels, sample_rate, nb_samples}; LOG("Loop in simple mode: capture -> playback\n"); // 1. alsa capture flow std::shared_ptr<easymedia::Flow> audio_source_flow = create_alsa_flow(aud_in_path, sample_info, true); if (!audio_source_flow) { LOG("Create flow alsa_capture_flow failed\n"); exit(EXIT_FAILURE); } // 2. alsa playback flow std::shared_ptr<easymedia::Flow> audio_sink_flow = create_alsa_flow(output_path, sample_info, false); if (!audio_sink_flow) { LOG("Create flow alsa_capture_flow failed\n"); exit(EXIT_FAILURE); } audio_source_flow->AddDownFlow(audio_sink_flow, 0, 0); signal(SIGINT, sigterm_handler); while (!quit) { easymedia::msleep(100); } audio_source_flow->RemoveDownFlow(audio_sink_flow); audio_source_flow.reset(); audio_sink_flow.reset(); return 0; } int res_nb_samples; const int sample_time_ms = 20; // anr only support 10/16/20ms nb_samples = sample_rate * sample_time_ms / 1000; res_nb_samples = res_sample_rate * sample_time_ms / 1000; SampleInfo sample_info = {fmt, channels, sample_rate, nb_samples}; SampleInfo res_sample_info = {res_fmt, res_channels, res_sample_rate, res_nb_samples}; LOG("Loop in complex mode: capture -> anr -> resample -> resample -> fifo -> " "playback\n"); // 1. alsa capture flow std::shared_ptr<easymedia::Flow> audio_source_flow = create_alsa_flow(aud_in_path, sample_info, true); if (!audio_source_flow) { LOG("Create flow alsa_capture_flow failed\n"); exit(EXIT_FAILURE); } int volume = 70; audio_source_flow->Control(easymedia::S_ALSA_VOLUME, &volume); // 2. audio ANR std::shared_ptr<easymedia::Flow> anr_flow = create_audio_filter_flow(sample_info, "ANR"); if (!anr_flow) { LOG("Create flow audio_resample_flow failed\n"); exit(EXIT_FAILURE); } // 3. alsa resample std::shared_ptr<easymedia::Flow> audio_resample_flow = create_audio_filter_flow(res_sample_info, "ffmpeg_resample"); if (!audio_resample_flow) { LOG("Create flow audio_resample_flow failed\n"); exit(EXIT_FAILURE); } // 4. alsa resample back std::shared_ptr<easymedia::Flow> audio_resample_back_flow = create_audio_filter_flow(sample_info, "ffmpeg_resample"); if (!audio_resample_back_flow) { LOG("Create flow audio_resample_flow failed\n"); exit(EXIT_FAILURE); } // 5. audio fifo to fixed output samples sample_info.nb_samples *= 2; std::shared_ptr<easymedia::Flow> audio_fifo_flow = create_audio_filter_flow(sample_info, "ffmpeg_audio_fifo"); if (!audio_fifo_flow) { LOG("Create flow audio_fifo_flow failed\n"); exit(EXIT_FAILURE); } // 6. alsa playback flow std::shared_ptr<easymedia::Flow> audio_sink_flow = create_alsa_flow(output_path, sample_info, false); if (!audio_sink_flow) { LOG("Create flow alsa_capture_flow failed\n"); exit(EXIT_FAILURE); } volume = 60; audio_sink_flow->Control(easymedia::S_ALSA_VOLUME, &volume); audio_fifo_flow->AddDownFlow(audio_sink_flow, 0, 0); audio_resample_back_flow->AddDownFlow(audio_fifo_flow, 0, 0); audio_resample_flow->AddDownFlow(audio_resample_back_flow, 0, 0); anr_flow->AddDownFlow(audio_resample_flow, 0, 0); audio_source_flow->AddDownFlow(anr_flow, 0, 0); signal(SIGINT, sigterm_handler); while (!quit) { easymedia::msleep(100); printf("Switch ANR ON/OFF: 0|1\n"); char value = getchar(); if (value == '0' || value == '1') { int i_value = value - '0'; anr_flow->Control(easymedia::S_ANR_ON, &i_value); } } audio_fifo_flow->RemoveDownFlow(audio_sink_flow); audio_resample_back_flow->RemoveDownFlow(audio_fifo_flow); audio_resample_flow->RemoveDownFlow(audio_resample_back_flow); anr_flow->RemoveDownFlow(audio_resample_flow); audio_source_flow->RemoveDownFlow(anr_flow); audio_resample_back_flow.reset(); audio_resample_flow.reset(); anr_flow.reset(); audio_source_flow.reset(); audio_fifo_flow.reset(); audio_sink_flow.reset(); return 0; }
[ "yuyz@rock-chips.com" ]
yuyz@rock-chips.com
a814bae602de66ab1e07d38d042550dbc4fd073a
8245e898fbd7bb655706de0a0c35078934ceee12
/C/read_csv/readin_arma.cpp
26dc9292e00d2ad4a20ed89057ac9c0ecfd720e3
[]
no_license
olszewskip/MDFS_playground
86e889bb08be0139ace42916c794eacfc657b74d
1cf7df6d8c60c2a4da7a9286a469bdb8855abb46
refs/heads/master
2020-04-08T21:01:22.839688
2019-05-15T14:29:06
2019-05-15T14:29:06
159,725,454
0
0
null
null
null
null
UTF-8
C++
false
false
1,218
cpp
// Copyright: me // g++ arma_1.cpp -DARMA_DONT_USE_WRAPPER -lopenblas -llapack #include <armadillo> #include <iostream> int main(int argc, const char **argv) { arma::Mat<double> M; M.load("madelon.csv"); std::cout << "first element: " << M(0, 0) << std::endl; std::cout << "number of rows: " << M.n_rows << std::endl; std::cout << "number of cols: " << M.n_cols << std::endl; std::cout << "number of elems: " << M.n_elem << std::endl; std::cout << "dimensions together: " << arma::size(M) << std::endl; std::cout << "number of elements in the 1st columns that are greater than 480: " << arma::sum(M.col(0) > 480) << std::endl; arma::Mat<double> M2 = M.cols(0, 2); std::cout << "number of columns in the new copy: " << M2.n_cols << std::endl; M2(0, 0) = 123; std::cout << "first element of the copy: " << M2(0, 0) << std::endl; std::cout << "first element of the original: " << M(0, 0) << std::endl; // overflowing copy: runtime error // arma::Mat<double> M3 = M.cols(M.n_cols, M.n_cols + 1); // save to file as explicit doubles, e.i. 123 = 1.23000000000000e+02 M2.save("madelon_columns_0-2.csv", arma::csv_ascii); // can also be binary, hdf5, ... return 0; }
[ "olspaw@gmail.com" ]
olspaw@gmail.com
33cd7c77da1754a7e99a1c9484674fdc1587f803
80b647b0214dd6b2e466581abc7a998a86758bc7
/Maze/pathFinder.cpp
137e908e20aec802ecb9a6203d98f5ca8493d58d
[]
no_license
kilowatthours224/CIS230KH
27cb55ebb8f3ca791c9d6d28ff4640a5fad30dc8
2592f995bb481bc8b807876270e53ce70f89ffc5
refs/heads/main
2023-03-27T03:27:19.979088
2021-04-02T04:37:49
2021-04-02T04:37:49
353,905,035
0
0
null
null
null
null
UTF-8
C++
false
false
6,144
cpp
// pathFinder.cpp: Driver for Assignment 3 - contains pathfinding elements and main #include <iostream> #include <stack> #include "Maze.h" #include "Creature.h" using namespace std; // function prototypes bool goNorth(Maze&, Creature&); bool goSouth(Maze&, Creature&); bool goEast(Maze&, Creature&); bool goWest(Maze&, Creature&); // main function int main() { Maze cornMaze; Creature lassy(cornMaze); cout << "Maze to be completed:\n" << cornMaze << endl; bool try1 = goNorth(cornMaze, lassy); cout << "\nPath:\n" << lassy << endl; return 0; } bool goNorth(Maze &maze, Creature &sparky) { //cout << "Calling goNorth()." << endl; int cPos1 = sparky.getPos1(), cPos2 = sparky.getPos2(); //cout << "I'm trying to access array element " << cPos1 - 1 << " and " << cPos2 << endl; char subject = maze.getSubject(cPos1 - 1, cPos2); bool success = false; if ((subject == Maze::CLEAR) && (maze.boundsCheck(cPos1 - 1, cPos2)) && (subject != Maze::VISITED)) { sparky.move(-1, 0); maze.setPath(sparky.getPos1(), sparky.getPos2()); sparky.setPath(sparky.getPos1(), sparky.getPos2()); if (maze.exitCheck(sparky.getPos1(), sparky.getPos2())) { success = true; } else { success = goNorth(maze, sparky); if (!success) { success = goWest(maze, sparky); if (!success) { success = goEast(maze, sparky); if (!success) { maze.setVisited(cPos1, cPos2); // Setting position as visited sparky.backtrack(sparky.getPos1(), sparky.getPos2()); sparky.move(1, 0); // Backtracking South } } } } } else { success = false; } return success; } bool goWest(Maze &maze, Creature &sparky) { //cout << "Calling goWest()." << endl; int cPos1 = sparky.getPos1(), cPos2 = sparky.getPos2(); //cout << "I'm trying to access array element " << cPos1 << " and " << cPos2 << endl; char subject = maze.getSubject(cPos1, cPos2 - 1); bool success = false; if ((subject == Maze::CLEAR) && (maze.boundsCheck(cPos1, cPos2 - 1)) && (subject != Maze::VISITED)) { sparky.move(0, -1); maze.setPath(sparky.getPos1(), sparky.getPos2()); sparky.setPath(sparky.getPos1(), sparky.getPos2()); if (maze.exitCheck(sparky.getPos1(), sparky.getPos2())) { success = true; } else { success = goWest(maze, sparky); if (!success) { success = goNorth(maze, sparky); if (!success) { success = goSouth(maze, sparky); if (!success) { maze.setVisited(cPos1, cPos2); // Setting position as visited sparky.backtrack(sparky.getPos1(), sparky.getPos2()); sparky.move(0, 1); // Backtracking East } } } } } else { success = false; } return success; } bool goEast(Maze &maze, Creature &sparky) { //cout << "Calling goEast()." << endl; int cPos1 = sparky.getPos1(), cPos2 = sparky.getPos2(); //cout << "I'm trying to access array element " << cPos1 << " and " << cPos2 + 1 << endl; char subject = maze.getSubject(cPos1, cPos2 + 1); bool success = false; if ((subject == Maze::CLEAR) && (maze.boundsCheck(cPos1, cPos2 + 1)) && (subject != Maze::VISITED)) { sparky.move(0, 1); maze.setPath(sparky.getPos1(), sparky.getPos2()); sparky.setPath(sparky.getPos1(), sparky.getPos2()); if (maze.exitCheck(sparky.getPos1(), sparky.getPos2())) { success = true; } else { success = goEast(maze, sparky); if (!success) { success = goNorth(maze, sparky); if (!success) { success = goSouth(maze, sparky); if (!success) { maze.setVisited(cPos1, cPos2); // Setting position as visited sparky.backtrack(sparky.getPos1(), sparky.getPos2()); sparky.move(0, -1); // Backtracking West } } } } } else { success = false; } return success; } bool goSouth(Maze &maze, Creature &sparky) { //cout << "Calling goSouth()." << endl; int cPos1 = sparky.getPos1(), cPos2 = sparky.getPos2(); //cout << "I'm trying to access array element " << cPos1 + 1 << " and " << cPos2 << endl; char subject = maze.getSubject(cPos1 + 1, cPos2); bool success = false; if ((subject == Maze::CLEAR) && (maze.boundsCheck(cPos1, cPos2 + 1)) && (subject != Maze::VISITED)) { sparky.move(1, 0); maze.setPath(sparky.getPos1(), sparky.getPos2()); sparky.setPath(sparky.getPos1(), sparky.getPos2()); if (maze.exitCheck(sparky.getPos1(), sparky.getPos2())) { success = true; } else { success = goSouth(maze, sparky); if (!success) { success = goWest(maze, sparky); if (!success) { success = goEast(maze, sparky);// Setting position as visited if (!success) { maze.setVisited(cPos1, cPos2); // Setting position as visited sparky.backtrack(sparky.getPos1(), sparky.getPos2()); sparky.move(-1, 0); // Backtracking North } } } } } else { success = false; } return success; }
[ "noreply@github.com" ]
kilowatthours224.noreply@github.com
81d55dcc07b65a788c50acb232e6ca71cafe83ae
cc7692c41fbf54e5e843264b3b8b37e06bf468f6
/stepper/stepper.ino
86da9ca36bfbf33214d840ae118976dfe3f6e44e
[]
no_license
jarchuleta/arduino
e5556d60592ab92394f2d11158a26a715f2ea974
d28001fdd0483a7e309daa2ec9562d76e9cf5740
refs/heads/master
2021-01-11T17:54:45.517069
2018-07-21T03:13:00
2018-07-21T03:13:00
79,872,100
0
0
null
null
null
null
UTF-8
C++
false
false
776
ino
/* * Stepper motor with potentiometer rotation * (or other sensors) using 0 analog inputs * Use IDE Stepper.h comes with the Arduino library file * */ #include <Stepper.h> // Here to set the stepper motor rotation is how many steps #define STEPS 100 // attached toSet the step number and pin of the stepper motor Stepper stepper(STEPS, 8, 9, 10, 11); // Define variables used to store historical readings int previous = 0; void setup() { // Set the motor at a speed of 90 steps per minute stepper.setSpeed(90); } void loop() { int val = analogRead(0); // Get sensor readings stepper.step(val - previous);// Move the number of steps for the current readings less historical readings previous = val;// Save historical readings }
[ "james.archuleta@gmail.com" ]
james.archuleta@gmail.com
1017c60a3ab3ade5d65a38dd7d8ed17cb6110bc1
adc5b9f7a45e5de1cd168b7eaee33b50d0740bf7
/pp2/ast_stmt.h
be361e1cbc09bc7a47ff5f1e481b3a16897e9542
[]
no_license
ear7up/ear7upCompilers4620
97dbb9199e3cf77cd8193e75fdff19bc3092d8bd
71222bc08ce4c27a0b6e109b5651c9d43a2a8d6f
refs/heads/master
2016-09-08T19:23:32.187266
2014-12-06T02:46:17
2014-12-06T02:46:17
23,360,385
1
0
null
null
null
null
UTF-8
C++
false
false
3,318
h
/* File: ast_stmt.h * ---------------- * The Stmt class and its subclasses are used to represent * statements in the parse tree. For each statment in the * language (for, if, return, etc.) there is a corresponding * node class for that construct. * * pp2: You will need to add new expression and statement node c * classes for the additional grammar elements (Switch/Postfix) */ #ifndef _H_ast_stmt #define _H_ast_stmt #include "list.h" #include "ast.h" class Decl; class VarDecl; class Expr; class IntConstant; class Program : public Node { protected: List<Decl*> *decls; public: Program(List<Decl*> *declList); const char *GetPrintNameForNode() { return "Program"; } void PrintChildren(int indentLevel); }; class Stmt : public Node { public: Stmt() : Node() {} Stmt(yyltype loc) : Node(loc) {} }; class StmtBlock : public Stmt { protected: List<VarDecl*> *decls; List<Stmt*> *stmts; public: StmtBlock(List<VarDecl*> *variableDeclarations, List<Stmt*> *statements); const char *GetPrintNameForNode() { return "StmtBlock"; } void PrintChildren(int indentLevel); }; class ConditionalStmt : public Stmt { protected: Expr *test; Stmt *body; public: ConditionalStmt(Expr *testExpr, Stmt *body); }; class LoopStmt : public ConditionalStmt { public: LoopStmt(Expr *testExpr, Stmt *body) : ConditionalStmt(testExpr, body) {} }; class ForStmt : public LoopStmt { protected: Expr *init, *step; public: ForStmt(Expr *init, Expr *test, Expr *step, Stmt *body); const char *GetPrintNameForNode() { return "ForStmt"; } void PrintChildren(int indentLevel); }; class WhileStmt : public LoopStmt { public: WhileStmt(Expr *test, Stmt *body) : LoopStmt(test, body) {} const char *GetPrintNameForNode() { return "WhileStmt"; } void PrintChildren(int indentLevel); }; class IfStmt : public ConditionalStmt { protected: Stmt *elseBody; public: IfStmt(Expr *test, Stmt *thenBody, Stmt *elseBody); const char *GetPrintNameForNode() { return "IfStmt"; } void PrintChildren(int indentLevel); }; class BreakStmt : public Stmt { public: BreakStmt(yyltype loc) : Stmt(loc) {} const char *GetPrintNameForNode() { return "BreakStmt"; } }; class ReturnStmt : public Stmt { protected: Expr *expr; public: ReturnStmt(yyltype loc, Expr *expr); const char *GetPrintNameForNode() { return "ReturnStmt"; } void PrintChildren(int indentLevel); }; class PrintStmt : public Stmt { protected: List<Expr*> *args; public: PrintStmt(List<Expr*> *arguments); const char *GetPrintNameForNode() { return "PrintStmt"; } void PrintChildren(int indentLevel); }; class SwitchStmt : public Stmt { protected: Expr *expr; List<Stmt*> *cases; public: SwitchStmt(Expr *expr, List<Stmt*> *cases); const char *GetPrintNameForNode() { return "SwitchStmt"; } void PrintChildren(int indentLevel); }; class Case : public Stmt { protected: IntConstant *label; List<Stmt*> *stmts; public: Case(IntConstant *label, List<Stmt*> *stmts); const char *GetPrintNameForNode(); void PrintChildren(int indentLevel); }; #endif
[ "ear7up@virginia.edu" ]
ear7up@virginia.edu
3c2c5d52c9c61f9f44b4258735991fa559dd69c3
e0b758271f45545629a10bf875ca6c3866ce01a6
/Library/Others/Time.cpp
18062589951f166e22cf06187f1bb05330697d51
[]
no_license
tonko2/C_plus_plus
10af20d2fe1fa575d515028eb37d6a721e3fb86a
d9e8de7bcf106e73e8d13122d10135c450e6b9e1
refs/heads/master
2020-05-20T08:43:05.842398
2015-12-21T06:17:46
2015-12-21T06:17:46
19,302,041
1
2
null
2015-12-21T06:15:51
2014-04-30T05:38:43
C++
UTF-8
C++
false
false
362
cpp
#include <bits/stdc++.h> using namespace std; #define debug(x) cout << #x << " = " << x << endl const int INF = 1<<29; typedef long long ll; typedef pair<int,int> P; int main(){ int N; cin >> N; int hh = N / 3600; int mm = (N % 3600) / 60; int ss = N % 60; //1秒なら01と、出力 printf("%02d:%02d:%02d\n",hh,mm,ss); return 0; }
[ "10cherry07@gmail.com" ]
10cherry07@gmail.com
56978e72357fbb683209a8a0d2e46ca2d8c56463
c5a20ed507089e7e72531757e98c3a3b371d4f7a
/service/unittest_service_helper.cc
78214eb8385c1ec98d03ecbbf0173a67d887e001
[]
no_license
pinghaoluo/499-zhihanz-usc-edu
39f1437595ce5d9cb7c93179f5fca17af7ebf316
198961100dba08547fff696eb680a1e39b05b70f
refs/heads/master
2020-04-25T12:17:06.767409
2019-02-15T07:41:37
2019-02-15T07:41:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,060
cc
#include "service_helper.h" #include <chrono> #include <gtest/gtest.h> #include <iostream> #include <string> #include <thread> #include <vector> using namespace parser; // test whether parser and deparser can be used to the empty string and empty // vector TEST(test, init) { std::string str{}; std::vector<string> vec{}; auto str1 = Parser(vec); ASSERT_EQ("", str1); auto vec1 = Deparser(str1); ASSERT_EQ(vec, vec1); } // test a simple case of vector to string and convert back to see whether they // are equal TEST(test, add) { std::string add1("n12hd1oiuh!!"); std::vector<string> vec{"test1^*(())", "test2h1ue91**~~~!!!", "HJVYUFOIUAMOIQ*!&((*&)Y*)"}; auto str1 = Parser(vec); auto vec1 = Deparser(str1); ASSERT_EQ(vec, vec1); } using namespace helper; using namespace std; IdGenerator idG; // parse username, text, pair , pid into a chirp string and convert it back to // see whether it can be converted successfully TEST(test, chirpInit) { auto username = "Adam"; auto text = "Hello World"; auto pair = idG(); auto pid = "-1"; auto str = chirpInit(username, text, pair.second, pid, pair.first); Chirp chirp; chirp.ParseFromString(str); ASSERT_EQ(username, chirp.username()); ASSERT_EQ(text, chirp.text()); ASSERT_EQ(pid, chirp.parent_id()); ASSERT_EQ(pair.second, chirp.id()); Chirp *chirp2 = StringToChirp(str); ASSERT_EQ(chirp2->username(), chirp.username()); ASSERT_EQ(chirp2->text(), chirp.text()); ASSERT_EQ(chirp2->parent_id(), chirp.parent_id()); ASSERT_EQ(chirp2->id(), chirp.id()); } // test some cases on whether idG functor can generate diffrent ids TEST(test, ID_GEN) { auto pair = idG(); cout << pair.second << endl; auto pair4 = idG(); cout << pair4.second << endl; auto pair3 = idG(); cout << pair3.second << endl; auto pair2 = idG(); cout << pair2.second << endl; } // This test is not relevent to the development and should be deleted int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "vagrant@vagrant.vm" ]
vagrant@vagrant.vm
1faac8a288675fe794e94140c64399e321742993
69daee30ea7cca07ac446c6986e44fe24bc9a34a
/多维数组.cpp
8ae9cdc5429fbcbf3b0ef8ef40e113b5f9df716a
[]
no_license
lml08/OJ
38b904ff7482b4cad827148d9538682d8997bfed
26ae3f28ffceea648d9206039031b432bb64ccec
refs/heads/master
2020-04-28T00:16:26.051417
2019-03-10T10:43:33
2019-03-10T10:43:33
174,809,240
0
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
#include<stdio.h> void search(float (*p)[4],int n) { int i,j,flag; for(j=0;j<n;j++) { flag=0; for(i=0;i<4;i++) if(*(*(p+j)+i)<60) flag=1; if(flag==1) { for(i=0;i<4;i++) printf("%.f ",*(*(p+j)+i)); printf("\n"); } } } int main() { float score[3][4]={{65,57,70,60},{58,87,90,81},{90,99,100,98}}; search(score,3); }
[ "353392619@qq.com" ]
353392619@qq.com
40c89d1acf8d53f322d3dd33a2ccd589ac16c4ca
577538f4e21dc5d16ba9cd2b3a1bacf21b234864
/Numerical/MullerRoots/main.cpp
062c3e11347cc99abc5f972a646fc9154e1cbdd0
[]
no_license
proctorsdp/mechanicalEngineering
91b6d14b2887833553fd879e3b55fd744b3e8212
69289b0b70aedfe05c7b8798d91b51c1d426bdfd
refs/heads/master
2021-08-23T19:06:36.475038
2017-12-06T04:36:08
2017-12-06T04:36:08
108,763,774
0
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
#include <iostream> #include "muller.h" using namespace std; int main() { muller m; char again; m.mullerSolver(); cout << "Would you like to find another root of the equation?\n" "'y' or 'n'?\n"; cin >> again; if (again == 'y') { main(); } return 0; }
[ "proctorsdp@users.noreply.github.com" ]
proctorsdp@users.noreply.github.com
29961e2a8a4144ba30577021c052e561223d539f
18fe661d6b2b85d1ef56dfd84054b18687e86a71
/Software/Signalgenerator/GUI/table.hpp
cd5349a39b2a440cd709577e1a308d608d9c1640
[]
no_license
jankae/Signalgenerator
48759b95d6f9139b900aee281b43f6e73dd67691
d6a2e1b0d0a1e50f169ecdedde816751158b143e
refs/heads/master
2023-02-02T11:04:07.942520
2023-02-01T13:38:07
2023-02-01T13:38:07
189,094,174
23
12
null
null
null
null
UTF-8
C++
false
false
7,480
hpp
#pragma once #include "widget.hpp" #include "Unit.hpp" #include "display.h" #include "font.h" #include "buttons.h" #include "Dialog/ValueInput.hpp" template<typename T> class Table : public Widget { public: Table(font_t font, uint8_t visibleLines) { columns = nullptr; rows = 0; cols = 0; size.x = 2 + ScrollbarSize; size.y = (font.height + PaddingRows) * (visibleLines + 1) + PaddingRows; this->font = font; selected_row = 0; selected_column = 0; lines = visibleLines; topVisibleEntry = 0; } ~Table() { while (columns) { Column *next = columns->next; delete columns; columns = next; } } bool AddColumn(const char *name, T *data, uint8_t len, const Unit::unit *u[], uint8_t digits, bool editable) { if (rows > 0) { if (len != rows) { // other length than already added column, aborting return false; } } auto *column = new Column; // copy members strncpy(column->name, name, MaxNameLength); column->name[MaxNameLength - 1] = 0; column->unit = u; column->digits = digits; column->editable = editable; column->data = data; column->next = nullptr; if (digits > strlen(name)) { column->sizex = font.width * digits + PaddingColumns; } else { column->sizex = font.width * strlen(name) + PaddingColumns; } // add to end of linked list if (!columns) { columns = column; rows = len; } else { auto it = columns; while (it->next) { it = it->next; } it->next = column; } // update overall table size size.x += column->sizex; cols++; return true; } private: static constexpr uint8_t MaxNameLength = 10; static constexpr uint8_t PaddingRows = 2; static constexpr uint8_t PaddingColumns = 2; static constexpr uint8_t ScrollbarSize = 20; static constexpr color_t ScrollbarColor = COLOR_ORANGE; Widget::Type getType() override { return Widget::Type::Table; }; void draw(coords_t offset) override { display_SetForeground(COLOR_BLACK); display_SetBackground(COLOR_WHITE); display_HorizontalLine(offset.x, offset.y, size.x); display_VerticalLine(offset.x, offset.y, size.y); // draw columns uint16_t offsetX = 1; Column *c = columns; uint8_t column_cnt = 0; while (c) { uint16_t offsetY = 1; // draw name display_AutoCenterString(c->name, COORDS(offset.x + offsetX, offset.y + offsetY), COORDS(offset.x + offsetX + c->sizex, offset.y + offsetY + font.height + 1)); offsetY += font.height + PaddingRows; display_HorizontalLine(offset.x + offsetX, offset.y + offsetY, c->sizex); for (uint8_t i = 0; i < lines; i++) { char val[c->digits + 1]; if (i + topVisibleEntry < rows) { Unit::StringFromValue(val, c->digits, c->data[i + topVisibleEntry], c->unit); } else { memset(val, ' ', c->digits); val[c->digits] = 0; } if (!c->editable) { display_SetForeground(COLOR_GRAY); } else if (selected) { if (i + topVisibleEntry == selected_row && column_cnt == selected_column) { display_SetForeground(COLOR_SELECTED); } } display_String(offset.x + offsetX + 1, offset.y + offsetY + 2, val); display_SetForeground(COLOR_BLACK); offsetY += font.height + PaddingRows; display_HorizontalLine(offset.x + offsetX, offset.y + offsetY, c->sizex); } offsetX += c->sizex; display_VerticalLine(offset.x + offsetX, offset.y, size.y); c = c->next; column_cnt++; } // draw scrollbar display_Rectangle(offset.x + offsetX, offset.y, offset.x + offsetX + ScrollbarSize, offset.y + size.y - 1); /* calculate beginning and end of scrollbar */ uint8_t scrollBegin = common_Map(topVisibleEntry, 0, rows, 0, size.y); uint8_t scrollEnd = size.y; if (rows > lines) { scrollEnd = common_Map(topVisibleEntry + lines, 0, rows, 0, size.y); } /* display position indicator */ display_SetForeground(COLOR_BG_DEFAULT); display_RectangleFull(offset.x + offsetX + 1, offset.y + 1, offset.x + offsetX + ScrollbarSize - 1, offset.y + scrollBegin); display_RectangleFull(offset.x + offsetX + 1, offset.y + scrollEnd - 1, offset.x + offsetX + ScrollbarSize - 1, offset.y + size.y - 2); display_SetForeground(ScrollbarColor); display_RectangleFull(offset.x + offsetX + 1, offset.y + scrollBegin + 1, offset.x + offsetX + ScrollbarSize - 1, offset.y + scrollEnd - 2); } void changeValue() { uint8_t column = 0; Column *c = columns; while (c) { if (column == selected_column) { if (!c->editable) { // this column is not changeable return; } new ValueInput<T>("New cell value:", &c->data[selected_row], c->unit, nullptr, nullptr); } column++; c = c->next; } } void input(GUIEvent_t *ev) override { if (!selectable) { return; } switch(ev->type) { case EVENT_TOUCH_PRESSED: { uint8_t new_row = ev->pos.y / (font.height + PaddingRows); if (new_row >= rows) { new_row = rows - 1; } else if (new_row > 0) { // remove offset caused by column name new_row--; } new_row += topVisibleEntry; uint8_t new_column = 0; Column *c = columns; uint16_t x_cnt = 0; while (c) { x_cnt += c->sizex; if (x_cnt >= ev->pos.x) { break; } new_column++; } if (new_row != selected_row || new_column != selected_column) { selected_row = new_row; selected_column = new_column; requestRedraw(); } else { // same cell was already selected changeValue(); } } ev->type = EVENT_NONE; break; case EVENT_BUTTON_CLICKED: if ((ev->button & BUTTON_LEFT) && selected_column > 0) { selected_column--; requestRedraw(); } if ((ev->button & BUTTON_UP) && selected_row > 0) { selected_row--; if (selected_row < topVisibleEntry) { topVisibleEntry = selected_row; } requestRedraw(); } if ((ev->button & BUTTON_DOWN) && selected_row < rows - 1) { selected_row++; if (selected_row >= lines) { topVisibleEntry = selected_row - lines + 1; } requestRedraw(); } if ((ev->button & BUTTON_RIGHT) && selected_column < cols - 1) { selected_column++; requestRedraw(); } if ((ev->button & BUTTON_ENCODER)) { changeValue(); } ev->type = EVENT_NONE; break; case EVENT_ENCODER_MOVED: if (ev->movement > 0) { if (selected_row < rows - 1) { selected_row++; if (selected_row >= lines) { topVisibleEntry = selected_row - lines + 1; } } else { selected_row = 0; topVisibleEntry = 0; if (selected_column < cols - 1) { selected_column++; } else { selected_column = 0; } } } else { if (selected_row > 0) { selected_row--; if (selected_row < topVisibleEntry) { topVisibleEntry = selected_row; } } else { selected_row = rows - 1; if (selected_row >= lines) { topVisibleEntry = selected_row - lines + 1; } if (selected_column > 0) { selected_column--; } else { selected_column = cols - 1; } } } requestRedraw(); ev->type = EVENT_NONE; break; default: break; } return; } using Column = struct column { char name[MaxNameLength]; const Unit::unit **unit; uint8_t digits; bool editable; uint16_t sizex; T *data; column *next; }; font_t font; Column *columns; uint8_t rows; uint8_t cols; uint8_t selected_row; uint8_t selected_column; uint8_t lines; uint8_t topVisibleEntry; };
[ "kaeberic@ibr.cs.tu-bs.de" ]
kaeberic@ibr.cs.tu-bs.de
3ccd67ce76630c0e91836a695e5f0d83d8aaf47f
6229725d6d8ee994537b4be33d8fd20f8dbaf2c9
/camera/src/board_cutout.cpp
7dcb6a82f6c9105651ead31cd888d7c6b19f7c93
[]
no_license
HKbaxterteam/Baxter2017
ec2121c9490397215046b1d66d523e96078a8910
9cc3d79d2462fa7637b0aefed469c9c4b984f6fd
refs/heads/master
2021-01-01T18:43:57.366296
2017-09-19T15:10:13
2017-09-19T15:10:13
98,415,486
0
0
null
null
null
null
UTF-8
C++
false
false
3,667
cpp
//************************************************ //**********Baxter 2017 Tic-Tac-Toe*************** //*******Nadine Drollinger & Michael Welle******** //************************************************ //*******Camera node - board_cutout************* //************************************************ //************************************************ // Description: cuts out the board in a rough //fashion to make it easier finding the game board contour //************************************************ //ros #include <ros/ros.h> #include <ros/console.h> //opencv #include <cv_bridge/cv_bridge.h> #include <image_transport/image_transport.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include "opencv2/opencv.hpp" //namespace using namespace cv; using namespace std; //class board_cutout class board_cutout { protected: ros::NodeHandle n_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_raw_; image_transport::Publisher image_pub_cut_; public: //vars for cutting out board double cutout_x; //start cut out point x double cutout_y; //start cut out point y double cutout_width; //start cut out point width double cutout_height; //start cut out point height //debug bool debug_flag; //Open cv images Mat org, grey, game; Mat M, rotated, cropped; //constructor board_cutout() : it_(n_),debug_flag(false),cutout_x(70),cutout_y(110),cutout_width(550),cutout_height(370) { // Subscriber and publisher image_sub_raw_ = it_.subscribe("/TTTgame/webcam/input_image_raw", 1, &board_cutout::imageCb, this); image_pub_cut_ = it_.advertise("/TTTgame/cut_board", 1); //debug if(debug_flag){ namedWindow("Input", CV_WINDOW_AUTOSIZE); namedWindow("Cut output",CV_WINDOW_AUTOSIZE); } } //deconstructor ~board_cutout() { if(debug_flag){ destroyWindow("Input"); destroyWindow("Cut output"); } } //callback function for raw webcam input image void imageCb(const sensor_msgs::ImageConstPtr& msg) { //read in image from subscribed topic and transform it to opencv cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // process the image org = cv_ptr->image; //debug output if(debug_flag){ waitKey(1); imshow("Input", org); //show the frame in "MyVideo" window waitKey(1); } // we cut out a smaller portion of the image Rect Rec(cutout_x, cutout_y, cutout_width, cutout_height); Mat cutorg = org(Rec).clone(); //publish the image in ros cv_bridge::CvImage out_msg; out_msg.header = cv_ptr->header; // Same timestamp and tf frame as input image out_msg.header.stamp =ros::Time::now(); // new timestamp out_msg.encoding = sensor_msgs::image_encodings::BGR8; // encoding, might need to try some diffrent ones out_msg.image = cutorg; image_pub_cut_.publish(out_msg.toImageMsg()); //transfer to ros image message //debug output if(debug_flag){ waitKey(1); imshow("Cut output", cutorg); //show the frame in "MyVideo" window waitKey(1); } } }; //Main int main(int argc, char** argv) { ros::init(argc, argv, "board_cut_out"); board_cutout bc; ROS_INFO("board cutout initilized"); ros::spin(); return 0; }
[ "mwelle@kth.se" ]
mwelle@kth.se
f64e42113ef954adb38de282f5018f2b27352e7a
83173c35a77d0c863b67f485ad09070986657ca8
/src/inter/expression.cpp
1b2286963956bb0d306abb6fa7924c22642543d0
[]
no_license
vin120/cpp-dragonbook-frontend
1310601fc709df349bff7e791ee00010e1493741
d5b9559f849a714de9b098f48eeafdcde0c0b7b3
refs/heads/master
2020-07-04T15:24:20.602786
2014-01-13T20:12:23
2014-01-13T20:12:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
598
cpp
#include <inter/expression.hpp> #include <sstream> namespace inter { void Expression::emit_jumps(const std::string &test, const std::uint32_t &to, const std::uint32_t &from) { std::stringstream ss; if (to && from) { ss << "if " << test << " goto L" << to; emit(ss.str()); ss.str(""); ss << "goto L" << from; emit(ss.str()); } else if (to) { ss << "if " << test << " goto L" << to; emit(ss.str()); } else if (from) { ss << "iffalse " << test << " goto L" << from; emit(ss.str()); } } } // namespace inter
[ "alexander.rojas@gmail.com" ]
alexander.rojas@gmail.com
5d4f76199fabdc765c9fc78de5734d72570c1632
eb597f5e43cc56b1e3141376da31640b757baf93
/src/fem_core/solvers/CSLR/preconditioners/Nothing/preconditioner_Nothing.h
e8fde164c306946ffd9804a8c93cbc36f88a096e
[]
no_license
AlienCowEatCake/vfem
27cee7980eb37937a7bdaec66338f20860686280
4fe0b260c12be6ffe51d699d2a3076a35c7c2ece
refs/heads/master
2023-02-15T19:35:48.320360
2017-02-03T19:46:47
2017-02-04T09:17:49
327,827,936
0
0
null
null
null
null
UTF-8
C++
false
false
4,643
h
#if !defined(SOLVERS_CSLR_PRECONDITIONERS_NOTHING_H_INCLUDED) #define SOLVERS_CSLR_PRECONDITIONERS_NOTHING_H_INCLUDED #include "../preconditioner_interface.h" namespace fem_core { namespace solvers { namespace CSLR { namespace preconditioners { /** * @brief Класс базовый (пустой) предобуславливатель A = S * Q */ template<typename val_type, typename ind_type = std::size_t> class preconditioner_Nothing : public preconditioner_interface<val_type, ind_type> { public: /** * @brief Конструктор для несимметричного предобуславливателя * @param[in] gi Массив ig в разряженном строчно-столбцовом представлении * @param[in] gj Массив jg в разряженном строчно-столбцовом представлении * @param[in] di Массив диагональных эл-тов в разряженном строчно-столбцовом представлении * @param[in] gl Массив нижнего треугольника в разряженном строчно-столбцовом представлении * @param[in] gu Массив верхнего треугольника в разряженном строчно-столбцовом представлении * @param[in] n Размерность матрицы */ preconditioner_Nothing(const ind_type * gi, const ind_type * gj, const val_type * di, const val_type * gl, const val_type * gu, ind_type n) : m_gi(gi), m_gj(gj), m_di(di), m_gl(gl), m_gu(gu), m_n(n), m_is_symmetric(false) {} /** * @brief Конструктор для симметричного предобуславливателя * @param[in] gi Массив ig в разряженном строчно-столбцовом представлении * @param[in] gj Массив jg в разряженном строчно-столбцовом представлении * @param[in] di Массив диагональных эл-тов в разряженном строчно-столбцовом представлении * @param[in] gg Массив нижнего и верхнего треугольника в разряженном строчно-столбцовом представлении * @param[in] n Размерность матрицы */ preconditioner_Nothing(const ind_type * gi, const ind_type * gj, const val_type * di, const val_type * gg, ind_type n) : m_gi(gi), m_gj(gj), m_di(di), m_gl(gg), m_gu(gg), m_n(n), m_is_symmetric(true) {} /** * @brief Узнать название предобуславливателя * @return Название предобуславливателя */ virtual std::string get_name() const { return "Nothing"; } /** * @brief Решает СЛАУ вида x = S^-1 * f * @param[in] f * @param[out] x */ virtual void solve_S(const val_type * f, val_type * x) const { for(ind_type k = 0; k < m_n; k++) x[k] = f[k]; } /** * @brief Решает СЛАУ вида x = S^-T * f * @param[in] f * @param[out] x */ virtual void solve_ST(const val_type * f, val_type * x) const { for(ind_type k = 0; k < m_n; k++) x[k] = f[k]; } /** * @brief Решает СЛАУ вида x = Q^-1 * f * @param[in] f * @param[out] x */ virtual void solve_Q(const val_type * f, val_type * x) const { for(ind_type k = 0; k < m_n; k++) x[k] = f[k]; } /** * @brief Решает СЛАУ вида x = Q^-T * f * @param[in] f * @param[out] x */ virtual void solve_QT(const val_type * f, val_type * x) const { for(ind_type k = 0; k < m_n; k++) x[k] = f[k]; } /** * @brief Вычисляет x = Q * f * @param[in] f * @param[out] x */ virtual void mul_Q(const val_type * f, val_type * x) const { for(ind_type k = 0; k < m_n; k++) x[k] = f[k]; } /** * @brief Виртуальный деструктор */ virtual ~preconditioner_Nothing() {} protected: const ind_type * m_gi, * m_gj; const val_type * m_di, * m_gl, * m_gu; ind_type m_n; bool m_is_symmetric; }; }}}} // namespace fem_core::solvers::CSLR::preconditioners #endif // SOLVERS_CSLR_PRECONDITIONERS_NOTHING_H_INCLUDED
[ "peter.zhigalov@gmail.com" ]
peter.zhigalov@gmail.com
ff610cfbe48165e84b2fbbd119b625cce2502735
9247cc17fbcf5ce96960e1b180d463339f45378d
/.LHP/.Lop11/.T.Minh/BoGhepSomNhat/BoGhepSomNhat/BoGhepSomNhat.cpp
4e8d3cda4a2e89482b51db27041293f63a46837c
[ "MIT" ]
permissive
sxweetlollipop2912/MaCode
dbc63da9400e729ce1fb8fdabe18508047d810ef
b8da22d6d9dc4bf82ca016896bf64497ac95febc
refs/heads/master
2022-07-28T03:42:14.703506
2021-12-16T15:44:04
2021-12-16T15:44:04
294,735,840
0
0
null
null
null
null
UTF-8
C++
false
false
1,330
cpp
#include <iostream> #include <cstdio> #include <algorithm> #define maxN 501 #define INF 999999999999999999 typedef int maxn; typedef long long maxa; maxa w[maxN][maxN], MIN, MAX; maxn mch[maxN], n; bool g[maxN][maxN], seen[maxN]; void Prepare() { std::cin >> n; MIN = INF, MAX = -INF; for (maxn i = 0; i < n; i++) for (maxn j = 0; j < n; j++) std::cin >> w[j][i], MIN = std::min(MIN, w[j][i]), MAX = std::max(MAX, w[j][i]); } bool DFS(maxn u) { for (maxn v = 0; v < n; v++) if (g[u][v] && !seen[v]) { seen[v] = 1; if (mch[v] < 0 || DFS(mch[v])) return mch[v] = u, 1; } return 0; } maxn maxBPM() { std::fill(mch, mch + n, -1); maxn res = 0; for (maxn u = 0; u < n; u++) { std::fill(seen, seen + n, 0); if (DFS(u)) ++res; } return res; } void Init(const maxa x) { for (maxn i = 0; i < n; i++) for (maxn j = 0; j < n; j++) g[i][j] = w[i][j] <= x; } void Process() { while (MIN != MAX) { maxa MID = (MIN + MAX) / 2; Init(MID); if (maxBPM() == n) MAX = MID; else MIN = MID + 1; } Init(MIN); maxBPM(); std::cout << MIN << '\n'; for (maxn i = 0; i < n; i++) std::cout << mch[i] + 1 << ' '; } int main() { //freopen("COUPEARL.inp", "r", stdin); //freopen("COUPEARL.out", "w", stdout); std::ios_base::sync_with_stdio(0); std::cin.tie(0); Prepare(); Process(); }
[ "thaolygoat@gmail.com" ]
thaolygoat@gmail.com
15b1396a71649c03c49c54b62139ee1e251d2060
1d9e60a377ce2b0b94234e90c3156f212f2a7e9b
/3/monijijian/qddown_vc/XXX.cpp
5d490e9f34ae44bdaa7731f0f9517dec45c5c5eb
[]
no_license
seehunter/visual_c-_reff_skill_code
fd13ceec2c34bd827f2556638bbc190be46d9b93
1a99bd875c32a04cbcc07c785b61270821c58341
refs/heads/master
2020-04-09T21:28:33.030596
2018-12-06T01:59:25
2018-12-06T01:59:25
160,603,401
0
0
null
null
null
null
UTF-8
C++
false
false
1,947
cpp
// XXX.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "XXX.h" #include "XXXDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CXXXApp BEGIN_MESSAGE_MAP(CXXXApp, CWinApp) //{{AFX_MSG_MAP(CXXXApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CXXXApp construction CXXXApp::CXXXApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CXXXApp object CXXXApp theApp; ///////////////////////////////////////////////////////////////////////////// // CXXXApp initialization BOOL CXXXApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif CXXXDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
[ "seehunter@163.com" ]
seehunter@163.com
e07e69330e7e4031f581a18cd460b0b951fbc826
d64f8212a7276c7e3fe9e56c1c64c6434c6fab53
/CSD1404(待补充)/c++(CSD1404,GAJ)/day09/01vtable.cpp
adf7496ec1ec8133f87b257d8c33a646b2981272
[]
no_license
kanglanglang/danei
16021cc91a137961f6affbfdd6fa46f6813fd8f0
a56ac9856546128dcc94b664193a6cc425619e6a
refs/heads/master
2023-03-19T03:00:13.214959
2016-07-23T14:39:59
2016-07-23T14:39:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
432
cpp
#include <iostream> using namespace std; class A{ public: virtual void fooa(int x){ cout << "fooa(int)" << endl; cout << x << endl; } virtual void foob(int x){ cout << "foob(int)" << endl; cout << x << endl; } }; typedef void (*VFUN)(A* mythis,int x); typedef VFUN* VTABLE; int main(){ A a; VTABLE vt=*((VTABLE*)&a); vt[0](&a,123); vt[1](&a,456); // vt[2](&a,456); }
[ "1019364135@qq.com" ]
1019364135@qq.com
2459dde7a1299250f3ec3b461782c11949d6acc5
10c52dc3619fb60299dccd7851f1ab586030aebf
/OSSIM_DEV_HOME/ossim_plugins/opencv/openCVtestclass.h
9ee939066255fb1c5589f469271caa61ccebb37f
[]
no_license
whigg/OSSIM-GSoC-2014_draft
8b84ee23e4bf1953c160e44cd0ca4b27e63bbf54
d2e86f859df63b10126fe1ba9d5d8aa30490db45
refs/heads/master
2020-09-02T05:24:23.337701
2014-08-08T18:47:15
2014-08-08T18:47:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
594
h
#include <ossim/base/ossimObject.h> #include <ossim/base/ossimDpt.h> #include <ossim/base/ossimString.h> #include <ossim/base/ossimTieMeasurementGeneratorInterface.h> #include "ossimIvtGeomXform.h" #include <opencv/cv.h> #include <ctime> #include <vector> #include <iostream> class openCVtestclass { public: openCVtestclass(); openCVtestclass(ossimRefPtr<ossimImageData> master, ossimRefPtr<ossimImageData> slave); bool execute(); cv::Mat master_mat, slave_mat; cv::vector<cv::KeyPoint> keypoints1, keypoints2; vector<cv::DMatch > good_matches; };
[ "martina@Martina-Ubuntu.(none)" ]
martina@Martina-Ubuntu.(none)
9edf550c089aed3f3a72db717d588fbb92b27aa1
afdb4de6d6db332b410dcacb23daf54f86cec7d6
/playground_learn_color/playground_learn_color.ino
30144a071e0630fd5195fed0078b1a73ecf48858
[]
no_license
andereyes99/ArduinoStuff
9bafae696d8a7074e2eddf63bd52a99de34e8918
d0507415e823831fcccf768f643bf00efa8ef3ee
refs/heads/master
2021-05-12T16:06:20.972459
2017-12-26T19:09:16
2017-12-26T19:09:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,513
ino
/*Tomas de Camino Beck www.funcostarica.org Learning colors Released under MIT License Copyright (c) 2016 Tomas de-Camino-Beck */ #include "Perceptron.h" #include <Wire.h> #include <Adafruit_CircuitPlayground.h> //we will use one perceptron with 3 inputs (Red, green, blue) perceptron colorPerceptron(4);//fourth is for bias void setup() { randomSeed(CircuitPlayground.readCap(3)); colorPerceptron.randomize();//weight initialization CircuitPlayground.begin(); CircuitPlayground.clearPixels(); Serial.begin(9600); } void loop() { //Read color if (CircuitPlayground.lightSensor() <10) { CircuitPlayground.clearPixels(); uint8_t red, green, blue; CircuitPlayground.senseColor(red, green, blue); /*** store in perceptron inputs ***/ colorPerceptron.inputs[0] = red; colorPerceptron.inputs[1] = green; colorPerceptron.inputs[2] = blue; } //make a guess float guess = colorPerceptron.feedForward(); //press button if guess incorrect if (CircuitPlayground.rightButton()) { CircuitPlayground.clearPixels(); colorPerceptron.train(-guess, guess); delay(1000); } //change color uint32_t c; if (guess == 1) { c = CircuitPlayground.strip.Color(0, 255, 0); Serial.println("Match"); } else { c = CircuitPlayground.strip.Color(255, 0, 0); Serial.println("No Match"); } //update pixels for (int i = 3; i <= 9; i++) { CircuitPlayground.setPixelColor(i, c); } // CircuitPlayground.clearPixels(); }
[ "tomas.decamino@gmail.com" ]
tomas.decamino@gmail.com
6e1debfeeb877e308a0a354500361340046fb779
c6f08f2bb8b812bcb63a6216fbd674e1ebdf00d8
/ni_header/NiTriBasedGeom.inl
8e84a2566c10d4edc94fa30475ff94e83d40b522
[]
no_license
yuexiae/ns
b45e2e97524bd3d5d54e8a79e6796475b13bd3f9
ffeb846c0204981cf9ae8033a83b2aca2f8cc3ac
refs/heads/master
2021-01-19T19:11:39.353269
2016-06-08T05:56:35
2016-06-08T05:56:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,761
inl
// NUMERICAL DESIGN LIMITED PROPRIETARY INFORMATION // // This software is supplied under the terms of a license agreement or // nondisclosure agreement with Numerical Design Limited and may not // be copied or disclosed except in accordance with the terms of that // agreement. // // Copyright (c) 1996-2004 Numerical Design Limited. // All Rights Reserved. // // Numerical Design Limited, Chapel Hill, North Carolina 27514 // http://www.ndl.com //--------------------------------------------------------------------------- // NiTriBasedGeom inline functions //--------------------------------------------------------------------------- inline unsigned short NiTriBasedGeom::GetTriangleCount() const { NiTriBasedGeomData* pkData = NiSmartPointerCast(NiTriBasedGeomData, m_spModelData); return pkData->GetTriangleCount(); } //--------------------------------------------------------------------------- inline void NiTriBasedGeom::SetActiveTriangleCount(unsigned short usActive) { ((NiTriBasedGeomData*) GetModelData())-> SetActiveTriangleCount(usActive); } //--------------------------------------------------------------------------- inline unsigned short NiTriBasedGeom::GetActiveTriangleCount() const { return ((NiTriBasedGeomData*) GetModelData())-> GetActiveTriangleCount(); } //--------------------------------------------------------------------------- inline void NiTriBasedGeom::GetTriangleIndices(unsigned short i, unsigned short& i0, unsigned short& i1, unsigned short& i2) const { ((NiTriBasedGeomData*) GetModelData())-> GetTriangleIndices(i, i0, i1, i2); } //---------------------------------------------------------------------------
[ "ioio@ioio-nb.lan" ]
ioio@ioio-nb.lan
c9323a6f842b351f07589957d79cd4613dde44fa
346c17a1b3feba55e3c8a0513ae97a4282399c05
/applis/uti_image/OLD-CmpIm.cpp
2cc93441fedf43002c286258899e031b58386f23
[ "LicenseRef-scancode-cecill-b-en" ]
permissive
micmacIGN/micmac
af4ab545c3e1d9c04b4c83ac7e926a3ff7707df6
6e5721ddc65cb9b480e53b5914e2e2391d5ae722
refs/heads/master
2023-09-01T15:06:30.805394
2023-07-25T09:18:43
2023-08-30T11:35:30
74,707,998
603
156
NOASSERTION
2023-06-19T12:53:13
2016-11-24T22:09:54
C++
UTF-8
C++
false
false
5,377
cpp
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #include "general/all.h" #include "private/all.h" #include <algorithm> int main(int argc,char ** argv) { std::string aName1; std::string aName2; std::string aFileDiff=""; double aDyn=1.0; Pt2di aBrd(0,0); ElInitArgMain ( argc,argv, LArgMain() << EAM(aName1) << EAM(aName2) , LArgMain() << EAM(aFileDiff,"FileDiff",true) << EAM(aDyn,"Dyn",true) << EAM(aBrd,"Brd",true) ); Tiff_Im aFile1 = Tiff_Im::BasicConvStd(aName1); Tiff_Im aFile2 = Tiff_Im::BasicConvStd(aName2); if (aFile1.sz() != aFile2.sz()) { std::cout << "Tailles Differentes " << aFile1.sz() << aFile2.sz() << "\n"; return -1; } Symb_FNum aFDif(Rconv(Abs(aFile1.in()-aFile2.in()))); double aNbDif,aSomDif,aMaxDif,aSom1; int aPtDifMax[2]; ELISE_COPY ( //aFile1.all_pts(), rectangle(aBrd,aFile1.sz()-aBrd), Virgule ( Rconv(aFDif), aFDif!=0, 1.0 ), Virgule ( sigma(aSomDif) | VMax(aMaxDif) | WhichMax(aPtDifMax,2), sigma(aNbDif), sigma(aSom1) ) ); if (aNbDif) { if (aFileDiff!="") { Tiff_Im::Create8BFromFonc ( aFileDiff, aFile1.sz(), Max(0,Min(255,128+round_ni(aDyn*(aFile1.in()-aFile2.in())))) ); } std::cout << aName1 << " et " << aName2 << " sont differentes\n"; std::cout << "Nombre de pixels differents = " << aNbDif << "\n"; std::cout << "Somme des differences = " << aSomDif << "\n"; std::cout << "Moyenne des differences = " << (aSomDif/aSom1 )<< "\n"; std::cout << "Difference maximale = " << aMaxDif << " (position " << aPtDifMax[0] << " " << aPtDifMax[1] << ")\n"; return 1; } else { std::cout << "FICHIERS IDENTIQUES SUR LEURS DOMAINES\n"; return 0; } } /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
[ "deseilligny@users.noreply.github.com" ]
deseilligny@users.noreply.github.com
0766243c0948a64a2f33cb287b5dcb90113e9970
4707e74e67ecf13fe852efde73631544d5454edc
/src/atcoder/abc140/c.cc
1fb1c1c46ceae595e4be91e12745b24f5660f249
[]
no_license
HiroakiMikami/procon-workspace
5c6ac081ac3da39c375c6f441d14c3d1a629bdc4
67e29fceae9c700f5cec261d4a82274798371c33
refs/heads/master
2021-01-01T06:33:39.035882
2020-09-04T11:31:19
2020-09-04T11:31:19
97,444,106
0
0
null
null
null
null
UTF-8
C++
false
false
23,775
cc
/* URL https:// SCORE 0 AC false WA false TLE false MLE false TASK_TYPE FAILURE_TYPE NOTES */ #include <iostream> #include <cstdint> #include <utility> #include <tuple> #include <vector> #include <stack> #include <queue> #include <unordered_map> #include <unordered_set> #include <map> #include <set> #include <algorithm> #include <limits> #include <numeric> #include <iomanip> #include <type_traits> #include <functional> #include <experimental/optional> /* import STL */ // stream using std::cout; using std::cerr; using std::cin; using std::endl; using std::flush; // basic types using std::nullptr_t; using std::experimental::optional; using std::pair; using std::tuple; using std::string; // function for basic types using std::experimental::make_optional; using std::make_pair; using std::make_tuple; using std::get; /* TODO remove them */ using std::vector; using std::queue; using std::stack; // algorithms using std::upper_bound; using std::lower_bound; using std::min_element; using std::max_element; using std::nth_element; using std::accumulate; /* macros */ // loops #define REP(i, n) for (i64 i = 0; i < static_cast<decltype(i)>(n); ++i) #define REPR(i, n) for (i64 i = (n) - 1; i >= static_cast<decltype(i)>(0); --i) #define FOR(i, n, m) for (i64 i = (n); i < static_cast<decltype(i)>(m); ++i) #define FORR(i, n, m) for (i64 i = (m) - 1; i >= static_cast<decltype(i)>(n); --i) #define EACH(x, xs) for (auto &x: (xs)) #define EACH_V(x, xs) for (auto x: (xs)) // helpers #define CTR(x) (x).begin(), (x).end() /* utils for std::tuple */ namespace internal { namespace tuple_utils { // TODO rename to "internal::tuple" template<size_t...> struct seq {}; template<size_t N, size_t... Is> struct gen_seq : gen_seq<N - 1, N - 1, Is...> {}; template<size_t... Is> struct gen_seq<0, Is...> : seq<Is...> {}; template<class Tuple, size_t... Is> void read(std::istream &stream, Tuple &t, seq<Is...>) { static_cast<void>((int[]) {0, (void(stream >> get<Is>(t)), 0)...}); } template<class Tuple, size_t... Is> void print(std::ostream &stream, Tuple const &t, seq<Is...>) { static_cast<void>((int[]) {0, (void(stream << (Is == 0 ? "" : ", ") << get<Is>(t)), 0)...}); } template<size_t I, class F, class A, class... Elems> struct ForEach { void operator()(A &arg, tuple<Elems...> const &t) const { F()(arg, get<I>(t)); ForEach<I - 1, F, A, Elems...>()(arg, t); } void operator()(A &arg, tuple<Elems...> &t) const { F()(arg, get<I>(t)); ForEach<I - 1, F, A, Elems...>()(arg, t); } }; template<class F, class A, class... Elems> struct ForEach<0, F, A, Elems...> { void operator()(A &arg, tuple<Elems...> const &t) const { F()(arg, get<0>(t)); } void operator()(A &arg, tuple<Elems...> &t) const { F()(arg, get<0>(t)); } }; template<class F, class A, class... Elems> void for_each(A &arg, tuple<Elems...> const &t) { ForEach<std::tuple_size<tuple<Elems...>>::value - 1, F, A, Elems...>()(arg, t); } template<class F, class A, class... Elems> void for_each(A &arg, tuple<Elems...> &t) { ForEach<std::tuple_size<tuple<Elems...>>::value - 1, F, A, Elems...>()(arg, t); } }} /* utils for Matrix (definition of Matrix) */ namespace internal { namespace matrix { template <typename V, int N> struct matrix_t { using type = std::vector<typename matrix_t<V, N-1>::type>; }; template <typename V> struct matrix_t<V, 0> { using type = V; }; template <typename V, int N> using Matrix = typename matrix_t<V, N>::type; template <typename V, typename It, int N> struct matrix_helper { static Matrix<V, N> create(const It &begin, const It &end, const V &default_value) { return Matrix<V, N>(*begin, matrix_helper<V, It, N - 1>::create(begin + 1, end, default_value)); } }; template <typename V, typename It> struct matrix_helper<V, It, 0> { static Matrix<V, 0> create(const It &begin __attribute__((unused)), const It &end __attribute__((unused)), const V &default_value) { return default_value; } }; }} /* Primitive types */ using i8 = int8_t; using u8 = uint8_t; using i16 = int16_t; using u16 = uint16_t; using i32 = int32_t; using u32 = uint32_t; using i64 = int64_t; using u64 = uint64_t; using usize = size_t; /* Data structure type */ template <typename T> using Vector = std::vector<T>; template <typename V> using OrderedSet = std::set<V>; template <typename V> using HashSet = std::unordered_set<V>; template <typename K, typename V> using OrderedMap = std::map<K, V>; template <typename K, typename V> using HashMap = std::unordered_map<K, V>; template <typename T, int N> using Matrix = internal::matrix::Matrix<T, N>; template <typename T, typename Compare = std::less<T>, typename Container = std::vector<T>> using PriorityQueue = std::priority_queue<T, Container, Compare>; /* utils for Vector */ template <typename V> Vector<V> make_pre_allocated_vector(size_t N) { Vector<V> retval; retval.reserve(N); return retval; } /* utils for Matrix */ template <class V, int N> Matrix<V, N> make_matrix(const std::array<size_t, N> &shape, V default_value = V()) { return internal::matrix::matrix_helper<V, decltype(shape.begin()), N>::create(shape.begin(), shape.end(), default_value); } /* utils for STL iterators */ namespace internal { template <typename Iterator, typename F> struct MappedIterator { MappedIterator(const Iterator &it, const F &function) : it(it), function(function) {} auto operator *() const { return this->function(this->it); } void operator++() { ++this->it; } void operator+=(size_t n) { this->it += n; } auto operator+(size_t n) const { return MappedIterator<Iterator, F>(this->it + n, this->function); } bool operator==(const MappedIterator<Iterator, F> &rhs) const { return this->it == rhs.it; } bool operator!=(const MappedIterator<Iterator, F> &rhs) const { return !(*this == rhs); } private: Iterator it; F function; }; template <typename Iterator, typename P> struct FilteredIterator { FilteredIterator(const Iterator &it, const Iterator &end, const P &predicate) : it(it), end(end), predicate(predicate) { if (this->it != end) { if (!predicate(this->it)) { this->increment(); } } } decltype(auto) operator *() const { return *this->it; } auto operator ->() const { return this->it; } void operator++() { this->increment(); } void operator+=(size_t n) { REP (i, n) { this->increment(); } } auto operator+(size_t n) const { auto retval = *this; retval += n; return retval; } bool operator==(const FilteredIterator<Iterator, P> &rhs) const { return this->it == rhs.it; } bool operator!=(const FilteredIterator<Iterator, P> &rhs) const { return !(*this == rhs); } private: void increment() { if (this->it == this->end) { return ; } ++this->it; while (this->it != this->end && !this->predicate(this->it)) { ++this->it; } } Iterator it; Iterator end; P predicate; }; template <typename Iterator, typename ElementIterator> struct FlattenedIterator { FlattenedIterator(const Iterator &it, const Iterator &end) : it(make_pair(it, ElementIterator())), end(end) { if (this->it.first != this->end) { this->it.second = it->begin(); } this->find_valid(); } decltype(auto) operator *() const { return this->it; } const pair<Iterator, ElementIterator> *operator ->() const { return &this->it; } void operator++() { this->increment(); } void operator+=(size_t n) { REP (i, n) { this->increment(); } } auto operator+(size_t n) const { auto retval = *this; retval += n; return retval; } bool operator==(const FlattenedIterator<Iterator, ElementIterator> &rhs) const { if (this->it.first != rhs.it.first) { return false; } if (this->it.first == this->end || rhs.it.first == rhs.end) { if (this->end == rhs.end) { return true; } else { return false; } } else { return this->it.second == rhs.it.second; } } bool operator!=(const FlattenedIterator<Iterator, ElementIterator> &rhs) const { return !(*this == rhs); } private: bool is_end() const { return this->it.first == this->end; } bool is_valid() const { if (this->is_end()) return false; if (this->it.second == this->it.first->end()) return false; return true; } void _increment() { if (this->it.second == this->it.first->end()) { ++this->it.first; if (this->it.first != this->end) { this->it.second = this->it.first->begin(); } } else { ++this->it.second; } } void find_valid() { while (!this->is_end() && !this->is_valid()) { this->_increment(); } } void increment() { this->_increment(); while (!this->is_end() && !this->is_valid()) { this->_increment(); } } pair<Iterator, ElementIterator> it; Iterator end; }; } template <class Iterator> struct Container { Container(const Iterator &begin, const Iterator &end) : m_begin(begin), m_end(end) {} const Iterator& begin() const { return this->m_begin; } const Iterator& end() const { return this->m_end; } Iterator m_begin; Iterator m_end; }; template <typename C, typename F> auto iterator_map(const C &c, F function) { using Iterator = std::remove_const_t<std::remove_reference_t<decltype(c.begin())>>; return Container<internal::MappedIterator<Iterator, F>>( internal::MappedIterator<Iterator, F>(c.begin(), function), internal::MappedIterator<Iterator, F>(c.end(), function)); } template <typename C, typename P> auto iterator_filter(const C &c, P predicate) { using Iterator = std::remove_const_t<std::remove_reference_t<decltype(c.begin())>>; return Container<internal::FilteredIterator<Iterator, P>>( internal::FilteredIterator<Iterator, P>(c.begin(), c.end(), predicate), internal::FilteredIterator<Iterator, P>(c.end(), c.end(), predicate)); } template <typename C> auto iterator_flatten(const C &c) { using Iterator = std::remove_const_t<std::remove_reference_t<decltype(c.begin())>>; using ElementIterator = std::remove_const_t<std::remove_reference_t<decltype(c.begin()->begin())>>; return Container<internal::FlattenedIterator<Iterator, ElementIterator>>( internal::FlattenedIterator<Iterator, ElementIterator>(c.begin(), c.end()), internal::FlattenedIterator<Iterator, ElementIterator>(c.end(), c.end())); } /* input */ template <class F, class S> std::istream &operator>>(std::istream &stream, pair<F, S> &pair) { stream >> pair.first; stream >> pair.second; return stream; } template <class ...Args> std::istream &operator>>(std::istream &stream, tuple<Args...> &tuple) { internal::tuple_utils::read(stream, tuple, internal::tuple_utils::gen_seq<sizeof...(Args)>()); return stream; } template <class T> T read() { T t; cin >> t; return t; } template <class F, class S> pair<F, S> read() { pair<F, S> p; cin >> p; return p; } template <class T1, class T2, class T3, class ...Args> tuple<T1, T2, T3, Args...> read() { tuple<T1, T2, T3, Args...> t; cin >> t; return t; } template <typename T, typename F = std::function<T()>> Vector<T> read(const usize length, F r) { auto retval = make_pre_allocated_vector<T>(length); REP (i, length) { retval.emplace_back(r()); } return retval; } template <class T> Vector<T> read(const usize length) { return read<T>(length, [] { return read<T>(); }); } template <class F, class S> Vector<pair<F, S>> read(const usize length) { return read<pair<F, S>>(length); } template <class T1, class T2, class T3, class ...Args> Vector<tuple<T1, T2, T3, Args...>> read(const usize length) { return read<tuple<T1, T2, T3, Args...>>(length); } namespace internal { template <typename T> struct oneline { std::string operator()(const T &t) const { std::ostringstream oss; oss << t; return oss.str(); } }; template <typename F, typename S> struct oneline<pair<F, S>> { std::string operator()(const pair<F, S> &p) const { std::ostringstream oss; oss << "{" << oneline<F>()(p.first) << ", " << oneline<S>()(p.second) << "}"; return oss.str(); } }; template <typename ...Args> struct oneline<tuple<Args...>> { struct oneline_tuple { template<class V> void operator()(Vector<std::string> &strs, const V &v) const { strs.emplace_back(oneline<V>()(v)); } }; std::string operator()(const tuple<Args...> &t) const { std::ostringstream oss; Vector<std::string> strs; internal::tuple_utils::for_each<oneline_tuple, Vector<std::string>, Args...>(strs, t); oss << "{"; REPR (i, strs.size()) { oss << strs[i]; if (i != 0) { oss << ", "; } } oss << "}"; return oss.str(); } }; template <> struct oneline<bool> { std::string operator()(const bool b) const { return b ? "true" : "false"; } }; template <typename X> struct oneline<Vector<X>> { std::string operator()(const Vector<X> &vec) const { std::string retval = "["; auto f = oneline<X>(); REP (i, vec.size()) { retval += f(vec[i]); if (i != static_cast<i64>(vec.size() - 1)) { retval += ", "; } } retval += "]"; return retval; } }; template <typename X> struct oneline<OrderedSet<X>> { std::string operator()(const OrderedSet<X> &s) const { std::string retval = "{"; auto f = oneline<X>(); size_t ctr = 0; EACH (x, s) { retval += f(x); ctr += 1; if (ctr != s.size()) { retval += ", "; } } retval += "}"; return retval; } }; template <typename X> struct oneline<HashSet<X>> { std::string operator()(const HashSet<X> &s) const { std::string retval = "{"; auto f = oneline<X>(); size_t ctr = 0; EACH (x, s) { retval += f(x); ctr += 1; if (ctr != s.size()) { retval += ", "; } } retval += "}"; return retval; } }; template <typename K, typename V> struct oneline<OrderedMap<K, V>> { std::string operator()(const OrderedMap<K, V> &s) const { std::string retval = "{"; auto f1 = oneline<K>(); auto f2 = oneline<V>(); size_t ctr = 0; EACH (x, s) { retval += f1(x.first); retval += ": "; retval += f2(x.second); ctr += 1; if (ctr != s.size()) { retval += ", "; } } retval += "}"; return retval; } }; template <typename K, typename V> struct oneline<HashMap<K, V>> { std::string operator()(const HashMap<K,V> &s) const { std::string retval = "{"; auto f1 = oneline<K>(); auto f2 = oneline<V>(); size_t ctr = 0; EACH (x, s) { retval += f1(x.first); retval += ": "; retval += f2(x.second); ctr += 1; if (ctr != s.size()) { retval += ", "; } } retval += "}"; return retval; } }; template <typename V> struct keys { /* no implementation */ }; template <typename X> struct keys<std::vector<X>> { Vector<size_t> operator()(const Vector<X> &v) const { Vector<size_t> keys; REP (i, v.size()) { keys.emplace_back(i); } return keys; } }; template <typename K, typename V> struct keys<OrderedMap<K, V>> { Vector<K> operator()(const OrderedMap<K, V> &c) const { Vector<K> keys; EACH (elem, c) { keys.emplace_back(elem.first); } return keys; } }; template <typename K, typename V> struct keys<HashMap<K, V>> { Vector<K> operator()(const HashMap<K, V> &c) const { Vector<K> keys; EACH (elem, c) { keys.emplace_back(elem.first); } return keys; } }; } template <typename T> void dump(const T& t) { using namespace internal; std::cerr << oneline<T>()(t) << std::endl; } template <typename V1, typename V2, typename ...Args> void dump(const V1 &v1, const V2 &v2, const Args&... args) { using namespace internal; using F = typename oneline<tuple<V1, V2, Args...>>::oneline_tuple; auto x = std::make_tuple(v1, v2, args...); Vector<std::string> strs; internal::tuple_utils::for_each<F, Vector<std::string>, V1, V2, Args...>(strs, x); REPR (i, strs.size()) { std::cerr << strs[i]; if (i != 0) { std::cerr << ", "; } } std::cerr << std::endl; } template <typename C> std::string as_set(const C& ctr) { Vector<std::string> values; using namespace internal; EACH (x, ctr) { values.emplace_back(oneline<decltype(x)>()(x)); } std::string retval = "---\n"; REP (i, values.size()) { retval += values[i]; retval += "\n"; } retval += "---"; return retval; } template <typename C> std::string as_map(const C& ctr) { using namespace internal; auto ks = keys<C>()(ctr); Vector<std::string> keys; Vector<std::string> values; EACH (key, ks) { keys.emplace_back(oneline<decltype(key)>()(key)); values.emplace_back(oneline<decltype(ctr.at(key))>()(ctr.at(key))); } size_t l = 0; EACH (key, keys) { l = std::max(l, key.size()); } std::string retval = "---\n"; REP (i, values.size()) { retval += keys[i]; REP (j, l - keys[i].size()) { retval += " "; } retval += ": "; retval += values[i]; retval += "\n"; } retval += "---"; return retval; } template <typename C> std::string as_table(const C &ctr) { using namespace internal; auto rkeys = keys<C>()(ctr); auto ckeys = OrderedSet<std::string>(); auto values = Vector<pair<std::string, OrderedMap<std::string, std::string>>>(); /* Stringify all data */ EACH (rkey, rkeys) { auto rkey_str = oneline<decltype(rkey)>()(rkey); values.emplace_back(rkey_str, OrderedMap<std::string, std::string>()); auto row = ctr.at(rkey); auto ks = keys<decltype(row)>()(row); EACH (ckey, ks) { auto ckey_str = oneline<decltype(ckey)>()(ckey); ckeys.emplace(ckey_str); values.back().second.emplace(ckey_str, oneline<decltype(row.at(ckey))>()(row.at(ckey))); } } /* Calculate string length */ size_t max_row_key_length = 0; EACH (value, values) { max_row_key_length = std::max(max_row_key_length, value.first.size()); } OrderedMap<std::string, size_t> max_col_length; EACH (ckey, ckeys) { max_col_length.emplace(ckey, ckey.size()); } EACH (value, values) { EACH (elem, value.second) { auto ckey = elem.first; auto value = elem.second; max_col_length[ckey] = std::max(max_col_length[ckey], value.size()); } } std::string retval = "---\n"; /* Header */ REP(i, max_row_key_length) { retval += " "; } retval += " "; size_t cnt = 0; EACH (ckey, ckeys) { retval += ckey; REP (j, max_col_length[ckey] - ckey.size()) { retval += " "; } cnt += 1; if (cnt != ckeys.size()) { retval += ", "; } } retval += "\n------\n"; /* Values */ EACH (value, values) { retval += value.first; REP(i, max_row_key_length - value.first.size()) { retval += " "; } retval += "| "; size_t cnt = 0; EACH (ckey, ckeys) { auto v = std::string(""); if (value.second.find(ckey) != value.second.end()) { v = value.second.at(ckey); } retval += v; REP (j, max_col_length[ckey] - v.size()) { retval += " "; } cnt += 1; if (cnt != ckeys.size()) { retval += ", "; } } retval += "\n"; } retval += "---"; return retval; } // Hash namespace std { template <class F, class S> struct hash<pair<F, S>> { size_t operator ()(const pair<F, S> &p) const { return hash<F>()(p.first) ^ hash<S>()(p.second); } }; template <class ...Args> struct hash<tuple<Args...>> { struct hash_for_element { template<class V> void operator()(size_t &size, const V &v) const { size ^= std::hash<V>()(v); } }; size_t operator ()(const tuple<Args...> &t) const { size_t retval = 0; internal::tuple_utils::for_each<hash_for_element, size_t, Args...>(retval, t); return retval; } }; } #define MAIN void body(); // main function (DO NOT EDIT) int main (int argc, char **argv) { cin.tie(0); std::ios_base::sync_with_stdio(false); cout << std::fixed; body(); return 0; } void body() { auto N = read<i64>(); auto Bs = read<i64>(N - 1); i64 ans = Bs.front() + Bs.back(); REP (i, N - 2) { ans += std::min(Bs[i], Bs[i + 1]); } cout << ans << endl; }
[ "hiroaki8270@gmail.com" ]
hiroaki8270@gmail.com
52d28f90ce6122539357f15d8d648f1ee703ba4d
8b9695b56da685aed7b91feb693fdef1c6945625
/Spatez_NodeMCU/speech_controlled/speech_controlled.ino
2bb4479dd56b2a25e446c2022e7ae8ec97c0870e
[]
no_license
iPankajrai/Spatez-Technology-Work
be3bb748d7a588f16beb509b5f17b1fc8340733d
38fac35434585f0639337b2d7bbc00a9a3bffbc1
refs/heads/master
2022-01-08T00:36:28.765937
2019-06-01T19:16:29
2019-06-01T19:16:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
451
ino
char incomingdata; void setup() { pinMode(13, OUTPUT); Serial.begin(9600); } void loop() { incomingdata = Serial.read(); { if (incomingdata == 'a') { digitalWrite(13, HIGH); Serial.println("light on"); } else if (incomingdata == 'b') { digitalWrite(13, LOW); Serial.println("light off"); } } }
[ "noreply@github.com" ]
iPankajrai.noreply@github.com
8210e2a1c32a5cb02c0addd6c5dce6fe4d1c48a6
7c646b11406898cb89dd453318e3af5b6de1e01c
/include/linuxdeploy/subprocess/process.h
3ff25df7f6bd4d0720b69fb8582fa53b3adad720
[ "MIT" ]
permissive
muttleyxd/linuxdeploy
664210e9b35829ddb9b503c1f52ac72f94bc3082
e91b459fcef2549c26ca1b76f7b8569f3e5267b8
refs/heads/master
2022-11-30T00:34:45.186926
2020-08-08T09:54:58
2020-08-08T09:54:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,665
h
// system headers #include <unordered_map> #include <vector> #include <signal.h> // local headers #include "linuxdeploy/subprocess/subprocess.h" namespace linuxdeploy { namespace subprocess { class process { private: // child process ID int child_pid_ = -1; // pipes to child process's stdout/stderr int stdout_fd_ = -1; int stderr_fd_ = -1; // process exited bool exited_ = false; // exit code -- will be initialized by close() int exit_code_ = -1; // these constants help make the pipe code more readable static constexpr int READ_END_ = 0, WRITE_END_ = 1; static std::vector<char*> make_args_vector_(const std::vector<std::string>& args); static std::vector<char*> make_env_vector_(const subprocess_env_map_t& env); static int check_waitpid_status_(int status); public: /** * Create a child process. * @param args parameters for process * @param env additional environment variables (current environment will be copied) */ process(std::initializer_list<std::string> args, const subprocess_env_map_t& env); /** * Create a child process. * @param args parameters for process * @param env additional environment variables (current environment will be copied) */ process(const std::vector<std::string>& args, const subprocess_env_map_t& env); ~process(); /** * @return child process's ID */ int pid() const; /** * @return child process's stdout file descriptor ID */ int stdout_fd() const; /** * @return child process's stderr file descriptor ID */ int stderr_fd() const; /** * Close all pipes and wait for process to exit. * If process is not running any more, just returns exit code. * @return child process's exit code */ int close(); /** * Kill underlying process with given signal. By default, SIGTERM is used to end the process. */ void kill(int signal = SIGTERM) const; /** * Check whether process is still alive. Use close() to fetch exit code. * @return true while process is alive, false otherwise */ bool is_running(); }; } }
[ "theassassin@assassinate-you.net" ]
theassassin@assassinate-you.net
33419118b513798c21ebbc4f2c74b75922433039
9eecdedbd23c679199c2834cd2e3aaa890684116
/construction/3d-model-rasterization/generation/debug.cpp
19344c1728018d7cabda52c9b1e669a9bf46d4b0
[ "MIT" ]
permissive
mrsalt/minecraft
2ccb931120dc7f917a4d15c81d8e42bbd0307a01
9543a08a680ae8f9351f76555b141ee93a486739
refs/heads/master
2021-07-20T21:30:52.750684
2021-03-17T14:18:29
2021-03-17T14:18:29
245,073,813
1
0
null
null
null
null
UTF-8
C++
false
false
2,679
cpp
#include "Arguments.h" #include "debug.h" #include "geometry.h" #include "ModelWriter_Wavefront.h" #include <iostream> using namespace std; extern const Arguments &args; void write_debug_model( const string &filename, const ModelBuilder &source, const set<const Polygon *> &unplacedPolygons, const Polygon *firstPiece, const vector<const Polygon *> placed, const Polygon *currentPiece, const Polygon *closestPiece, double p) { // let's write a 3d model to help visualize the state of things... SolidColorSurface gray({100, 100, 100}); // completed sections SolidColorSurface blue({50, 50, 150}); // head of current section SolidColorSurface white({255, 255, 255}); // current section, middle pieces SolidColorSurface green({50, 150, 50}); // current polygon SolidColorSurface red({150, 50, 50}); // unplaced polygons SolidColorSurface purple({128, 0, 128}); // closest piece vector<const Polygon *> vector_unplaced_poly; for (auto &up : unplacedPolygons) { if (up != closestPiece && dist(center(up), center(currentPiece)) < 1.0) vector_unplaced_poly.push_back(up); } vector<pair<SolidColorSurface, vector<const Polygon *>>> debug_surfaces; //debug_surfaces.push_back({gray, debug_completed_surfaces}); debug_surfaces.push_back({blue, {firstPiece}}); debug_surfaces.push_back({white, {++placed.begin(), placed.end()}}); debug_surfaces.push_back({green, {currentPiece}}); debug_surfaces.push_back({red, vector_unplaced_poly}); if (closestPiece) debug_surfaces.push_back({purple, {closestPiece}}); cout << "Writing 3D model debug.obj to visualize polygons." << endl; ModelWriter_Wavefront model_writer(args.output_directory, filename); model_writer.write(source.points, debug_surfaces); // add rectangle that shows the plane we're trying to intersect. ModelBuilder::Statistics stats; for (auto &pair : debug_surfaces) { for (auto &poly : pair.second) { stats.addPoints(poly->vertices); } } vector<Point> plane_points = { {p, stats.min.y, stats.min.z}, {p, stats.min.y, stats.max.z}, {p, stats.max.y, stats.max.z}, {p, stats.max.y, stats.min.z}}; Polygon plane; plane.vertices.push_back(&plane_points[0]); plane.vertices.push_back(&plane_points[1]); plane.vertices.push_back(&plane_points[2]); plane.vertices.push_back(&plane_points[3]); vector<pair<SolidColorSurface, vector<const Polygon *>>> debug_plane; debug_plane.push_back({gray, {&plane}}); model_writer.write(plane_points, debug_plane); }
[ "fmark.salisbury@gmail.com" ]
fmark.salisbury@gmail.com
a6d0f7736343f0f62b9b9e24e3fc47aa76758b74
dfdc585de77b411b29cb30882c686cd9a007cfed
/packages/vendors/stm/stm32f4.pack/include/stm32f4/GpioPort.h
321a03ea736df26a5bff1bb53b45c288def0772c
[]
no_license
micro-os-plus/micro-os-plus-iii-alpha
b420532967e9c7498f4448e260a0532d7e303353
a2eed58c5df1e988c1be328f9a2fe6936a1fe0b9
refs/heads/master
2023-06-08T12:48:45.266781
2023-05-25T07:53:05
2023-05-25T07:53:05
69,369,101
0
0
null
null
null
null
UTF-8
C++
false
false
13,111
h
// // This file is part of the µOS++ III distribution. // Copyright (c) 2014 Liviu Ionescu. // #ifndef STM32F4_GPIO_PORT_H_ #define STM32F4_GPIO_PORT_H_ // ---------------------------------------------------------------------------- #include "stm32f4xx.h" #include "stm32f4/gpio.h" #include "stm32f4/GpioPowerPolicy.h" // ---------------------------------------------------------------------------- namespace stm32f4 { // -------------------------------------------------------------------------- class GpioPortImplementation { public: using value_t = gpio::reg16_t; using reg32_t = gpio::reg32_t; using bitsMask_t = gpio::bitsMask_t; using bitNumber_t = gpio::portBitNumber_t; using portNumber_t = gpio::portNumber_t; using index_t = gpio::index_t; protected: GpioPortImplementation() = default; /// \details /// Use read/modify/write to change the 2 configuration bits. /// \warning Non atomic, the caller must use critical sections. inline static void __attribute__((always_inline)) configureMode(GPIO_TypeDef* address, reg32_t mask, reg32_t value) { address->MODER = ((address->MODER & (~mask)) | (value & mask)); } inline static reg32_t __attribute__((always_inline)) retrieveMode(GPIO_TypeDef* address, reg32_t mask) { return (address->MODER & mask); } inline static void __attribute__((always_inline)) configureOutputType(GPIO_TypeDef* address, reg32_t mask, reg32_t value) { address->OTYPER = ((address->OTYPER & (~mask)) | (value & mask)); } inline static reg32_t __attribute__((always_inline)) retrieveOutputType(GPIO_TypeDef* address, reg32_t mask) { return (address->OTYPER & mask); } inline static void __attribute__((always_inline)) configureOutputSpeed(GPIO_TypeDef* address, reg32_t mask, reg32_t value) { address->OSPEEDR = ((address->OSPEEDR & (~mask)) | (value & mask)); } inline static reg32_t __attribute__((always_inline)) retrieveOutputSpeed(GPIO_TypeDef* address, reg32_t mask) { return (address->OSPEEDR & mask); } inline static void __attribute__((always_inline)) configureResistors(GPIO_TypeDef* address, reg32_t mask, reg32_t value) { address->PUPDR = ((address->PUPDR & (~mask)) | (value & mask)); } inline static reg32_t __attribute__((always_inline)) retrieveResistors(GPIO_TypeDef* address, reg32_t mask) { return (address->PUPDR & mask); } inline static void __attribute__((always_inline)) configureAlternateFunction(GPIO_TypeDef* address, index_t index, reg32_t mask, reg32_t value) { address->AFR[index] = ((address->AFR[index] & (~mask)) | (value & mask)); } inline static reg32_t __attribute__((always_inline)) retrieveAlternateFunction(GPIO_TypeDef* address, index_t index, reg32_t mask) { return (address->AFR[index] & mask); } inline static void __attribute__((always_inline)) setHigh(GPIO_TypeDef* address, bitsMask_t mask) { address->BSRRL = mask; } inline static void __attribute__((always_inline)) setLow(GPIO_TypeDef* address, bitsMask_t mask) { address->BSRRH = mask; } inline static void __attribute__((always_inline)) toggle(GPIO_TypeDef* address, bitsMask_t mask) { address->ODR ^= mask; } inline static value_t __attribute__((always_inline)) readInput(GPIO_TypeDef* address) { return static_cast<value_t>(address->IDR); } inline static value_t __attribute__((always_inline)) readOutput(GPIO_TypeDef* address) { return static_cast<value_t>(address->ODR); } inline static void __attribute__((always_inline)) writeOutput(GPIO_TypeDef* address, value_t value) { address->ODR = value; } }; // -------------------------------------------------------------------------- #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpadded" template< // template<typename > class PowerPolicy_T = TAllocatedGpioPortPowerDownPolicy // > class TAllocatedGpioPort : public GpioPortImplementation, // public PowerPolicy_T<TAllocatedGpioPort<PowerPolicy_T>> { using portNumber_t = GpioPortImplementation::portNumber_t; using Implementation = GpioPortImplementation; using PowerPolicy = PowerPolicy_T<TAllocatedGpioPort<PowerPolicy_T>>; public: TAllocatedGpioPort(gpio::PortId portId) : address( reinterpret_cast<GPIO_TypeDef*>(GPIOA_BASE + (static_cast<gpio::portNumber_t>(portId)) * (GPIOB_BASE - GPIOA_BASE))), // portNumber(static_cast<gpio::portNumber_t>(portId)) { } inline gpio::portNumber_t __attribute__((always_inline)) getPortNumber(void) { return this->portNumber; } inline gpio::PortId __attribute__((always_inline)) getPortId(void) { return static_cast<gpio::PortId>(this->portNumber); } inline GPIO_TypeDef* __attribute__((always_inline)) getAddress(void) const { return this->address; } inline void powerUp(void) { PowerPolicy::powerUp(this); } inline void powerDown(void) { PowerPolicy::powerDown(this); } inline void configureMode(reg32_t mask, reg32_t value) const { Implementation::configureMode(this->address, mask, value); } inline reg32_t retrieveMode(reg32_t mask) const { return Implementation::retrieveMode(this->address, mask); } inline void configureOutputType(reg32_t mask, reg32_t value) const { Implementation::configureOutputType(this->address, mask, value); } inline reg32_t retrieveOutputType(reg32_t mask) const { return Implementation::retrieveOutputType(this->address, mask); } inline void configureOutputSpeed(reg32_t mask, reg32_t value) const { Implementation::configureOutputSpeed(this->address, mask, value); } inline reg32_t retrieveOutputSpeed(reg32_t mask) const { return Implementation::retrieveOutputSpeed(this->address, mask); } inline void configureResistors(reg32_t mask, reg32_t value) const { Implementation::configureResistors(this->address, mask, value); } inline reg32_t retrieveResistors(reg32_t mask) const { return Implementation::retrieveResistors(this->address, mask); } inline void configureAlternateFunction(index_t index, reg32_t mask, reg32_t value) const { Implementation::configureAlternateFunction(this->address, index, mask, value); } inline reg32_t retrieveAlternateFunction(index_t index, reg32_t mask) const { return Implementation::retrieveAlternateFunction(this->address, index, mask); } inline void setHigh(bitsMask_t mask) const { Implementation::setHigh(this->address, mask); } inline void setLow(bitsMask_t mask) const { Implementation::setLow(this->address, mask); } inline void toggle(bitsMask_t mask) const { Implementation::toggle(this->address, mask); } inline value_t readInput(void) const { return Implementation::readInput(this->address); } inline value_t readOutput(void) const { return Implementation::readOutput(this->address); } inline void writeOutput(value_t value) const { Implementation::writeOutput(this->address, value); } private: // Allocated members GPIO_TypeDef* const address; portNumber_t const portNumber; }; #pragma GCC diagnostic pop // -------------------------------------------------------------------------- template< gpio::PortId portId_T, // template<typename > class PowerPolicy_T = TConstantGpioPortNoPowerDownPolicy // > class TConstantGpioPort : public GpioPortImplementation, // public PowerPolicy_T<TConstantGpioPort<portId_T, PowerPolicy_T>> { using Implementation = GpioPortImplementation; using PowerPolicy = PowerPolicy_T<TConstantGpioPort<portId_T, PowerPolicy_T>>; // Validate template constant parameters static_assert(portId_T <= gpio::PortId::MAX, "Port number too high"); public: TConstantGpioPort() = default; inline static gpio::portNumber_t __attribute__((always_inline)) getPortNumber(void) { return PORT_NUMBER; } inline static gpio::PortId __attribute__((always_inline)) getPortId(void) { return PORT_ID; } inline static GPIO_TypeDef* __attribute__((always_inline)) getAddress(void) { return PORT_ADDRESS; } inline static void __attribute__((always_inline)) powerUp(void) { PowerPolicy::powerUp(nullptr); } inline static void __attribute__((always_inline)) powerDown(void) { PowerPolicy::powerDown(nullptr); } inline static void __attribute__((always_inline)) configureMode(reg32_t mask, reg32_t value) { Implementation::configureMode(PORT_ADDRESS, mask, value); } inline static reg32_t __attribute__((always_inline)) retrieveMode(reg32_t mask) { return Implementation::retrieveMode(PORT_ADDRESS, mask); } inline static void __attribute__((always_inline)) configureOutputType(reg32_t mask, reg32_t value) { Implementation::configureOutputType(PORT_ADDRESS, mask, value); } inline static reg32_t __attribute__((always_inline)) retrieveOutputType(reg32_t mask) { return Implementation::retrieveOutputType(PORT_ADDRESS, mask); } inline static void __attribute__((always_inline)) configureOutputSpeed(reg32_t mask, reg32_t value) { Implementation::configureOutputSpeed(PORT_ADDRESS, mask, value); } inline static reg32_t __attribute__((always_inline)) retrieveOutputSpeed(reg32_t mask) { return Implementation::retrieveOutputSpeed(PORT_ADDRESS, mask); } inline static void __attribute__((always_inline)) configureResistors(reg32_t mask, reg32_t value) { Implementation::configureResistors(PORT_ADDRESS, mask, value); } inline static reg32_t __attribute__((always_inline)) retrieveResistors(reg32_t mask) { return Implementation::retrieveResistors(PORT_ADDRESS, mask); } inline static void __attribute__((always_inline)) configureAlternateFunction(index_t index, reg32_t mask, reg32_t value) { Implementation::configureAlternateFunction(PORT_ADDRESS, index, mask, value); } inline static reg32_t __attribute__((always_inline)) retrieveAlternateFunction(index_t index, reg32_t mask) { return Implementation::retrieveAlternateFunction(PORT_ADDRESS, index, mask); } inline static void __attribute__((always_inline)) setHigh(bitsMask_t mask) { Implementation::setHigh(PORT_ADDRESS, mask); } inline static void __attribute__((always_inline)) setLow(bitsMask_t mask) { Implementation::setLow(PORT_ADDRESS, mask); } inline static void __attribute__((always_inline)) toggle(bitsMask_t mask) { Implementation::toggle(PORT_ADDRESS, mask); } inline static value_t __attribute__((always_inline)) readInput(void) { return Implementation::readInput(PORT_ADDRESS); } inline static value_t __attribute__((always_inline)) readOutput(void) { return Implementation::readOutput(PORT_ADDRESS); } inline static void __attribute__((always_inline)) writeOutput(value_t mask) { Implementation::writeOutput(PORT_ADDRESS, mask); } private: // Constant members static constexpr gpio::PortId PORT_ID = portId_T; // static constexpr gpio::portNumber_t PORT_NUMBER = static_cast<gpio::portNumber_t>(portId_T); static constexpr GPIO_TypeDef* PORT_ADDRESS = reinterpret_cast<GPIO_TypeDef*>(GPIOA_BASE + PORT_NUMBER * (GPIOB_BASE - GPIOA_BASE)); }; // ---------------------------------------------------------------------------- }//namespace stm32f4 // ---------------------------------------------------------------------------- #endif // STM32F4_GPIO_PORT_H_
[ "ilg@livius.net" ]
ilg@livius.net
5e7cc00175e13aeec91eb23484145f207d375a84
cc153bdc1238b6888d309939fc683e6d1589df80
/mm-video-utils/vtest-omx/app/src/vtest_App.cpp
521e196d3ab7051d1a1c51274b958e5421a3d4df
[]
no_license
ml-think-tanks/msm8996-vendor
bb9aa72dabe59a9bd9158cd7a6e350a287fa6a35
b506122cefbe34508214e0bc6a57941a1bfbbe97
refs/heads/master
2022-10-21T17:39:51.458074
2020-06-18T08:35:56
2020-06-18T08:35:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,197
cpp
/*------------------------------------------------------------------- Copyright (c) 2013-2014, 2016 Qualcomm Technologies, Inc. All Rights Reserved. Confidential and Proprietary - Qualcomm Technologies, Inc. Copyright (c) 2010 The Linux 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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of The Linux Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------*/ #include <stdlib.h> #include "vtest_Script.h" #include "vtest_Debug.h" #include "vtest_ComDef.h" #include "vtest_XmlComdef.h" #include "vtest_XmlParser.h" #include "vtest_ITestCase.h" #include "vtest_TestCaseFactory.h" vtest::VideoStaticProperties sGlobalStaticVideoProp; OMX_ERRORTYPE RunTest(vtest::VideoStaticProperties* pGlobalVideoProp, vtest::VideoSessionInfo* pSessionInfo) { OMX_ERRORTYPE result = OMX_ErrorNone; static OMX_S32 testNum = 0; testNum++; vtest::ITestCase *pTest = vtest::TestCaseFactory::AllocTest(pSessionInfo->SessionType); if (pTest == NULL) { VTEST_MSG_CONSOLE("Unable to alloc test: %s", pSessionInfo->SessionType); return OMX_ErrorInsufficientResources; } VTEST_SIMPLE_MSG_CONSOLE("\n\n"); VTEST_MSG_CONSOLE("Running OMX test %s", pSessionInfo->SessionType); result = pTest->Start(testNum,pGlobalVideoProp, pSessionInfo); if (result != OMX_ErrorNone) { VTEST_MSG_CONSOLE("Error starting test"); } else { result = pTest->Finish(); if (result != OMX_ErrorNone) { VTEST_MSG_CONSOLE("Test failed\n"); if(pGlobalVideoProp->fResult) { fprintf(pGlobalVideoProp->fResult, "\nVTEST-OMX %s, %s, FAIL\n", OMX_VTEST_VERSION, pSessionInfo->TestId); } else { VTEST_MSG_HIGH("Result file not found"); } } else { VTEST_MSG_CONSOLE("Test passed\n"); if(!strcmp(pSessionInfo->SessionType,"DECODE")) { if(pGlobalVideoProp->fResult) { fprintf(pGlobalVideoProp->fResult, "\nVTEST-OMX %s, %s, PASS\n", OMX_VTEST_VERSION, pSessionInfo->TestId); } else { VTEST_MSG_HIGH("Result file not found"); } } else if(!strcmp(pSessionInfo->SessionType,"ENCODE")) { if(pGlobalVideoProp->fResult) { fprintf(pGlobalVideoProp->fResult, "\nVTEST-OMX %s, %s, EPV Pending \n", OMX_VTEST_VERSION, pSessionInfo->TestId); } else { VTEST_MSG_HIGH("Result file not found"); } } else { if(pGlobalVideoProp->fResult) { fprintf(pGlobalVideoProp->fResult, "\nVTEST-OMX %s, %s, UNSUPPORTED TEST CASE \n", OMX_VTEST_VERSION, pSessionInfo->TestId); } else { VTEST_MSG_HIGH("Result file not found"); } } } } vtest::TestCaseFactory::DestroyTest(pTest); return result; } int main(int argc, char *argv[]) { OMX_ERRORTYPE result = OMX_ErrorNone; vtest::XmlParser *pXmlParser = NULL; vtest::VideoSessionInfo sSessionInfo[MAX_NUM_SESSIONS]; vtest::VideoSessionInfo *pSessionInfo = NULL; vtest::VideoSessionInfo *pBaseSessionInfo = NULL; char resultFile[MAX_STR_LEN]; char masterXmlLocation[MAX_STR_LEN]; OMX_Init(); if (argc != 3) { VTEST_MSG_CONSOLE("Usage: %s <MasterConfg.xml path> <input.xml>\n", argv[0]); return OMX_ErrorBadParameter; } pXmlParser = new vtest::XmlParser; if(!pXmlParser) { VTEST_MSG_CONSOLE("Error while allocating memory for pXmlParser\n"); result = OMX_ErrorUndefined; goto DEINIT; } if (!pXmlParser) { VTEST_MSG_CONSOLE("Failed to initialise pXmlParser\n"); return OMX_ErrorInsufficientResources; } //Master XML Parsing if (OMX_ErrorNone != pXmlParser->ResolveMasterXmlPath(argv[1], masterXmlLocation)) { VTEST_MSG_CONSOLE("Error: Input %s is neither a valid path nor a valid filename\n", argv[1]); return OMX_ErrorUndefined; } if (OMX_ErrorNone != pXmlParser->ProcessMasterConfig(&sGlobalStaticVideoProp)) { VTEST_MSG_CONSOLE("Error while processing MasterXml\n"); return OMX_ErrorUndefined; } //Also open the Results.Csv file SNPRINTF(resultFile, MAX_STR_LEN, "%s/Results.csv", masterXmlLocation); sGlobalStaticVideoProp.fResult = fopen(resultFile, "a+"); if (!sGlobalStaticVideoProp.fResult) { VTEST_MSG_CONSOLE("Results.Csv file opening failed"); return OMX_ErrorUndefined; } //Session XML Parsing and Running memset((char*)&sSessionInfo[0], 0, MAX_NUM_SESSIONS * sizeof(vtest::VideoSessionInfo)); if (OMX_ErrorNone != pXmlParser->ParseSessionXml((OMX_STRING)argv[2], &sGlobalStaticVideoProp, &sSessionInfo[0])) { VTEST_MSG_CONSOLE("Error while processing SessionXml and starting test\n"); return OMX_ErrorUndefined; } pSessionInfo = pBaseSessionInfo = &sSessionInfo[0]; while (pSessionInfo->bActiveSession == OMX_TRUE) { if (OMX_ErrorNone != RunTest(&sGlobalStaticVideoProp,pSessionInfo)) { VTEST_MSG_CONSOLE("Failed Processing Session: %s\n", pSessionInfo->SessionType); } pSessionInfo++; if(pSessionInfo >= (pBaseSessionInfo + MAX_NUM_SESSIONS )) { VTEST_MSG_CONSOLE("Exceeded the number of sessions\n"); break; } } if (sGlobalStaticVideoProp.fResult) { fclose(sGlobalStaticVideoProp.fResult); sGlobalStaticVideoProp.fResult = NULL; } if(pXmlParser) { delete pXmlParser; pXmlParser = NULL; } DEINIT: OMX_Deinit(); return result; }
[ "deepakjeganathan@gmail.com" ]
deepakjeganathan@gmail.com
20d24aea6e7da8157ded4537d70373b9c8e47ff0
2755f3d5c0601d9bb4e6281ff66c2bbe14d3ce59
/code/fuzzyoutput.hpp
1675ffe75245f2f0dedb1356541d6faf37f2dfe6
[]
no_license
bozzano101/SmartTrafficLights
e6d6711ec2884feb89c98f579158e9030d3a1080
6881f9014e36dd3a7a536171a41b9806c6b780e8
refs/heads/master
2020-11-25T21:05:11.140982
2020-01-26T09:05:02
2020-01-26T09:05:02
228,846,819
0
1
null
null
null
null
UTF-8
C++
false
false
423
hpp
#ifndef FUZZYOUTPUT_HPP #define FUZZYOUTPUT_HPP #include <fuzzyoutputvariable.hpp> class FuzzyOutput { public: FuzzyOutput(QString name); void appendVariable(FuzzyOutputVariable *newVariable); FuzzyOutputVariable* is(QString name); QString name(); QVector<FuzzyOutputVariable *> *variables(); private: QString m_name; QVector<FuzzyOutputVariable *> m_variables; }; #endif // FUZZYOUTPUT_HPP
[ "boskonet@gmail.com" ]
boskonet@gmail.com
9c6d6948430f0e691753ffaafb9067952c7f2267
98410335456794507c518e361c1c52b6a13b0b39
/sprayMASCOTTELAM2/0.34/uniform/time
bce72b52bcbc7c63d99d79cf35baca7e7ec6dafc
[]
no_license
Sebvi26/MASCOTTE
d3d817563f09310dfc8c891d11b351ec761904f3
80241928adec6bcaad85dca1f2159f6591483986
refs/heads/master
2022-10-21T03:19:24.725958
2020-06-14T21:19:38
2020-06-14T21:19:38
270,176,043
0
0
null
null
null
null
UTF-8
C++
false
false
1,008
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 4.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "0.34/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 0.340000000000000024; name "0.34"; index 1731; deltaT 0.000196078; deltaT0 0.000196078; // ************************************************************************* //
[ "sebastianvi26@gmail.com" ]
sebastianvi26@gmail.com
e108cf9ad48989d799ed640555ed4257c3c66c5a
24bc4990e9d0bef6a42a6f86dc783785b10dbd42
/chrome/browser/accessibility/ax_screen_ai_annotator_factory.h
d22ca07a706f4f9d38613e9c09a3026d3826bf29
[ "BSD-3-Clause" ]
permissive
nwjs/chromium.src
7736ce86a9a0b810449a3b80a4af15de9ef9115d
454f26d09b2f6204c096b47f778705eab1e3ba46
refs/heads/nw75
2023-08-31T08:01:39.796085
2023-04-19T17:25:53
2023-04-19T17:25:53
50,512,158
161
201
BSD-3-Clause
2023-05-08T03:19:09
2016-01-27T14:17:03
null
UTF-8
C++
false
false
1,279
h
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ACCESSIBILITY_AX_SCREEN_AI_ANNOTATOR_FACTORY_H_ #define CHROME_BROWSER_ACCESSIBILITY_AX_SCREEN_AI_ANNOTATOR_FACTORY_H_ #include "base/no_destructor.h" #include "chrome/browser/profiles/profile_keyed_service_factory.h" namespace content { class BrowserContext; } namespace screen_ai { class AXScreenAIAnnotator; // Factory to get or create an instance of AXScreenAIAnnotator for a // BrowserContext. class AXScreenAIAnnotatorFactory : public ProfileKeyedServiceFactory { public: static screen_ai::AXScreenAIAnnotator* GetForBrowserContext( content::BrowserContext* context); static void EnsureExistsForBrowserContext(content::BrowserContext* context); private: friend class base::NoDestructor<AXScreenAIAnnotatorFactory>; static AXScreenAIAnnotatorFactory* GetInstance(); AXScreenAIAnnotatorFactory(); ~AXScreenAIAnnotatorFactory() override; // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; }; } // namespace screen_ai #endif // CHROME_BROWSER_ACCESSIBILITY_AX_SCREEN_AI_ANNOTATOR_FACTORY_H_
[ "roger@nwjs.io" ]
roger@nwjs.io
6f8d639c01b133e7674237a3b40147e8720bdee8
4642f67aa4cc14fe6032d83a89812939ce699e6c
/C++/algorithms/algorithm-interview/Time-Complexity/DynamicVector/main.cpp
e04eef92a462617fa7520e5f981ffd8e5b9cd0d1
[]
no_license
Thpffcj/DataStructures-and-Algorithms
947e75b6e41cb4142fcd1d63e358d44389298a7b
66b838a7a90527064fc1cdcebb43379cb9f0c66c
refs/heads/master
2021-01-01T19:14:38.755589
2020-04-06T01:50:22
2020-04-06T01:50:22
98,543,990
7
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
// // Created by Thpffcj on 2017/9/16. // #include <iostream> #include <cassert> #include <cmath> #include <ctime> #include "MyVector.h" using namespace std; int main() { for( int i = 10 ; i <= 26 ; i ++ ){ int n = pow(2,i); clock_t startTime = clock(); MyVector<int> vec; for( int i = 0 ; i < n ; i ++ ) vec.push_back(i); for( int i = 0 ; i < n ; i ++ ) vec.pop_back(); clock_t endTime = clock(); cout<<2*n<<" operations: \t"; cout<<double(endTime - startTime)/CLOCKS_PER_SEC<<" s"<<endl; } return 0; }
[ "1441732331@qq.com" ]
1441732331@qq.com
ea5a7abc44b014ccb4eb084e3ea70424e60e35dc
c71c0c5d693bccd4cb64b2282cbedbac25b6e114
/src/Magnum/GL/Test/PipelineStatisticsQueryGLTest.cpp
fe20bc2d4a46ef89cf479b6543cc62e680c78efa
[ "MIT" ]
permissive
janbajana/magnum
69287c6d4fc0be577e7b19078406131484f4c53f
9870cd72c96a3e09d5d79cbcd838bb365f84abc6
refs/heads/master
2023-08-23T07:20:47.202851
2021-10-24T17:52:08
2021-10-24T18:17:34
269,671,008
1
0
NOASSERTION
2020-06-05T14:47:21
2020-06-05T14:47:20
null
UTF-8
C++
false
false
5,682
cpp
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Vladimír Vondruš <mosra@centrum.cz> 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 <Corrade/TestSuite/Compare/Numeric.h> #include "Magnum/GL/AbstractShaderProgram.h" #include "Magnum/GL/Buffer.h" #include "Magnum/GL/Context.h" #include "Magnum/GL/Extensions.h" #include "Magnum/GL/Framebuffer.h" #include "Magnum/GL/Mesh.h" #include "Magnum/GL/OpenGLTester.h" #include "Magnum/GL/PipelineStatisticsQuery.h" #include "Magnum/GL/Renderbuffer.h" #include "Magnum/GL/RenderbufferFormat.h" #include "Magnum/GL/Shader.h" namespace Magnum { namespace GL { namespace Test { namespace { struct PipelineStatisticsQueryGLTest: OpenGLTester { explicit PipelineStatisticsQueryGLTest(); void constructMove(); void wrap(); void queryVerticesSubmitted(); }; PipelineStatisticsQueryGLTest::PipelineStatisticsQueryGLTest() { addTests({&PipelineStatisticsQueryGLTest::constructMove, &PipelineStatisticsQueryGLTest::wrap, &PipelineStatisticsQueryGLTest::queryVerticesSubmitted}); } void PipelineStatisticsQueryGLTest::constructMove() { /* Move constructor tested in AbstractQuery, here we just verify there are no extra members that would need to be taken care of */ CORRADE_COMPARE(sizeof(PipelineStatisticsQuery), sizeof(AbstractQuery)); CORRADE_VERIFY(std::is_nothrow_move_constructible<PipelineStatisticsQuery>::value); CORRADE_VERIFY(std::is_nothrow_move_assignable<PipelineStatisticsQuery>::value); } void PipelineStatisticsQueryGLTest::wrap() { if(!Context::current().isExtensionSupported<Extensions::ARB::pipeline_statistics_query>()) CORRADE_SKIP(Extensions::ARB::pipeline_statistics_query::string() << "is not available"); GLuint id; glGenQueries(1, &id); /* Releasing won't delete anything */ { auto query = PipelineStatisticsQuery::wrap(id, PipelineStatisticsQuery::Target::ClippingInputPrimitives, ObjectFlag::DeleteOnDestruction); CORRADE_COMPARE(query.release(), id); } /* ...so we can wrap it again */ PipelineStatisticsQuery::wrap(id, PipelineStatisticsQuery::Target::ClippingInputPrimitives); glDeleteQueries(1, &id); } void PipelineStatisticsQueryGLTest::queryVerticesSubmitted() { if(!Context::current().isExtensionSupported<Extensions::ARB::pipeline_statistics_query>()) CORRADE_SKIP(Extensions::ARB::pipeline_statistics_query::string() << "is not available"); /* Bind some FB to avoid errors on contexts w/o default FB */ Renderbuffer color; color.setStorage(RenderbufferFormat::RGBA8, Vector2i{32}); Framebuffer fb{{{}, Vector2i{32}}}; fb.attachRenderbuffer(Framebuffer::ColorAttachment{0}, color) .bind(); struct MyShader: AbstractShaderProgram { typedef Attribute<0, Vector2> Position; explicit MyShader() { Shader vert( #ifdef CORRADE_TARGET_APPLE Version::GL310 #else Version::GL210 #endif , Shader::Type::Vertex); CORRADE_INTERNAL_ASSERT_OUTPUT(vert.addSource( "#if __VERSION__ >= 130\n" "#define attribute in\n" "#endif\n" "attribute vec4 position;\n" "void main() {\n" " gl_Position = position;\n" "}\n").compile()); attachShader(vert); bindAttributeLocation(Position::Location, "position"); CORRADE_INTERNAL_ASSERT_OUTPUT(link()); } } shader; Buffer vertices; vertices.setData({nullptr, 9*sizeof(Vector2)}, BufferUsage::StaticDraw); Mesh mesh; mesh.setPrimitive(MeshPrimitive::Triangles) .setCount(9) .addVertexBuffer(vertices, 0, MyShader::Position()); MAGNUM_VERIFY_NO_GL_ERROR(); PipelineStatisticsQuery q{PipelineStatisticsQuery::Target::VerticesSubmitted}; q.begin(); Renderer::enable(Renderer::Feature::RasterizerDiscard); shader.draw(mesh); q.end(); const bool availableBefore = q.resultAvailable(); const UnsignedInt count = q.result<UnsignedInt>(); const bool availableAfter = q.resultAvailable(); MAGNUM_VERIFY_NO_GL_ERROR(); { CORRADE_EXPECT_FAIL_IF(availableBefore, "GPU faster than light?"); CORRADE_VERIFY(!availableBefore); } CORRADE_VERIFY(availableAfter); CORRADE_COMPARE(count, 9); } }}}} CORRADE_TEST_MAIN(Magnum::GL::Test::PipelineStatisticsQueryGLTest)
[ "mosra@centrum.cz" ]
mosra@centrum.cz
b8914068b17106b842ad13bb0d7fc33e88d0f90a
240ee2e6a6235cc23d3a6bb9a0171a609ee33129
/2nd/p02Mouse.cpp
66a1f89fb9cda183c93c47d35e28b8a026c66777
[]
no_license
fjnkt98/gazoushori
18b83f89d7303645c2512f2a7b492fbc7b9b3ef1
f0eeb867ffb86189442b70ac7d9b1b2067155e43
refs/heads/master
2020-12-28T00:11:23.147289
2020-02-04T03:43:57
2020-02-04T03:43:57
238,116,400
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,029
cpp
#include <stdio.h> #include <opencv/highgui.h> void mouseCallback(int event, int x, int y, int flags, void *param); void main(int argc, char* argv[]){ IplImage* img; printf("argc = %d\n", argc); for (int k = 0; k < argc; k++) { printf("argv[%d] = %s\n", k, argv[k]); } printf("\n\n"); if (argc > 1) { img = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED); cvNamedWindow("p02-2_Mouse"); cvSetMouseCallback("p02-2_Mouse", mouseCallback, img); cvShowImage("p02-2_Mouse", img); cvWaitKey(0); cvSetMouseCallback("p02-2_Mouse", NULL); cvDestroyAllWindows(); cvReleaseImage(&img); } else { printf("ファイル名を指定してください。\n"); } } void mouseCallback(int event, int x, int y, int flags, void *param){ if (param != NULL){ IplImage *img = (IplImage*)param; // Cast param to IplImage type if (event == CV_EVENT_LBUTTONDOWN){ printf("X : %d, Y : %d, Value : %d\n", x, y, (unsigned char)img->imageData[img->widthStep * y + x]); } } }
[ "a19613@g.ichinoseki.ac.jp" ]
a19613@g.ichinoseki.ac.jp
1816ebd6435993fae91ecc7a2cb66a400ece9555
3c17d9a5f2ff2fd7d8793bc98b96f655513086a5
/ZQlibCNN/ZQ_CNN_CUDA.h
35f4cbfab99e9b599c8df1ceb543a43be20cff6e
[]
no_license
canyuedao/ZQ_SampleMTCNNCuda
5d4445a4dca27f5dea4cda2e1b34040507b89fcb
8aa1beda3cbba1956c5a767414ebbbbd043ccd84
refs/heads/master
2020-11-28T23:01:51.615233
2018-12-05T05:12:01
2018-12-05T05:12:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,877
h
#ifndef _ZQ_CNN_CUDA_H_ #define _ZQ_CNN_CUDA_H_ #pragma once namespace ZQ_CNN_CUDA { /*****************************************************************************/ /*make sure: pBias 's dim: (1,C,1,1) */ float cuAddBias(int N, int C, int H, int W, float* pData, const float* pBias); /*make sure: pBias 's dim: (1,C,1,1) pPara 's dim: (1,C,1,1) */ float cuAddBiasPReLU(int N, int C, int H, int W, float* pData, const float* pBias, const float* pPara); /* over all channels, for each N,H,W */ float cuSoftmaxChannel(int N, int C, int H, int W, float* pData); /*make sure: dst_W = (src_W - filter_W) / stride_W + 1; dst_H = (src_H - filter_H) / stride_H + 1; dst_C = filter_N; dst_N = src_N; filter_C = src_C; */ float cuConvolutionNopadding(int src_N, int src_C, int src_H, int src_W, const float* src, int filter_N, int filter_C, int filter_H, int filter_W, int stride_H, int stride_W, const float* filters, int dst_N, int dst_C, int dst_H, int dst_W, float* dst); /*make sure: dst_W = ceil((float)(src_W - kernel_W) / stride_W + 1); dst_H = ceil((float)(src_H - kernel_H) / stride_H + 1); dst_C = src_C; dst_N = src_N; */ float cuMaxpooling(int src_N, int src_C, int src_H, int src_W, const float* src, int kernel_H, int kernel_W, int stride_H, int stride_W, int dst_N, int dst_C, int dst_H, int dst_W, float* dst); /*make sure: dst_N = src_N; dst_C = dst_C; */ float cuResizeBilinear(int src_N, int src_C, int src_H, int src_W, const float* src, int dst_N, int dst_C, int dst_H, int dst_W, float* dst); /*make sure: src_N = 1; dst_N = rect_N; dst_C = dst_C; rects: 4*rectN, arranged as [off_x, off_y, rect_W, rect_H,...] */ float cuResizeRectBilinear(int src_N, int src_C, int src_H, int src_W, const float* src, int rect_N, const int* rects, int dst_N, int dst_C, int dst_H, int dst_W, float* dst); } #endif
[ "zuoqing1988@aliyun.com" ]
zuoqing1988@aliyun.com
9ccb1f1aa8f0d9fb9a85d54a40a8240e1d7cf329
258c88dfdf72366287752549f0942120e7eb5792
/src/ipm/ipx/src/conjugate_residuals.h
416cddd3fc4b130466a5c7b4114714d59fe7d3bb
[ "MIT" ]
permissive
sschnug/HiGHS
d840cf02bb0315823d97998849d513b282aef01c
53fd9b0629491159d8eb90f42fd46f547c293323
refs/heads/master
2022-07-28T11:36:51.553033
2022-07-12T21:27:21
2022-07-12T21:27:21
131,449,295
0
0
null
2018-04-28T22:43:19
2018-04-28T22:43:19
null
UTF-8
C++
false
false
3,178
h
#ifndef IPX_CONJUGATE_RESIDUALS_H_ #define IPX_CONJUGATE_RESIDUALS_H_ // Implementation of the (preconditioned) Conjugate Residuals (CR) method for // symmetric positive definite linear systems. Without preconditioning, the // method is implemented as in [1, Algorithm 6.20]. The implementation with // preconditioning is described in [2, Section 6.3]. // // [1] Y. Saad, "Iterative Methods for Sparse Linear Systems", 2nd (2003) // [2] L. Schork, "Basis Preconditioning in Interior Point Methods", PhD thesis // (2018) #include "control.h" #include "linear_operator.h" namespace ipx { class ConjugateResiduals { public: // Constructs a ConjugateReisdual object. The object does not have any // memory allocated between calls to Solve(). // @control for InterruptCheck() and Debug(). No parameters are accessed. ConjugateResiduals(const Control& control); // Solves C*lhs = rhs. @lhs has initial iterate on entry, solution on // return. The method terminates when reaching the accuracy criterion // // Infnorm(residual) <= tol (if resscale == NULL), or // Infnorm(resscale.*residual) <= tol (if resscale != NULL). // // In the latter case, @resscale must be an array of dimension @rhs.size(). // The method also stops after @maxiter iterations. If @maxiter < 0, a // maximum of @rhs.size()+100 iterations is performed. (In exact arithmetic // the solution would be found after @rhs.size() iterations. It happened on // some LP models with m << n, e.g. "rvb-sub" from MIPLIB2010, that the CR // method did not reach the termination criterion within m iterations, // causing the IPM to fail. Giving the CR method 100 extra iterations // resolved the issue on all LP models from our test set where it occured.) // // If the @P argument is given, it is used as preconditioner (which // approximates inverse(C)) and must be symmetric positive definite. // void Solve(LinearOperator& C, const Vector& rhs, double tol, const double* resscale, Int maxiter, Vector& lhs); void Solve(LinearOperator& C, LinearOperator& P, const Vector& rhs, double tol, const double* resscale, Int maxiter, Vector& lhs); // Returns 0 if the last call to Solve() terminated successfully (i.e. // the system was solved to the required accuracy). Otherwise returns // IPX_ERROR_cr_iter_limit if iteration limit was reached // IPX_ERROR_cr_matrix_not_posdef if v'*C*v <= 0 for some vector v // IPX_ERROR_cr_precond_not_posdef if v'*P*v <= 0 for some vector v // IPX_ERROR_cr_inf_or_nan if overflow occured // IPX_ERROR_cr_no_progress if no progress due to round-off errors // IPX_ERROR_interrupted if interrupted by control Int errflag() const; // Returns the # iterations in the last call to Solve(). Int iter() const; // Returns the runtime of the last call to Solve(). double time() const; private: const Control& control_; Int errflag_{0}; Int iter_{0}; double time_{0.0}; }; } // namespace ipx #endif // IPX_CONJUGATE_RESIDUALS_H_
[ "jajhall@ed.ac.uk" ]
jajhall@ed.ac.uk
f532dc0e8fb2938407d68dc216f453976ca514e0
4bcf2253c87510bb7ad573587b6fbb7ec23bd13d
/engine/external/tmx-parser/TmxPolygon.h
cb320171aeaa665a72dd3beae32791a845edc360
[]
no_license
Miceroy/yam2d
2d1f586e5c6d16c90b14aa99077ebb9b2f2657a8
089c74a8f297552f4fb0ecf06f9c2839eef4c095
refs/heads/master
2021-01-17T13:07:08.171077
2020-06-10T19:07:08
2020-06-10T19:07:08
32,387,246
1
8
null
null
null
null
UTF-8
C++
false
false
2,248
h
//----------------------------------------------------------------------------- // TmxPolygon.h // // Copyright (c) 2010-2012, Tamir Atias // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL TAMIR ATIAS 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. // // Author: Tamir Atias //----------------------------------------------------------------------------- #pragma once #include <vector> #include "TmxPoint.h" class TiXmlNode; namespace Tmx { //------------------------------------------------------------------------- // Class to store a Polygon of an Object. //------------------------------------------------------------------------- class PointList { public: PointList(); // Parse the polygon node. void Parse(const TiXmlNode *polygonNode); // Get one of the vertices. const Tmx::Point &GetPoint(int index) const { return points[index]; } // Get the number of vertices. int GetNumPoints() const { return points.size(); } private: std::vector< Tmx::Point > points; }; };
[ "kajakbros@gmail.com@2756e8b1-e213-d811-d314-e58f43a541ef" ]
kajakbros@gmail.com@2756e8b1-e213-d811-d314-e58f43a541ef
edb9515cbe9080c225a496e5b282b19255ad3846
f54e1c191f737f1a4c546cad851bd23c125b7dfc
/prblm_001182/prblm_001182/main.cpp
1a7d6892c9629892cf56359082d81d95e2f7a710
[]
no_license
Uginim/baekjoon-solution
1bfcff52aeb3879a9c80851c8dc5f545ba93fa44
aa1486b07ea8e9f78899ed32ff1307e7c36ac445
refs/heads/master
2020-09-22T11:38:43.711180
2019-12-01T14:56:00
2019-12-01T14:56:00
225,177,199
0
0
null
null
null
null
UHC
C++
false
false
943
cpp
#include <iostream> //N using namespace std; #define MAX_SIZE 20 int main(int argc, char * argv) { int N,S,value;//N:숫자 개수, S:합 int nums[MAX_SIZE]; unsigned int powSet, universalSet; powSet = 0x0; //for (int i = 0; i < MAX_SIZE; i++) //powSet[i] = 0; cin >> N >> S;//입력 for (int i = 0; i < N; i++) { scanf("%d", &value); nums[i] = value; } universalSet =0x1; universalSet <<= N; int sum,agreeCnt;//sum : 합계 ,agreeCnt 일치하는 것 개수 unsigned int setFlag;//부분집합을 더하기위한 flag agreeCnt = 0;//카운트 초기화 //부분집합 case를 순회하는 for문 for (unsigned int setIdx = 0x1; setIdx < universalSet; setIdx++) { sum = 0; //부분집합의 합 구하기. for (int i = 0; i < N; i++) { setFlag = 0x1; setFlag <<= i; if (setFlag & setIdx) sum += nums[N - (1+i )]; } if (sum == S) agreeCnt++; } cout << agreeCnt << endl; return 0; }
[ "kimugiugi@gmail.com" ]
kimugiugi@gmail.com
795efb56839a1dc10267d7e712f76cdebc1f67d7
19b016952946bfc56d6ed54b2f6a86774c5405dd
/logdevice/admin/safety/CheckMetaDataLogRequest.h
7c6aa0815d582156e2ca7a5814e75591b1087f82
[ "BSD-3-Clause" ]
permissive
msdgwzhy6/LogDevice
de46d8c327585073df1c18fc94f4cc7b81b173d1
bc2491b7dfcd129e25490c7d5321d3d701f53ac4
refs/heads/master
2020-04-01T17:00:39.187506
2018-10-17T06:29:11
2018-10-17T06:32:21
153,408,883
1
0
NOASSERTION
2018-10-17T06:49:01
2018-10-17T06:49:01
null
UTF-8
C++
false
false
6,740
h
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <chrono> #include <memory> #include "logdevice/common/EpochMetaData.h" #include "logdevice/common/FailureDomainNodeSet.h" #include "logdevice/common/NodeSetFinder.h" #include "logdevice/common/Request.h" #include "logdevice/common/ShardAuthoritativeStatusMap.h" #include "logdevice/common/Worker.h" #include "logdevice/common/configuration/Configuration.h" #include "logdevice/include/types.h" #include "logdevice/include/Record.h" #include "logdevice/include/Err.h" #include "SafetyAPI.h" namespace facebook { namespace logdevice { // read the metadata log record by record, and determine // is it safe to drain specified shards class ClientImpl; class CheckMetaDataLogRequest : public Request { public: // callback function called when the operation is complete // The epoch_t and StorageSet parameters are valid only if Status != E::OK using Callback = folly::Function<void( Status, int, // impact result bit set logid_t, epoch_t, // Which epoch in logid_t has failed the safety check StorageSet, // The storage set that caused the failure (if st != E::OK) ReplicationProperty // The replication property for the offending epoch )>; /** * create a CheckMetaDataLogRequest. CheckMetaDataLogRequest verifies that * it is safe to set the storage state to 'target_storage_state' for op_shards. * If it is data log (check_metadata=false) it reads corresponding metadata * log records by record to do so. * If check_metadata=true, it ignores log_id and verifies we have enough nodes * for metadata after operations * * @param log_id data log id to perform check. Ignored * if check_metadata=true * @param timeout Timeout to use * @param shard_status shard authoritative status map * @param op_shards check those shards if it is safe to perform * operations on them * @param target_storage_state * The configuration::StorageState that we want * to set * @safety_margin safety margin (number of domains in each scope) which we could afford to lose after operations * @param abort_on_error abort on the first problem detected * @param check_metadata check metadata logs instead * @param callback callback to provide result of check */ CheckMetaDataLogRequest(logid_t log_id, std::chrono::milliseconds timeout, ShardAuthoritativeStatusMap shard_status, ShardSet op_shards, configuration::StorageState target_storage_state, SafetyMargin safety_margin, bool check_meta_nodeset, WorkerType worker_type_, Callback callback); ~CheckMetaDataLogRequest() override; WorkerType getWorkerTypeAffinity() override; Request::Execution execute() override; void complete(Status st, int = Impact::ImpactResult::INVALID, // impact result bit set epoch_t error_epoch = EPOCH_INVALID, StorageSet storage_set = {}, ReplicationProperty replication = ReplicationProperty()); /* * Instructs this utility to not assume the server is recent enough to be able * to serve EpochMetaData from the sequencer. */ void readEpochMetaDataFromSequencer() { read_epoch_metadata_from_sequencer_ = true; } private: // Use NodeSetFinder to find historical metadata. void fetchHistoricalMetadata(); // callback for delivering a metadata log record // returns false if an error was found and complete() was called. bool onEpochMetaData(EpochMetaData metadata); /** * Checks whether write availability in this storage set would be lost if we * were to perform the drain. * @param storage_set storage set to verify * @param replication replication property of storage set * @return true if the storage set will not be affected by the drain, false * otherwise */ bool checkWriteAvailability(const StorageSet& storage_set, const ReplicationProperty& replication, NodeLocationScope* fail_scope) const; /** * Checks whether read availability in this storage set would be lost if we * were to disable reads. * @param storage_set storage set to verify * @param replication replication property of storage set * @return true if the storage set will not be affected by the operation, * false otherwise */ bool checkReadAvailability(const StorageSet& storage_set, const ReplicationProperty& replication) const; bool isAlive(node_index_t index) const; /** * Verifies that it is possible to perform operations_ * without losing read/write availability of metadata nodes */ void checkMetadataNodeset(); /** * Create modified ReplicationProperty which takes into account Safety Margin. * For write check (canDrain) we should add it, for read check (isFmajority) * we should subtract **/ ReplicationProperty extendReplicationWithSafetyMargin(const ReplicationProperty& replication_base, bool add) const; std::tuple<bool, bool, NodeLocationScope> checkReadWriteAvailablity(const StorageSet& storage_set, const ReplicationProperty& replication_property); const logid_t log_id_; std::chrono::milliseconds timeout_; // TODO(T28386689): remove once all production tiers are on 2.35. bool read_epoch_metadata_from_sequencer_ = false; std::unique_ptr<NodeSetFinder> nodeset_finder_; // worker index to run the request worker_id_t current_worker_{-1}; ShardAuthoritativeStatusMap shard_status_; ShardSet op_shards_; configuration::StorageState target_storage_state_; // safety margin for each replication scope // we consider operations safe, only if after draining/stopping // we would still have extra (safety margin) domains to loose in each scope // lifetime managed by SafetyChecker SafetyMargin safety_margin_; const bool check_metadata_nodeset_; WorkerType worker_type_; // callback function provided by user of the class. Called when the state // machine completes. Callback callback_; }; }} // namespace facebook::logdevice
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
e5ce6f66ff48cf1a97980fe95e6143560494aed2
4a1d6340874f20ee07f2eea33068148c103d17c2
/chap9/9.8-哈弗曼树/C.cpp
1b674d925d9c44c54cd1b0c11d8f9a26c0854847
[]
no_license
Esther-Guo/algorithm_notes_and_exercise
746febfc52c1c8534c14849a27465b6af2263a38
6b4e6fbc22b66df40e370d0e82def88c4b090a64
refs/heads/master
2020-12-05T04:27:55.229086
2020-02-18T13:02:54
2020-02-18T13:02:54
232,008,697
0
0
null
null
null
null
UTF-8
C++
false
false
80
cpp
// http://codeup.cn/problem.php?cid=100000617&pid=2 /* 本节暂时跳过。 */
[ "special0831qi@gmail.com" ]
special0831qi@gmail.com
e623ade810286ad3859f9f2e0e472de0d1fb8f9a
93abe5bb790b74841f7e28960f0e07cfb79de9a7
/solid/frame/reactorcontext.hpp
170632ae742d6d7e76143464c810b440205e32ff
[ "BSL-1.0" ]
permissive
liuxw7/solidframe
011eb99adbb52ab094e5c1694fe8ad48825195a6
d04794df7e856df9f246516cbb8a5ae4e2caf629
refs/heads/master
2023-03-05T15:54:44.494146
2020-11-27T15:34:27
2020-11-27T15:34:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,331
hpp
// solid/frame/aio/reactorcontext.hpp // // Copyright (c) 2015 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #pragma once #include "solid/system/common.hpp" #include "solid/system/error.hpp" #include "solid/system/nanotime.hpp" #include "solid/system/socketdevice.hpp" #include "solid/frame/aio/aiocommon.hpp" #include <mutex> namespace solid { namespace frame { class Service; class Actor; class Reactor; class CompletionHandler; struct ReactorContext { ~ReactorContext() { } const NanoTime& nanoTime() const { return rcrttm; } std::chrono::steady_clock::time_point steadyTime() const { return rcrttm.timePointCast<std::chrono::steady_clock::time_point>(); } ErrorCodeT const& systemError() const { return syserr; } ErrorConditionT const& error() const { return err; } Actor& actor() const; Service& service() const; Manager& manager() const; UniqueId actorUid() const; std::mutex& actorMutex() const; void clearError() { err.clear(); syserr.clear(); } private: friend class CompletionHandler; friend class Reactor; friend class Actor; Reactor& reactor() { return rreactor; } Reactor const& reactor() const { return rreactor; } ReactorEventsE reactorEvent() const { return reactevn; } CompletionHandler* completionHandler() const; void error(ErrorConditionT const& _err) { err = _err; } void systemError(ErrorCodeT const& _err) { syserr = _err; } ReactorContext( Reactor& _rreactor, const NanoTime& _rcrttm) : rreactor(_rreactor) , rcrttm(_rcrttm) , chnidx(InvalidIndex()) , actidx(InvalidIndex()) , reactevn(ReactorEventNone) { } Reactor& rreactor; const NanoTime& rcrttm; size_t chnidx; size_t actidx; ReactorEventsE reactevn; ErrorCodeT syserr; ErrorConditionT err; }; } //namespace frame } //namespace solid
[ "vipalade@gmail.com" ]
vipalade@gmail.com