blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
24e229139b7a8ef91c67972f63daa0b3cbd4c3d4 | 9bf237b47591f0faae6ef3935be2012584eff1cb | /TextureFileEnumerater/TextureFileEnumerater.cpp | ecd6bdcbac55fd483f37ce7f19af98e1615db9ef | [] | no_license | Alex-Chang/FileAnlayzer | d1492e94a912c50325e0857c1735989ec5b6c459 | 65e74fd7300cd77027ad6b708d273be314130270 | refs/heads/master | 2020-04-05T23:26:48.565619 | 2012-10-09T12:46:12 | 2012-10-09T12:46:12 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,240 | cpp | // TextureFileEnumerater.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "TextureFileEnumerater.h"
#include "../Common/FileHelper.h"
void TextureFileEmumerater::run()
{
string currentPath = FileSystem::getCurrentPath();
FileList fileList;
StringList textureFileList;
FileSystem::getAllFileInPath(fileList, currentPath, "material", FILE_ATTRIBUTE_ARCHIVE);
for (FileIterator i = fileList.begin(); i != fileList.end(); i++)
{
string fileText = FileSystem::GetFileText(i->fileName);
int start = 0, stop = 0;
while(true)
{
start = fileText.find("texture ", start) + 8;
if (start == 7) break;
int spacestop = fileText.find(' ', start);
if (spacestop == -1) spacestop = 999999999;
int returnstop = fileText.find('\n', start);
stop = spacestop < returnstop ? spacestop : returnstop;
string textureFileName = fileText.substr(start, stop - start);
textureFileList.push_back(textureFileName);
}
}
sort(textureFileList.begin(), textureFileList.end());
textureFileList.erase(unique(textureFileList.begin(), textureFileList.end()), textureFileList.end());
for (StringIterator i = textureFileList.begin(); i != textureFileList.end(); i++)
{
cout << "\t" << *i << endl;
}
} | [
"zhangjian19890218@163.com"
] | zhangjian19890218@163.com |
491518bb1f9e4dfe98d4e5c1360d10ef4642fd29 | 43a54d76227b48d851a11cc30bbe4212f59e1154 | /ssa/src/v20180608/model/SaDivulgeDataQueryPubResponse.cpp | e33efb9124e820c0c334608b5577545c76afaf25 | [
"Apache-2.0"
] | permissive | make1122/tencentcloud-sdk-cpp | 175ce4d143c90d7ea06f2034dabdb348697a6c1c | 2af6954b2ee6c9c9f61489472b800c8ce00fb949 | refs/heads/master | 2023-06-04T03:18:47.169750 | 2021-06-18T03:00:01 | 2021-06-18T03:00:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,161 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/ssa/v20180608/model/SaDivulgeDataQueryPubResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ssa::V20180608::Model;
using namespace std;
SaDivulgeDataQueryPubResponse::SaDivulgeDataQueryPubResponse() :
m_dataHasBeenSet(false)
{
}
CoreInternalOutcome SaDivulgeDataQueryPubResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("Data") && !rsp["Data"].IsNull())
{
if (!rsp["Data"].IsObject())
{
return CoreInternalOutcome(Error("response `Data` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_data.Deserialize(rsp["Data"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_dataHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
SaDivulgeDataQueryPubList SaDivulgeDataQueryPubResponse::GetData() const
{
return m_data;
}
bool SaDivulgeDataQueryPubResponse::DataHasBeenSet() const
{
return m_dataHasBeenSet;
}
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
63f2c756e6be00c72da156df42fb98c4ada59760 | 9ee78a31eddfad1c29974e4c0174e0864a1c8dd4 | /CodeUp/1020번.cpp | 669e53896584083fe5bcd29765b80246d610143f | [] | no_license | jingeo1025/Algorithm | e6c84d30fd9cfef21100ed6a6285f2c46cc6de0b | 13a826ca0159f267cc8fee130558265d85b9ebfa | refs/heads/main | 2023-04-30T03:11:54.854844 | 2021-05-26T10:24:54 | 2021-05-26T10:24:54 | 368,077,550 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #include <iostream>
int main() {
int a, b;
scanf("%d-%d", &a, &b);
printf("%.6d%.7d", a, b);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
2d96e14c2b28dcbd18d2fa1b9a46ebb62a2331bc | 7de775f67c84b66a32e29237f608f9f17caf0adb | /src/simulation.integration/implementations/ImplicitEuler.h | 5986c9b0e4332c1018fd8e78bc467646cc755779 | [
"MIT"
] | permissive | toeb/sine | d616f21b9a4ff18d8b1b1d5e9e5a21a8ee7aec04 | 96bcde571218f89a2b0b3cc51c19ad2b7be89c13 | refs/heads/master | 2016-09-05T19:17:07.891203 | 2015-03-20T07:13:45 | 2015-03-20T07:13:45 | 32,568,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,631 | h | /*
* Copyright (C) 2011
* Simulation, Systems Optimization and Robotics Group (SIM)
* Technische Universitaet Darmstadt
* Hochschulstr. 10
* 64289 Darmstadt, Germany
* www.sim.tu-darmstadt.de
*
* This file is part of the mbslib.
* All rights are reserved by the copyright holder.
*
* The mbslib is distributed WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You may use the mbslib or parts of it only with the written permission of the copyright holder.
* You may NOT modify or redistribute any part of the mbslib without the prior written
* permission by the copyright holder.
*
* Any violation of the rights and restrictions mentioned above will be prosecuted by civil and penal law.
* Any expenses associated with the prosecution will be charged against the violator.
*/
/**
* \file src/mbs/integrators/implementations/ImplicitEuler.h
* Declaration of mbslib::ImplicitEulerIntegrator
*/
#pragma once
#include <simulation.integration/StepIntegrator.h>
namespace nspace{
/**
* \brief Implicit euler integrator. (uses fixpoint iteration to solve the implicit equation)
*/
class ImplicitEuler : public StepIntegrator{
private:
StateMatrix _x_next;
Real _tolerance;
int _maxIterations;
public:
ImplicitEuler(Real h=0.01, Real tolerance = 10e-5,int maxIterations=100);
void doStep(StateMatrix & x_next, const StateMatrix & x_i, Real t_i, Real h);
int getErrorOrder()const;
protected:
void logParameters(std::ostream & out);
};//class ImplicitEuler
}//namespace mbslib
| [
"toeb@c65b9dfa-2e9b-4d30-9b60-b5bbc3021b56"
] | toeb@c65b9dfa-2e9b-4d30-9b60-b5bbc3021b56 |
ec24b785dcde930877693f23f4cfc3b8fd283b5e | d5991ab18b6fb8ec8421b02afa317064f6b3b583 | /Projectile.cpp | 83ddcc8e89c91d5a6d409fdb8612734363767096 | [
"CC0-1.0"
] | permissive | atoledanoh/Frogger2020 | dc30c04e22d2e00dbfcfb597528bee4ada2a7ecb | 23e29da4d1e30b0e158b05fa690531660415f715 | refs/heads/main | 2023-01-30T06:19:52.573311 | 2020-12-12T03:20:37 | 2020-12-12T03:20:37 | 320,738,011 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,220 | cpp | #include "Projectile.h"
#include "DataTables.h"
#include "Utility.h"
#include <SFML/Graphics/RenderWindow.hpp>
#include <cmath>
#include <iostream>
#include "EmitterNode.h"
namespace {
const std::map<Projectile::Type, ProjectileData> TABLE = initializeProjectileData();
}
Projectile::Projectile(Type type, const TextureHolder_t& textures)
: Entity(1)
, type(type)
, sprite(textures.get(TABLE.at(type).texture), TABLE.at(type).textureRect)
{
centerOrigin(sprite);
if (isGuided())
{
std::unique_ptr<EmitterNode> smoke(new EmitterNode(Particle::Type::Smoke));
smoke->setPosition(0.f, getBoundingRect().height / 2.f);
attachChild(std::move(smoke));
std::unique_ptr<EmitterNode> fire(new EmitterNode(Particle::Type::Propellant));
fire->setPosition(0.f, getBoundingRect().height / 2.f);
attachChild(std::move(fire));
}
}
void Projectile::guideTowards(sf::Vector2f position)
{
assert(isGuided());
targetDirection = normalize(position - getWorldPosition());
}
bool Projectile::isGuided() const
{
return type == Type::Missile;
}
unsigned int Projectile::getCategory() const
{
if (type == Type::EnemyBullet) {
return Category::Type::EnemyProjectile;
}
else {
return Category::Type::AlliedProjectile;
}
}
float Projectile::getMaxSpeed() const
{
return TABLE.at(type).speed;
}
int Projectile::getDamage() const
{
return TABLE.at(type).damage;
}
sf::FloatRect Projectile::getBoundingRect() const
{
return getWorldTransform().transformRect(sprite.getGlobalBounds());
}
void Projectile::drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(sprite, states);
}
void Projectile::updateCurrent(sf::Time dt, CommandQueue& commands)
{
if (isGuided())
{
const float approachRate = 200.f;
sf::Vector2f newVelocity =
normalize( approachRate * dt.asSeconds() * targetDirection + getVelocity());
newVelocity *= getMaxSpeed();
float angle = std::atan2(newVelocity.y, newVelocity.x);
setRotation(toDegree(angle) + 90.f);
setVelocity(newVelocity);
}
Entity::updateCurrent(dt, commands);
}
| [
"a.toledanoh@gmail.com"
] | a.toledanoh@gmail.com |
d5246171f173457a2dc572c4bde52ce5868524bb | 9324cb559c509753d3a2f6467ccb6616de58af05 | /fboss/agent/hw/bcm/tests/BcmRtag7Test.cpp | f363ac58c61f8be3628f7e72f6017725c6dc5ce4 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | rsunkad/fboss | 4b39eefa3851bd9e415403d28a28290838dea22f | 760255f88fdaeb7f12d092a41362acf1e9a45bbb | refs/heads/main | 2023-07-24T10:39:48.865411 | 2021-09-08T18:58:30 | 2021-09-08T18:59:40 | 404,465,680 | 0 | 0 | NOASSERTION | 2021-09-08T19:09:20 | 2021-09-08T19:09:19 | null | UTF-8 | C++ | false | false | 10,621 | cpp | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/gen-cpp2/switch_config_types.h"
#include "fboss/agent/hw/bcm/BcmError.h"
#include "fboss/agent/hw/bcm/BcmSwitch.h"
#include "fboss/agent/hw/bcm/tests/BcmTest.h"
#include "fboss/agent/hw/bcm/tests/BcmTestUtils.h"
#include "fboss/agent/state/LoadBalancer.h"
#include "fboss/agent/state/LoadBalancerMap.h"
#include <memory>
using namespace facebook::fboss;
namespace facebook::fboss {
class BcmRtag7Test : public BcmTest {
public:
void updateLoadBalancers(std::shared_ptr<LoadBalancerMap> loadBalancerMap) {
auto newState = getProgrammedState()->clone();
newState->resetLoadBalancers(loadBalancerMap);
applyNewState(newState);
}
protected:
std::shared_ptr<SwitchState> setupFullEcmpHash() {
auto noMplsFields = LoadBalancer::MPLSFields{};
return setupHash(
LoadBalancerID::ECMP,
kV4Fields_,
kV6FieldsNoFlowLabel_,
kTransportFields_,
std::move(noMplsFields));
}
std::shared_ptr<SwitchState> setupHalfTrunkHash() {
auto noTransportFields = LoadBalancer::TransportFields{};
auto noMplsFields = LoadBalancer::MPLSFields{};
return setupHash(
LoadBalancerID::AGGREGATE_PORT,
kV4Fields_,
kV6FieldsNoFlowLabel_,
std::move(noTransportFields),
std::move(noMplsFields));
}
std::shared_ptr<SwitchState> setupHashWithAllFields(LoadBalancerID id) {
return setupHash(
id, kV4Fields_, kV6Fields_, kTransportFields_, kMplsFields_);
}
std::shared_ptr<SwitchState> setupHash(
LoadBalancerID id,
const LoadBalancer::IPv4Fields& v4Fields,
const LoadBalancer::IPv6Fields& v6Fields,
const LoadBalancer::TransportFields& transportFields,
const LoadBalancer::MPLSFields& mplsFields) {
auto loadBalancer =
makeLoadBalancer(id, v4Fields, v6Fields, transportFields, mplsFields);
auto loadBalancers = getProgrammedState()->getLoadBalancers()->clone();
if (!loadBalancers->getNodeIf(id)) {
loadBalancers->addNode(std::move(loadBalancer));
} else {
loadBalancers->updateNode(std::move(loadBalancer));
}
auto state = getProgrammedState();
state->modify(&state);
state->resetLoadBalancers(std::move(loadBalancers));
return state;
}
std::unique_ptr<LoadBalancer> makeLoadBalancer(
LoadBalancerID id,
const LoadBalancer::IPv4Fields& v4Fields,
const LoadBalancer::IPv6Fields& v6Fields,
const LoadBalancer::TransportFields& transportFields,
const LoadBalancer::MPLSFields& mplsFields) {
return std::make_unique<LoadBalancer>(
id,
cfg::HashingAlgorithm::CRC16_CCITT,
getSeed(id),
v4Fields,
v6Fields,
transportFields,
mplsFields);
}
uint32_t getDefaultHashSubFieldSelectorsForL3MPLSForward() {
return BCM_HASH_MPLS_FIELD_TOP_LABEL | BCM_HASH_MPLS_FIELD_2ND_LABEL |
BCM_HASH_MPLS_FIELD_3RD_LABEL | BCM_HASH_MPLS_FIELD_LABELS_4MSB |
BCM_HASH_MPLS_FIELD_IP4SRC_LO | BCM_HASH_MPLS_FIELD_IP4SRC_HI |
BCM_HASH_MPLS_FIELD_IP4DST_LO | BCM_HASH_MPLS_FIELD_IP4DST_HI;
}
uint32_t getDefaultHashSubFieldSelectorsForL3MPLSTerminate() {
return BCM_HASH_MPLS_FIELD_IP4SRC_LO | BCM_HASH_MPLS_FIELD_IP4SRC_HI |
BCM_HASH_MPLS_FIELD_IP4DST_LO | BCM_HASH_MPLS_FIELD_IP4DST_HI |
BCM_HASH_FIELD_FLOWLABEL_LO | BCM_HASH_FIELD_FLOWLABEL_HI |
BCM_HASH_FIELD_SRCL4 | BCM_HASH_FIELD_DSTL4;
}
inline uint32_t getSeed(LoadBalancerID id) const {
return id == LoadBalancerID::AGGREGATE_PORT ? kTrunkSeed : kEcmpSeed;
}
const LoadBalancer::IPv4Fields kV4Fields_{
LoadBalancer::IPv4Field::SOURCE_ADDRESS,
LoadBalancer::IPv4Field::DESTINATION_ADDRESS};
const LoadBalancer::IPv6Fields kV6Fields_{
LoadBalancer::IPv6Field::SOURCE_ADDRESS,
LoadBalancer::IPv6Field::DESTINATION_ADDRESS,
LoadBalancer::IPv6Field::FLOW_LABEL};
const LoadBalancer::IPv6Fields kV6FieldsNoFlowLabel_{
LoadBalancer::IPv6Field::SOURCE_ADDRESS,
LoadBalancer::IPv6Field::DESTINATION_ADDRESS};
const LoadBalancer::TransportFields kTransportFields_{
LoadBalancer::TransportField::SOURCE_PORT,
LoadBalancer::TransportField::DESTINATION_PORT};
const LoadBalancer::MPLSFields kMplsFields_{
LoadBalancer::MPLSField::TOP_LABEL,
LoadBalancer::MPLSField::SECOND_LABEL,
LoadBalancer::MPLSField::THIRD_LABEL};
static constexpr auto kEcmpSeed = 0x7E57EDA;
static constexpr auto kTrunkSeed = 0x7E57EDB;
};
TEST_F(BcmRtag7Test, programLoadBalancerMap) {
auto setupBothLoadBalancers = [=]() {
applyNewState(setupFullEcmpHash());
applyNewState(setupHalfTrunkHash());
};
auto verifyBothLoadBalancers = [=]() {
// TODO(samank): factor out unit number
const bool kEnable = true;
const int v4HalfHash = BCM_HASH_FIELD_IP4SRC_LO | BCM_HASH_FIELD_IP4SRC_HI |
BCM_HASH_FIELD_IP4DST_LO | BCM_HASH_FIELD_IP4DST_HI;
const int v4FullHash =
v4HalfHash | BCM_HASH_FIELD_SRCL4 | BCM_HASH_FIELD_DSTL4;
const int v6HalfHash = BCM_HASH_FIELD_IP6SRC_LO | BCM_HASH_FIELD_IP6SRC_HI |
BCM_HASH_FIELD_IP6DST_LO | BCM_HASH_FIELD_IP6DST_HI;
const int v6FullHash =
v6HalfHash | BCM_HASH_FIELD_SRCL4 | BCM_HASH_FIELD_DSTL4;
// ECMP load-balancing settings
utility::assertSwitchControl(bcmSwitchHashField0PreProcessEnable, kEnable);
utility::assertSwitchControl(
bcmSwitchHashSeed0, getSeed(LoadBalancerID::ECMP));
utility::assertSwitchControl(bcmSwitchHashIP4Field0, v4FullHash);
utility::assertSwitchControl(bcmSwitchHashIP6Field0, v6FullHash);
utility::assertSwitchControl(bcmSwitchHashIP4TcpUdpField0, v4FullHash);
utility::assertSwitchControl(bcmSwitchHashIP6TcpUdpField0, v6FullHash);
utility::assertSwitchControl(
bcmSwitchHashIP4TcpUdpPortsEqualField0, v4FullHash);
utility::assertSwitchControl(
bcmSwitchHashIP6TcpUdpPortsEqualField0, v6FullHash);
utility::assertSwitchControl(
bcmSwitchHashField0Config, BCM_HASH_FIELD_CONFIG_CRC16CCITT);
utility::assertSwitchControl(
bcmSwitchHashField0Config1, BCM_HASH_FIELD_CONFIG_CRC16CCITT);
// ECMP output-selection settings
utility::assertSwitchControl(bcmSwitchHashUseFlowSelEcmp, 1);
utility::assertSwitchControl(bcmSwitchMacroFlowHashMinOffset, 0);
utility::assertSwitchControl(bcmSwitchMacroFlowHashMaxOffset, 15);
utility::assertSwitchControl(bcmSwitchMacroFlowHashStrideOffset, 1);
// ECMP specific settings
utility::assertSwitchControl(
bcmSwitchHashControl, BCM_HASH_CONTROL_ECMP_ENHANCE);
// LAG load-balancing settings
utility::assertSwitchControl(bcmSwitchHashField1PreProcessEnable, kEnable);
utility::assertSwitchControl(
bcmSwitchHashSeed1, getSeed(LoadBalancerID::AGGREGATE_PORT));
utility::assertSwitchControl(bcmSwitchHashIP4Field1, v4HalfHash);
utility::assertSwitchControl(bcmSwitchHashIP6Field1, v6HalfHash);
utility::assertSwitchControl(bcmSwitchHashIP4TcpUdpField1, v4HalfHash);
utility::assertSwitchControl(bcmSwitchHashIP6TcpUdpField1, v6HalfHash);
utility::assertSwitchControl(
bcmSwitchHashIP4TcpUdpPortsEqualField1, v4HalfHash);
utility::assertSwitchControl(
bcmSwitchHashIP6TcpUdpPortsEqualField1, v6HalfHash);
utility::assertSwitchControl(
bcmSwitchHashField1Config, BCM_HASH_FIELD_CONFIG_CRC16CCITT);
utility::assertSwitchControl(
bcmSwitchHashField1Config1, BCM_HASH_FIELD_CONFIG_CRC16CCITT);
// LAG output-selection settings
utility::assertSwitchControl(bcmSwitchHashUseFlowSelTrunkUc, 1);
if (!getHwSwitch()->getPlatform()->getAsic()->isSupported(
HwAsic::Feature::NON_UNICAST_HASH)) {
utility::assertSwitchControl(bcmSwitchMacroFlowTrunkHashMinOffset, 16);
utility::assertSwitchControl(bcmSwitchMacroFlowTrunkHashMaxOffset, 31);
utility::assertSwitchControl(bcmSwitchMacroFlowTrunkHashStrideOffset, 1);
utility::assertSwitchControl(bcmSwitchMacroFlowTrunkHashConcatEnable, 0);
} else {
utility::assertSwitchControl(
bcmSwitchMacroFlowTrunkUnicastHashMinOffset, 16);
utility::assertSwitchControl(
bcmSwitchMacroFlowTrunkUnicastHashMaxOffset, 31);
utility::assertSwitchControl(
bcmSwitchMacroFlowTrunkUnicastHashStrideOffset, 1);
utility::assertSwitchControl(
bcmSwitchMacroFlowTrunkUnicastHashConcatEnable, 0);
utility::assertSwitchControl(
bcmSwitchMacroFlowTrunkNonUnicastHashMinOffset, 16);
utility::assertSwitchControl(
bcmSwitchMacroFlowTrunkNonUnicastHashMaxOffset, 31);
utility::assertSwitchControl(
bcmSwitchMacroFlowTrunkNonUnicastHashStrideOffset, 1);
utility::assertSwitchControl(
bcmSwitchMacroFlowTrunkNonUnicastHashConcatEnable, 0);
}
// Global RTAG7 settings
utility::assertSwitchControl(bcmSwitchHashSelectControl, 0);
utility::assertSwitchControl(
bcmSwitchMacroFlowHashFieldConfig,
BcmRtag7Module::getMacroFlowIDHashingAlgorithm());
utility::assertSwitchControl(bcmSwitchMacroFlowHashUseMSB, 1);
utility::assertSwitchControl(bcmSwitchMacroFlowEcmpHashConcatEnable, 0);
};
verifyAcrossWarmBoots(setupBothLoadBalancers, verifyBothLoadBalancers);
}
TEST_F(BcmRtag7Test, programMPLSLoadBalancer) {
auto setupBothLoadBalancers = [=]() {
applyNewState(setupHashWithAllFields(LoadBalancerID::ECMP));
return applyNewState(
setupHashWithAllFields(LoadBalancerID::AGGREGATE_PORT));
};
auto verifyBothLoadBalancers = [=]() {
auto mplsTerminationHash =
getDefaultHashSubFieldSelectorsForL3MPLSTerminate();
auto mplsForwardHash = getDefaultHashSubFieldSelectorsForL3MPLSForward();
// ECMP load-balancing settings
utility::assertSwitchControl(
bcmSwitchHashL3MPLSField0, mplsTerminationHash);
utility::assertSwitchControl(
bcmSwitchHashL3MPLSField1, mplsTerminationHash);
utility::assertSwitchControl(
bcmSwitchHashMPLSTunnelField0, mplsForwardHash);
utility::assertSwitchControl(
bcmSwitchHashMPLSTunnelField0, mplsForwardHash);
};
verifyAcrossWarmBoots(setupBothLoadBalancers, verifyBothLoadBalancers);
}
} // namespace facebook::fboss
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
86f3e6f89beb1db7c422fef02c31fb70c1bc0245 | 60c275f5670d8a509421dbe53a704cdf85289035 | /LeetCode/67_Add_Binary/main.cpp | fb066f56943921d3ae852f5c282f1f6a24d608a1 | [
"MIT"
] | permissive | Cutyroach/Solve_Algorithms | f02f03c5ad146550b136e19292a3599b2eff6702 | 97d9f8bb65055fe5ad62d108a9359b91f0f40c49 | refs/heads/master | 2023-03-02T21:27:03.214056 | 2021-02-09T23:58:47 | 2021-02-09T23:58:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,456 | cpp | /**
* Runtime: 0 ms, faster than 100.00% of C++ online submissions for Add Binary.
* Memory Usage: 6.2 MB, less than 100.00% of C++ online submissions for Add Binary.
*/
class Solution {
public:
string addBinary(string a, string b) {
for (int i = 0; i < a.size() / 2; i++) {
char tmp = a[i];
a[i] = a[a.size() - 1 - i];
a[a.size() - 1 - i] = tmp;
}
for (int i = 0; i < b.size() / 2; i++) {
char tmp = b[i];
b[i] = b[b.size() - 1 - i];
b[b.size() - 1 - i] = tmp;
}
if (a.size() < b.size()) {
int upper = 0;
for (int i = 0; i < a.size(); i++) {
int chr = a[i] - '0' + b[i] - '0' + upper;
upper = chr / 2;
b[i] = chr % 2 + '0';
}
for (int i = a.size(); i < b.size(); i++) {
int chr = b[i] - '0' + upper;
upper = chr / 2;
b[i] = chr % 2 + '0';
}
if (upper) b += '1';
for (int i = 0; i < b.size() / 2; i++) {
char tmp = b[i];
b[i] = b[b.size() - 1 - i];
b[b.size() - 1 - i] = tmp;
}
return b;
} else if (a.size() > b.size()) {
int upper = 0;
for (int i = 0; i < b.size(); i++) {
int chr = a[i] - '0' + b[i] - '0' + upper;
upper = chr / 2;
a[i] = chr % 2 + '0';
}
for (int i = b.size(); i < a.size(); i++) {
int chr = a[i] - '0' + upper;
upper = chr / 2;
a[i] = chr % 2 + '0';
}
if (upper) a += '1';
for (int i = 0; i < a.size() / 2; i++) {
char tmp = a[i];
a[i] = a[a.size() - 1 - i];
a[a.size() - 1 - i] = tmp;
}
return a;
} else {
int upper = 0;
for (int i = 0; i < b.size(); i++) {
int chr = a[i] - '0' + b[i] - '0' + upper;
upper = chr / 2;
a[i] = chr % 2 + '0';
}
if (upper) a += '1';
for (int i = 0; i < a.size() / 2; i++) {
char tmp = a[i];
a[i] = a[a.size() - 1 - i];
a[a.size() - 1 - i] = tmp;
}
return a;
}
}
}; | [
"spe0678@gmail.com"
] | spe0678@gmail.com |
2aaf151908ec1f858a5441580da8bd7732315937 | bdf380de8e928693a8332711a3795a1d70f8fc69 | /constants.hpp | 89dc5482efa9ef6b974a69f124ce9a74761081c4 | [] | no_license | fjdu/chempl | e69cd29781689f57a53269810e5764b44275ffc3 | fca959a9959be33bb9bec5f86b2da14a23eb2803 | refs/heads/master | 2023-08-26T12:09:20.770430 | 2021-10-22T04:21:59 | 2021-10-22T04:21:59 | 248,031,308 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,635 | hpp | #ifndef CONST_H
#define CONST_H
#include <map>
#include <string>
namespace CONST {
extern "C" {
extern std::map<std::string, double> element_masses;
extern const double PI;
extern const double PI_div_2;
extern const double PI_mul_2;
extern const double SQRT2PI;
extern const double LN10;
extern const double phy_elementaryCharge_SI;
extern const double phy_electronClassicalRadius_SI;
extern const double phy_electronClassicalRadius_CGS;
extern const double phy_CoulombConst_SI;
extern const double phy_atomicMassUnit_SI ;
extern const double phy_mProton_SI ;
extern const double phy_mProton_CGS;
extern const double phy_mElectron_SI ;
extern const double phy_mElectron_CGS;
extern const double phy_kBoltzmann_SI ;
extern const double phy_kBoltzmann_CGS;
extern const double phy_hPlanck_SI ;
extern const double phy_hPlanck_CGS;
extern const double phy_hbarPlanck_SI ;
extern const double phy_hbarPlanck_CGS;
extern const double phy_GravitationConst_SI ;
extern const double phy_GravitationConst_CGS;
extern const double phy_SpeedOfLight_SI ;
extern const double phy_SpeedOfLight_CGS;
extern const double phy_StefanBoltzmann_SI;
extern const double phy_StefanBoltzmann_CGS;
extern const double phy_IdealGasConst_SI;
extern const double phy_ThomsonScatterCross_CGS;
extern const double phy_Lsun_SI;
extern const double phy_Lsun_CGS;
extern const double phy_Msun_SI;
extern const double phy_Msun_CGS;
extern const double phy_Rsun_SI;
extern const double phy_Rsun_CGS;
extern const double phy_Rearth_CGS;
extern const double phy_Mearth_CGS;
extern const double phy_Rmoon_CGS;
extern const double phy_Mmoon_CGS;
extern const double phy_RJupiter_CGS;
extern const double phy_MJupiter_CGS;
extern const double phy_SecondsPerYear;
extern const double phy_Deg2Rad;
extern const double phy_erg2joule;
extern const double phy_m2cm;
extern const double phy_kg2g;
extern const double phy_eV2erg;
extern const double phy_cm_1_2erg;
extern const double phy_cm_1_2K;
extern const double phy_AvogadroConst;
extern const double phy_AU2cm;
extern const double phy_AU2m ;
extern const double phy_pc2m ;
extern const double phy_pc2cm;
extern const double phy_Angstrom2micron ;
extern const double phy_Angstrom2cm ;
extern const double phy_micron2cm ;
extern const double phy_jansky2CGS;
extern const double phy_jansky2SI ;
extern const double phy_CMB_T;
extern const double phy_ratioDust2GasMass_ISM;
extern const double phy_Habing_photon_energy_CGS;
extern const double phy_LyAlpha_energy_CGS;
extern const double phy_UV_cont_energy_CGS;
extern const double phy_Habing_energy_density_CGS;
extern const double phy_Habing_photon_flux_CGS;
extern const double phy_Habing_energy_flux_CGS;
extern const double phy_UVext2Av;
extern const double phy_EUVext2Av;
extern const double phy_LyAlpha_nu0;
extern const double phy_LyAlpha_l0;
extern const double phy_LyAlpha_dnul;
extern const double phy_LyAlpha_f12;
extern const double phy_LyAlpha_cross_H2O;
extern const double phy_LyAlpha_cross_OH ;
extern const double phy_cosmicray_ionization_rate;
extern const double phy_cosmicray_desorption_factor;
extern const double phy_cosmicray_desorption_T;
extern const double phy_cosmicray_attenuate_N_CGS;
extern const double phy_cosmicray_attenuate_m_CGS;
extern const double phy_PAH_abundance_0;
extern const double phy_SitesDensity_CGS;
extern const double phy_DiffBarrierWidth_CGS;
extern const double phy_Diff2DesorRatio;
extern const double phy_DiffBarrierDefault;
extern const double phy_vibFreqDefault;
extern const double colDen2Av_coeff;
extern const double phy_colDen2Av_coeff;
extern const double phy_colDen2AUV_1000A;
}
}
#endif //CONST_H
| [
"fujun.du@gmail.com"
] | fujun.du@gmail.com |
40abc81283e0438df85e61aeaf632efe854abd3e | 1c249aadf837aa71fc5fea9508ded990367f01ff | /DesignPatterns/Bridge/Bridge/Bridge.cpp | 8b4837aeee1ff4433056e65a5715c5e240c9ba81 | [] | no_license | MYOUTCR/DesignPatterns | 91c9b6146e6961095e26f4c3ef381b3f59ea8977 | 5a8e0c4b967a0d093285598e333ac111ca29309d | refs/heads/master | 2020-03-31T21:51:10.813574 | 2020-01-05T12:23:08 | 2020-01-05T12:23:08 | 152,596,101 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 338 | cpp | // Bridge.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Bridge.h"
int main()
{
Shape *redCircle = new Circle(100, 100, 10, new RedCircle());
Shape *greenCircle = new Circle(100, 100, 10, new GreenCircle());
redCircle->draw();
greenCircle->draw();
getchar();
return 0;
}
| [
"cn_yhm@163.com"
] | cn_yhm@163.com |
3c81c8f14c0e86ffc4a42bddb0db8eadc9a0314b | d160bb839227b14bb25e6b1b70c8dffb8d270274 | /MCMS/Main/Libs/McmsCurlLib/CurlSoap.cpp | 7e7601922c4ecd762762742b2b4875932c12cccc | [] | no_license | somesh-ballia/mcms | 62a58baffee123a2af427b21fa7979beb1e39dd3 | 41aaa87d5f3b38bc186749861140fef464ddadd4 | refs/heads/master | 2020-12-02T22:04:46.442309 | 2017-07-03T06:02:21 | 2017-07-03T06:02:21 | 96,075,113 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,272 | cpp | /*
* CurlSoap.cpp
*
* Created on: Jun 17, 2009
* Author: kobi
*/
#include "CurlSoap.h"
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <curl/curl.h>
#include "Trace.h"
#include "TraceStream.h"
#include "ProcessBase.h"
#include "SysConfig.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
CurlSoap::CurlSoap(bool bIsSecured/*=false*/,bool bSkipPeerVerification/*=false*/,bool bSkipHostNameVerfication/*=false*/)
: CurlHTTP(bIsSecured,bSkipPeerVerification,bSkipHostNameVerfication)
{
m_bFirstSendTrans = true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
CurlSoap::~CurlSoap()
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void CurlSoap::AddAditionalConfiguration()
{
CurlHTTP::AddAditionalConfiguration();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
bool CurlSoap::PostSoapRequestFromFile(CURLcode& retCode, const std::string& strUrl,
const std::string& strSoapAction, const std::string& strPostDataFileName,
const bool grabHeaders /*= true*/, const bool grabUrl /*= true*/)
{
char * buffer = LoadSoapBufferFromFile(strPostDataFileName.c_str());
if (buffer==NULL)
{
FPTRACE(eLevelInfoNormal,"CurlSoap::PostSoapRequestFromFile failed to load file!");
return false;
}
FPTRACE(eLevelInfoNormal,buffer);
std::string strRequest = buffer;
delete[] buffer;
return PostSoapRequest(retCode,strUrl,strSoapAction,strRequest,grabHeaders,grabUrl);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
bool CurlSoap::PostSoapRequest(CURLcode& res, const std::string& strUrl,
const std::string& strSoapAction, const std::string& strRequest,
const bool grabHeaders /*= true*/, const bool grabUrl /*= true*/)
{
// FPTRACE2(eLevelInfoNormal,"CurlSoap::PostSoapRequest=",strRequest.c_str());
res = CURLE_OK;
std::string::size_type start_pos;
DATA data;
data.bGrab = grabUrl;
data.pstr = m_pstrContent;
data.bClearString = true;
DATA headers_data = {&m_headers , grabHeaders, true};
struct curl_slist* headers = NULL;
int reason = 0;
char * buffer = new char[strRequest.length()+1];
memset(buffer,'\0',strRequest.length()+1);
strncpy(buffer,strRequest.c_str(),strRequest.length());
std::string strCombinedSoap = "SOAPAction:" + strSoapAction;
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_ERRORBUFFER , m_pszErrorBuffer)) != CURLE_OK )
{
reason = 1;
goto clean_up;
}
AddAditionalConfiguration();
SetMethodConfiguration(eHttpPost);
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_POSTFIELDS, buffer)) != CURLE_OK )
{
reason = 2;
goto clean_up;
}
headers = curl_slist_append(headers, "Content-Type: text/xml; charset=utf-8");
headers = curl_slist_append(headers, strCombinedSoap.c_str());
// headers = curl_slist_append(headers, "Expect:100-continue");
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_HTTPHEADER , headers)) != CURLE_OK )
{
reason = 3;
goto clean_up;
}
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_TIMEOUT , /*5*/m_timeout)) != CURLE_OK )
{
reason = 4;
goto clean_up;
}
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_URL, strUrl.c_str())) != CURLE_OK )
{
reason = 5;
goto clean_up;
}
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_USERAGENT, MY_USR_AGENT)) != CURLE_OK )
{
reason = 6;
goto clean_up;
}
if (m_bIsNTLMAuth)
SetNtlmAuthenticationParams(m_userName,m_password);
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_POSTFIELDSIZE, strlen(buffer))) != CURLE_OK )
{
reason = 7;
goto clean_up;
}
// if (m_bFirstSendTrans==false) //if riding on the Same Post request there is no point to register the write Function again
// return true; // and we use the same connection that has already been NTLM authenticated, in first request
// it is required to send the same request time twice due to NTLM Authentication.
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_WRITEFUNCTION, writefunction)) != CURLE_OK )
{
reason = 9;
goto clean_up;
}
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_WRITEDATA, (void *)&data)) != CURLE_OK )
{
reason = 10;
goto clean_up;
}
if(grabHeaders)
{
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_HEADERFUNCTION, writefunction)) != CURLE_OK )
{
reason = 11;
goto clean_up;
}
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_WRITEHEADER, (void *)&headers_data)) != CURLE_OK )
{
reason = 12;
goto clean_up;
}
}
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_NOSIGNAL , 1L)) != CURLE_OK )
{
reason = 13;
goto clean_up;
}
if(m_bIsSetSourceIF)
{
if ( (res = curl_easy_setopt(m_pcurl, CURLOPT_INTERFACE , m_sourceIF.c_str())) != CURLE_OK )
{
reason = 14;
goto clean_up;
}
}
if( true )
{
sighandler_t tOldSignalHandler = signal(SIGALRM,SIG_IGN);
// FPTRACE(eLevelInfoNormal,"CurlSoap::PostSoapRequestFromFile - change signal to SIG_IGN");
if ( (res = curl_easy_perform(m_pcurl)) != CURLE_OK )
{
// FPTRACE(eLevelInfoNormal,"CurlSoap::PostSoapRequestFromFile - change signal back to old");
signal(SIGALRM,tOldSignalHandler);
if ( grabUrl )
{
reason = 15;
goto clean_up;
}
}
else
{
signal(SIGALRM,tOldSignalHandler);
// FPTRACE(eLevelInfoNormal,"CurlSoap::PostSoapRequestFromFile - change signal back to old");
}
}
m_bFirstSendTrans = false;
curl_slist_free_all(headers);
delete [] buffer;
start_pos = m_headers.find(SOAP_OR_REST_RESPONSE_OK);
if( std::string::npos == start_pos )
{
FPTRACE2(eLevelInfoNormal,"CurlSoap::PostSoapRequestFromFile failure response from Server resp header = %s!",m_headers.c_str());
return false;
}
return true;
clean_up:
// error string
std::stringstream streamMsg;
streamMsg << "Curl error: " << __FILE__ << ":" << __LINE__
<< "; error: " << m_pszErrorBuffer
<< "; retVal=" << res
<< "; reason=" << reason
<< ";";
FPTRACE(eLevelInfoNormal,streamMsg.str().c_str());
if( headers != NULL )
curl_slist_free_all(headers);
delete [] buffer;
return false;
}
void CurlSoap::ResetCurlLib()
{
curl_easy_reset(m_pcurl);
}
| [
"somesh.ballia@gmail.com"
] | somesh.ballia@gmail.com |
210361c1369473a1de2ff87fa360d21f3b056f35 | 4b1063e24b83896463a53dd0e2a0fef8c2ae29a3 | /QMediaLearner/gui/dialogs/ExportVideoDialog.cpp | 0301f081d4036d5fca861a451fb6bac43e33e05d | [] | no_license | cedrix57/QMediaLearner | 00c1750fa5afe8fc2a1ff3245e44d27db710fa9f | 2ca936190987cc67bdd03c4b1c09acbe504d6b8f | refs/heads/master | 2016-09-05T10:51:17.796726 | 2014-01-01T01:01:18 | 2014-01-01T01:01:18 | 12,093,828 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,762 | cpp | #include "ExportVideoDialog.h"
#include "ui_ExportVideoDialog.h"
#include <QFileDialog>
#include <QMessageBox>
#include <SettingsManagerSingleton.h>
//====================================
ExportVideoDialog::ExportVideoDialog(
ML::MediaLearnerLib
*mediaLearner,
QWidget *parent) :
QDialog(parent),
ui(new Ui::ExportVideoDialog){
ui->setupUi(this);
this->mediaLearner
= mediaLearner;
this->progressDialog.setWindowTitle(
tr("Encoding..."));
this->progressDialog.setMinimum(
0);
this->progressDialog.setMaximum(
0);
this->progressDialog.setLabelText(
"0 %");
this->ui->buttonEditProfiles->hide();
this->_loadInfos();
this->_connectSlots();
if(this->ui->radioButtonAudioProfile->isChecked()){
this->ui->radioButtonVideoProfile->setChecked(true);
this->ui->radioButtonAudioProfile->toggle();
}else{
this->ui->radioButtonAudioProfile->setChecked(true);
this->ui->radioButtonVideoProfile->toggle();
}
this->changingSize = false;
}
//====================================
void ExportVideoDialog::onAudioProfileToogled(
bool val){
this->ui->comboBoxProfilesAudio->setEnabled(val);
this->ui->comboBoxProfilesVideo->setEnabled(!val);
this->ui->checkBoxSaveSubEmbedded->setEnabled(!val);
this->ui->checkBoxSaveSubEncoded->setEnabled(!val);
QString profileName = this->getProfileName();
this->onProfileChanged(profileName);
}
//====================================
QString ExportVideoDialog::getProfileName(){
bool isVideo
= this->ui->radioButtonVideoProfile
->isChecked();
QString profileName;
if(isVideo){
profileName
= this->ui->comboBoxProfilesVideo
->currentText();
}else{
profileName
= this->ui->comboBoxProfilesAudio
->currentText();
}
return profileName;
}
//====================================
void ExportVideoDialog::onProfileChanged(
QString profileName){
QString filePath
= this->ui->lineEditFilePath
->text();
if(!filePath.isEmpty() && filePath.indexOf(".") != -1){
ML::EncoderInterface
*encoder
= this->mediaLearner
->getEncoder();
QString ext
= encoder->getProfileExt(profileName);
if(!filePath.endsWith(ext)){
QStringList cuttedFilePath
= filePath.split(".");
cuttedFilePath.takeLast();
cuttedFilePath << ext;
QString newFilePath
= cuttedFilePath.join(".");
this->ui->lineEditFilePath
->setText(newFilePath);
}
}
}
//====================================
void ExportVideoDialog::onProgressChanged(int percentage){
QString text = QString::number(percentage);
text += " %";
qDebug() << "progress changed: " << text;
this->progressDialog.setLabelText(
text);
}
//====================================
void ExportVideoDialog::_connectSlots(){
ML::EncoderInterface
*encoder
= this->mediaLearner
->getEncoder();
this->progressDialog.connect(
encoder,
SIGNAL(encodingFinished()),
SLOT(reset()));
this->progressDialog.connect(
encoder,
SIGNAL(encodingFailed()),
SLOT(reset()));
this->connect(
encoder,
SIGNAL(encodingProgressed(int)),
SLOT(onProgressChanged(int)));
this->connect(
this->ui->buttonBrowseFilePath,
SIGNAL(clicked()),
SLOT(browseNewVideoFilePath()));
this->connect(
this->ui->radioButtonAudioProfile,
SIGNAL(toggled(bool)),
SLOT(onAudioProfileToogled(bool)));
this->connect(
this->ui->comboBoxProfilesAudio,
SIGNAL(currentIndexChanged(QString)),
SLOT(onProfileChanged(QString)));
this->connect(
this->ui->comboBoxProfilesVideo,
SIGNAL(currentIndexChanged(QString)),
SLOT(onProfileChanged(QString)));
this->connect(
this->ui->spinBoxHeight,
SIGNAL(valueChanged(int)),
SLOT(onHeightChanged(int)));
this->connect(
this->ui->spinBoxWidth,
SIGNAL(valueChanged(int)),
SLOT(onWidthChanged(int)));
}
//====================================
void ExportVideoDialog::_loadInfos(){
ML::EncoderInterface
*encoder
= this->mediaLearner
->getEncoder();
QMap<QString, ML::ProfileInfo>
videoProfiles
= encoder->getAvailableVideoProfiles();
foreach(QString profile, videoProfiles.keys()){
this->ui->comboBoxProfilesVideo->addItem(
profile);
}
QMap<QString, ML::ProfileInfo>
audioProfiles
= encoder->getAvailableAudioProfiles();
foreach(QString profile, audioProfiles.keys()){
this->ui->comboBoxProfilesAudio->addItem(
profile);
}
ML::SettingsManagerSingleton *settingsManager
= ML::SettingsManagerSingleton::getInstance();
bool saveSRTsubs
= settingsManager->isSaveSRTsubs();
this->ui->checkBoxSaveSubWithSrt
->setChecked(saveSRTsubs);
bool lastWasVideoProfile
= settingsManager->isLastProfileVideo();
QString lastVideoProfileName
= settingsManager->getLastVideoProfileName();
this->ui->comboBoxProfilesVideo
->setCurrentText(lastVideoProfileName);
QString lastAudioProfileName
= settingsManager->getLastAudioProfileName();
this->ui->comboBoxProfilesAudio
->setCurrentText(lastAudioProfileName);
if(lastWasVideoProfile){
this->ui->radioButtonVideoProfile->setChecked(true);
this->ui->radioButtonAudioProfile->setChecked(false);
}else{
this->ui->radioButtonVideoProfile->setChecked(false);
this->ui->radioButtonAudioProfile->setChecked(true);
}
//this->ui->radioButtonVideoProfile->setAutoExclusive(true);
//this->ui->radioButtonAudioProfile->setAutoExclusive(true);
ML::SubtitlesManager *subManager
= this->mediaLearner->getSubtitlesManager();
bool sub1 = subManager->isSubTrackEnabled(0);
bool sub2 = subManager->isSubTrackEnabled(1);
bool sub3 = subManager->isSubTrackEnabled(2);
bool saveSubs = sub1 || sub2 || sub3;
this->ui->groupBoxSaveSubtitles
->setEnabled(saveSubs);
this->ui->groupBoxSaveSubtitles
->setChecked(saveSubs);
this->ui->checkBoxTrack1->setChecked(sub1);
this->ui->checkBoxTrack2->setChecked(sub2);
this->ui->checkBoxTrack3->setChecked(sub3);
QSize videoSize = encoder->getOriginalSize();
this->ui->spinBoxWidth->setValue(videoSize.width());
this->ui->spinBoxHeight->setValue(videoSize.height());
this->originalVideoSize = videoSize;
}
//====================================
ExportVideoDialog::~ExportVideoDialog(){
delete ui;
}
//====================================
void ExportVideoDialog::accept(){
QString outVideoFilePath
= this->ui->lineEditFilePath->text();
bool fileExists = QFile(outVideoFilePath).exists();
if(fileExists){
QMessageBox::StandardButton reply
= QMessageBox::question(
this,
tr("The file already exist"),
tr("Do you want to replace it?"),
QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::No){
return;
}else{
QFile::remove(outVideoFilePath);
}
}
ML::SettingsManagerSingleton *settingsManager
= ML::SettingsManagerSingleton::getInstance();
bool isVideo
= this->ui->radioButtonVideoProfile
->isChecked();
QString videoProfileName
= this->ui->comboBoxProfilesVideo
->currentText();
QString audioProfileName
= this->ui->comboBoxProfilesAudio
->currentText();
bool saveSRTsubs
= this->ui->checkBoxSaveSubWithSrt
->isChecked();
settingsManager->setLastProfileVideo(isVideo);
settingsManager->setLastVideoProfileName(videoProfileName);
settingsManager->setLastAudioProfileName(audioProfileName);
settingsManager->setSaveSRTsubs(saveSRTsubs);
QString profileName = this->getProfileName();
ML::EncoderInterface
*encoder
= this->mediaLearner
->getEncoder();
encoder->selectFormatProfile(profileName);
ML::SequenceExtractor
*sequenceExtractor
= this->mediaLearner
->getSequenceExtractor();
ML::SubtitlesManager
*subtitlesManager
= this->mediaLearner
->getSubtitlesManager();
QSharedPointer<QList<ML::Sequence> >
sequences
= sequenceExtractor
->getExtractedSequences();
bool embedSubtitle
= this->ui->checkBoxSaveSubEmbedded
->isChecked()
&& isVideo;
if(embedSubtitle){
ML::SubtitleTrack*
subs
= subtitlesManager
->getSubtitleTracks();
this->sequencesWithSubs.init(
*sequences,
subs);
}else{
this->sequencesWithSubs.init(
*sequences);
}
QSize videoSize
= encoder->getOriginalSize();
this->sequencesWithSubs.setScreenSize(
videoSize);
if(this->ui->groupBoxPlaybackRate->isChecked()){
double playbackRate = this->ui->spinBoxRate->value();
encoder->setPlaybackRate(playbackRate);
}
if(this->ui->groupBoxResize->isChecked()){
int videoWidth = this->ui->spinBoxWidth->value();
int videoHeight = this->ui->spinBoxHeight->value();
QSize newVideoSize(videoWidth, videoHeight);
encoder->setNewSize(
newVideoSize);
}
QList<ML::SequenceWithSubs>
sequencesWithSubs
= this->sequencesWithSubs.getSequencesWithTexts();
encoder->setSequences(
sequencesWithSubs);
encoder->encode(
outVideoFilePath);
this->progressDialog.show();
this->_saveSrtSubEventually();
//*/
//TODO progress dialog
}
//====================================
void ExportVideoDialog::_saveSrtSubEventually(){
ML::SequenceExtractor
*sequenceExtractor
= this->mediaLearner
->getSequenceExtractor();
QSharedPointer<QList<ML::Sequence> >
sequences
= sequenceExtractor
->getExtractedSequences();
bool saveStr
= this->ui->checkBoxSaveSubWithSrt
->isChecked();
if(saveStr){
QString outVideoFilePath
= this->ui->lineEditFilePath->text();
QStringList cuttedFilePath
= outVideoFilePath.split(".");
cuttedFilePath.takeLast();
QString baseSrtFilePath
= cuttedFilePath.join(".");
ML::SubtitlesManager
*subtitlesManager
= this->mediaLearner
->getSubtitlesManager();
bool save1
= this->ui->checkBoxTrack1
->isChecked();
if(save1){
subtitlesManager->saveSubtitle(
0,
baseSrtFilePath + "_1.srt",
*sequences);
}
bool save2
= this->ui->checkBoxTrack2
->isChecked();
if(save2){
subtitlesManager->saveSubtitle(
1,
baseSrtFilePath + "_2.srt",
*sequences);
}
bool save3
= this->ui->checkBoxTrack3
->isChecked();
if(save3){
subtitlesManager->saveSubtitle(
2,
baseSrtFilePath + "_3.srt",
*sequences);
}
}
}
//====================================
void ExportVideoDialog::browseNewVideoFilePath(){
QString lastDirPath
= ML::SettingsManagerSingleton::getInstance()
->getExtractedVideoPath();
QString filePath
= QFileDialog::getSaveFileName(
this,
tr("Choose a new file"),
lastDirPath);
if(!filePath.isNull()){
QString profileName;
if(this->ui->radioButtonAudioProfile->isChecked()){
profileName
= this->ui->comboBoxProfilesAudio->currentText();
}else{
profileName
= this->ui->comboBoxProfilesVideo->currentText();
}
ML::EncoderInterface
*encoder
= this->mediaLearner
->getEncoder();
QString ext
= encoder->getProfileExt(profileName);
filePath += "." + ext;
this->ui->lineEditFilePath
->setText(filePath);
QDir dirPath(filePath);
dirPath.cd("..");
QString currentPath = dirPath.path();
ML::SettingsManagerSingleton::getInstance()
->setExtractedVideoPath(
currentPath);
}
}
//====================================
void ExportVideoDialog::onWidthChanged(int width){
if(!this->changingSize){
this->changingSize = true;
int keepRatio
= this->ui->checkBoxKeepRatio->isChecked();
if(keepRatio){
int newHeight
= width
* this->originalVideoSize.height()
/ this->originalVideoSize.width();
this->ui->spinBoxHeight->setValue(newHeight);
}
this->changingSize = false;
}
}
//====================================
void ExportVideoDialog::onHeightChanged(int height){
if(!this->changingSize){
this->changingSize = true;
int keepRatio
= this->ui->checkBoxKeepRatio->isChecked();
if(keepRatio){
int newWidth
= height
* this->originalVideoSize.width()
/ this->originalVideoSize.height();
this->ui->spinBoxWidth->setValue(newWidth);
}
this->changingSize = false;
}
}
//====================================
| [
"bcedrix@gmail.com"
] | bcedrix@gmail.com |
b58baf6e456da44ea33946f2cc8f8a6b91119a7f | e320855ed72cdb446366371e9b8b94f8f2ab9dc4 | /baseView.h | 61634d2e9c637ec6435e7b6a9634711d939e7b8b | [] | no_license | yourcaptain/rsa_encryption_sample | 368179b7cb1ea766c1a2bf088e50922ff0e5226c | fcbbfd0b1ebf9ca111ee889fdbcddd81ee52c2cb | refs/heads/master | 2021-01-16T22:30:43.682217 | 2016-09-19T05:53:06 | 2016-09-19T05:53:06 | 68,573,320 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,862 | h | // baseView.h : interface of the CBaseView class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_BASEVIEW_H__FE5B55F7_2799_4E08_8C74_660C333B4DB5__INCLUDED_)
#define AFX_BASEVIEW_H__FE5B55F7_2799_4E08_8C74_660C333B4DB5__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <string>//Ôö¼Ó
//#include <qstring>//QString
class CBaseView : public CView
{
protected: // create from serialization only
CBaseView();
DECLARE_DYNCREATE(CBaseView)
// Attributes
public:
CBaseDoc* GetDocument();
// QString global_strPublicKey ;
// static const char rnd_seed[] = "string to make the random number generator think it has entropy";
// std::string base64_encode(unsigned char const* , unsigned int len);
// std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len)
//
// std::string base64_decode(std::string const& s);
// std::string base64_decode(std::string const& encoded_string)
std::string EncodeRSAKeyFile(std::string const& strPemFileName, std::string const& strData);
std::string EncodeRSAKeyMemory(std::string const& strData);
std::string DecodeRSAKeyFile(std::string const& strPemFileName, std::string const& strData);
std::string DecodeRSAKeyMemory(std::string const& strData);
// std::string EncodeRSAKeyFile( const std::string& strPemFileName, const std::string& strData );
// std::string DecodeRSAKeyFile( const std::string& strPemFileName, const std::string& strData );
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBaseView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CBaseView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CBaseView)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in baseView.cpp
inline CBaseDoc* CBaseView::GetDocument()
{ return (CBaseDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BASEVIEW_H__FE5B55F7_2799_4E08_8C74_660C333B4DB5__INCLUDED_)
| [
"yuan.aiqing@gmail.com"
] | yuan.aiqing@gmail.com |
fdb38d44eb1cf0251b5e617dee393a6edad4d097 | d5200712c2e5485fc122b608161eac50d8abedff | /CodeForces/CF797E.cpp | 10bc3a6123cf7505ad5f4a50abe68bdc1f634186 | [] | no_license | CSHwang4869/Online-Judge-Solutions | 0f416b219616d7eb2d1e979b4690491c17230597 | f5e6e3f9722b660955b97e147e14817270c169c4 | refs/heads/master | 2021-09-26T08:01:39.141055 | 2021-09-17T06:09:18 | 2021-09-17T06:09:18 | 150,004,099 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,221 | cpp | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#define DEBUG printf("Passing [%s] in Line %d\n" , __FUNCTION__ , __LINE__) ;
const int MAX_N = 1e5 + 10 ;
struct Query {
int p , k , idx , ans ;
}que[MAX_N] ;
int n , m , block , a[MAX_N] , f[MAX_N] ;
bool cmp1(Query x , Query y) {return x.k < y.k ;}
bool cmp2(Query x , Query y) {return x.idx < y.idx ;}
int getans(int p , int k) {
int t = 0 ;
for (; p <= n ; p = p + a[p] + k , ++t) ;
return t ;
}
void dp(int k) {
for (int i = n ; i ; --i) {
int np = i + a[i] + k ;
if (np > n) f[i] = 1 ;
else f[i] = f[np] + 1 ;
}
}
int main() {
scanf("%d" , &n) ; block = (int)sqrt(n) ;
for (int i = 1 ; i <= n ; ++i) scanf("%d" , &a[i]) ;
scanf("%d" , &m) ;
for (int i = 0 ; i < m ; ++i) scanf("%d %d" , &que[i].p , &que[i].k) , que[i].idx = i ;
///
std::sort(que + 0 , que + m , cmp1) ;
int last = -1 ;
for (int i = 0 ; i < m ; ++i) {
Query *pt = &que[i] ;
if (pt->k > block) pt->ans = getans(pt->p , pt->k) ;
else {
if (last != pt->k) dp(pt->k) , last = pt->k ;
pt->ans = f[pt->p] ;
}
}
std::sort(que + 0 , que + m , cmp2) ;
for (int i = 0 ; i < m ; ++i) printf("%d\n" , que[i].ans) ;
return 0 ;
} | [
"cshwang4869@outlook.com"
] | cshwang4869@outlook.com |
c618b164287bd99bc8f493b59cb4c4471dbcafba | 223c83d90308a94c3c0df8580aafe558f082d1ec | /Lumen_Engine/LumenPT/vendor/Include/Cuda/thrust/version.h | a79b369c1d0911c8a897d9b62a5b5d59f04224a0 | [] | no_license | LumenPT/LumenRenderer | 79ca9ebe423afbaff09c5f565ba99bc57ef96dc0 | fcf147af8339dc9a77695a668cbb2d963f918c72 | refs/heads/main | 2023-06-20T08:31:53.145932 | 2021-07-02T10:23:37 | 2021-07-02T10:23:37 | 315,650,016 | 19 | 3 | null | 2021-07-01T15:45:49 | 2020-11-24T14:02:52 | C++ | UTF-8 | C++ | false | false | 2,949 | h | /*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*! \file version.h
* \brief Compile-time macros encoding Thrust release version
*
* <thrust/version.h> is the only Thrust header that is guaranteed to
* change with every thrust release.
*
* It is also the only header that does not cause THRUST_HOST_SYSTEM
* and THRUST_DEVICE_SYSTEM to be defined. This way, a user may include
* this header and inspect THRUST_VERSION before programatically defining
* either of these macros herself.
*/
#pragma once
// This is the only Thrust header that is guaranteed to
// change with every Thrust release.
//
// THRUST_VERSION % 100 is the sub-minor version
// THRUST_VERSION / 100 % 1000 is the minor version
// THRUST_VERSION / 100000 is the major version
//
// Because this header does not #include <thrust/detail/config.h>,
// it is the only Thrust header that does not cause
// THRUST_HOST_SYSTEM and THRUST_DEVICE_SYSTEM to be defined.
/*! \def THRUST_VERSION
* \brief The preprocessor macro \p THRUST_VERSION encodes the version
* number of the Thrust library.
*
* <tt>THRUST_VERSION % 100</tt> is the sub-minor version.
* <tt>THRUST_VERSION / 100 % 1000</tt> is the minor version.
* <tt>THRUST_VERSION / 100000</tt> is the major version.
*/
#define THRUST_VERSION 100910
/*! \def THRUST_MAJOR_VERSION
* \brief The preprocessor macro \p THRUST_MAJOR_VERSION encodes the
* major version number of the Thrust library.
*/
#define THRUST_MAJOR_VERSION (THRUST_VERSION / 100000)
/*! \def THRUST_MINOR_VERSION
* \brief The preprocessor macro \p THRUST_MINOR_VERSION encodes the
* minor version number of the Thrust library.
*/
#define THRUST_MINOR_VERSION (THRUST_VERSION / 100 % 1000)
/*! \def THRUST_SUBMINOR_VERSION
* \brief The preprocessor macro \p THRUST_SUBMINOR_VERSION encodes the
* sub-minor version number of the Thrust library.
*/
#define THRUST_SUBMINOR_VERSION (THRUST_VERSION % 100)
/*! \def THRUST_PATCH_NUMBER
* \brief The preprocessor macro \p THRUST_PATCH_NUMBER encodes the
* patch number of the Thrust library.
*/
#define THRUST_PATCH_NUMBER 1
/*! \namespace thrust
* \brief \p thrust is the top-level namespace which contains all Thrust
* functions and types.
*/
namespace thrust
{
}
| [
"44769712+AlphaAlexRed@users.noreply.github.com"
] | 44769712+AlphaAlexRed@users.noreply.github.com |
13dea2d29e4317870b6d7c0b7e7313e87b0743af | e12b5ffa7153c58c16e25cd4475189f56e4eb9d1 | /Explanation2/P3371.cpp | 943cb098369b15081f68028b66d16769d497dee3 | [] | no_license | hhhnnn2112-Home/NOI-ACcode-Explanation | ef1cdf60504b3bd01ba96f93519dde5aa1aec7ad | 821b08584b804a2ae425f3f7294cc99bd87c9f5b | refs/heads/main | 2023-02-01T02:20:00.421990 | 2020-12-15T10:11:22 | 2020-12-15T10:11:22 | 321,634,613 | 1 | 0 | null | 2020-12-15T10:36:22 | 2020-12-15T10:36:21 | null | UTF-8 | C++ | false | false | 869 | cpp | #include<bits/stdc++.h>
using namespace std;
const int N=10000+10;
const int M=500000+10;
int d[N];
int cnt,head[N],ver[M],nxt[M],edge[M];
void add(int x,int y,int z)
{
ver[++cnt]=y;
nxt[cnt]=head[x];
head[x]=cnt;
edge[cnt]=z;
}
bool v[N];
void spfa(int s)
{
queue<int>q;
v[s]=1;
d[s]=0;
q.push(s);
while(!q.empty())
{
int x=q.front();
v[x]=0;
q.pop();
for(int i=head[x];i;i=nxt[i])
{
int y=ver[i];
int z=edge[i];
if(d[x]+z<d[y])
{
d[y]=d[x]+z;
if(!v[y])
{
v[y]=1;
q.push(y);
}
}
}
}
}
int n,m,s;
int main()
{
scanf("%d%d%d",&n,&m,&s);
for(int i=1;i<=m;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
}
for(int i=1;i<=n;i++)
{
d[i]=2147483647;
}
spfa(s);
for(int i=1;i<=n;i++)
{
printf("%d ",d[i]);
}
return 0;
}
| [
"48145116+hhhnnn2112@users.noreply.github.com"
] | 48145116+hhhnnn2112@users.noreply.github.com |
3e16e695dbe6f4b266a5f77930b499a2699e4e44 | 8cc641da73d9fd9b84c32ccf1c55817f0ca715ad | /src/ADTF_filter/DH_laneAssistant/stdafx.h | 2f61908ad774de996f732f5d6da10d71c9ce56e1 | [] | no_license | jackiecx/AADC_2015_DrivingHorse | 15b451f372ad26e3c8ce127aa5d7a8b18a9b9ad4 | 3e2c9893eafc802c64f19ea31c5d43224c56dbbf | refs/heads/master | 2021-05-30T13:31:28.844918 | 2015-09-12T13:11:36 | 2015-09-12T13:11:36 | 53,236,408 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | h | #ifndef __STD_INCLUDES_HEADER
#define __STD_INCLUDES_HEADER
// ADTF header
#include <adtf_platform_inc.h>
#include <adtf_plugin_sdk.h>
using namespace adtf;
#include <adtf_graphics.h>
using namespace adtf_graphics;
#include <cmath>
// opencv header
#include <opencv/cv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
#include <cstdio>
#endif // __STD_INCLUDES_HEADER
| [
"nicolai.behmann@ims.uni-hannover.de"
] | nicolai.behmann@ims.uni-hannover.de |
cef7d3f837d42392c87c9d2fd20ef02833ba9699 | 8f45bbe83d3cd59e5bf7d05aab5e6f98c0859079 | /TP3/Data/Data.h | f3c9c98a1a3ac0e18c96c9539413beed7ba17b26 | [] | no_license | jesimonbarreto/poo | 261ff3c09d1125c561623cf10d4e60df7cb4cd18 | b2cacc8d8661d6d34b2aa144acaa52a91b2c9420 | refs/heads/main | 2023-03-27T19:32:06.383362 | 2021-03-14T20:00:26 | 2021-03-14T20:00:26 | 347,717,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | h | //CONVERTE ANO E MÊS EM DIAS, SOMA E SUBTRAI DIAS, MESES E ANOS À UMA DATA
#ifndef DATA_H
#define DATA_H
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Data {
int dia,mes,ano;
string formato;
char separador='/';
public:
Data(string formato_data, string data_inserida): formato (formato_data){
int aux = 0;
string Dia_aux, Mes_aux, Ano_aux;
while ((aux<data_inserida.size()) && (data_inserida[aux] != separador)){
Dia_aux.push_back (data_inserida[aux]);
aux++;
}
dia = stoi(Dia_aux);
aux++;
while ( (aux<data_inserida.size()) && (data_inserida[aux] != separador)){
Mes_aux.push_back (data_inserida[aux]);
aux++;
}
mes = stoi(Mes_aux);
aux++;
while ( (aux<data_inserida.size()) && (data_inserida[aux] != separador)){
Ano_aux.push_back (data_inserida[aux]);
aux++;
}
ano = stoi(Ano_aux);
};
string getData(){
stringstream dia_S, mes_S, ano_S;
dia_S << dia;
mes_S << mes;
ano_S << ano;
return dia_S.str() + "/" + mes_S.str() + "/" + ano_S.str();
};
};
#endif | [
"jesimonbarreto@gmail.com"
] | jesimonbarreto@gmail.com |
fc02bfd980cebb0c004353bbd5aa32c7e17b5abd | f17f190d1802050d11add00b505993dd39c32e65 | /branch and bound/Graph Coloring.cpp | 4c8cfb2a626773f71d424b1069f42adb272be56b | [] | no_license | Dristy03/AlgorithmCourse-codes | 2f72c7fadcb7870fe1d93af39c02b009869d3dbb | 521d9f043f914be1050db5a41e21fefa13dca552 | refs/heads/master | 2023-06-18T14:33:56.180248 | 2021-07-13T18:58:39 | 2021-07-13T18:58:39 | 377,518,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,160 | cpp | #include<bits/stdc++.h>
using namespace std;
int vis[100], col[100];
set<int> st[100];
vector <int> graph[100];
int n,m;
void bfs()
{
int cnt=0,i;
int mx=-1,pos=-1;
for(i=1;i<=n;i++)
{
if(vis[i]) {
cnt++;
continue;
}
if((int)st[i].size()>mx)
{
mx=st[i].size();
pos=i;
}
}
if(cnt==n) return;
vis[pos]=1;
if(st[pos].size()==0) {
col[pos]=1;
for(auto it:graph[pos]) {st[it].insert(1);}
bfs();
return;
}
int j=1;
for(auto itt: st[pos]) {
if(itt!=j)
{
col[pos]=j;
for(auto it:graph[pos]) {st[it].insert(j);}
bfs();
return;
}
j++;
}
col[pos]=j;
for(auto it:graph[pos]) {st[it].insert(j);}
bfs();
}
void solve()
{
int x,y;
cin >> n >> m;
for(int i=0;i<m;i++)
{
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
bfs();
for(int i=1;i<=n;i++) cout << col[i] << " ";
cout << endl;
}
int main()
{
int t=1;
while(t--) solve();
}
| [
"anannadristy03@gmail.com"
] | anannadristy03@gmail.com |
e5c9ff336e09930b7cb5178ced32261a25cef764 | 29ff542fc0ed3b45334bdb522bd132e1ac424728 | /tools/z3/src/tactic/arith/lia2pb_tactic.cpp | 178ace7fdfbc2e8978e946dde247d9c4c7241001 | [
"MIT"
] | permissive | diverse-project/samplingfm | e7de9df8b71f5e621ce0d112d57173f1c88d001a | ffd0cd7755eddbe3adfe00cee5ffff2703bb39a6 | refs/heads/master | 2020-04-18T02:58:51.937550 | 2019-01-23T13:08:12 | 2019-01-23T13:08:12 | 167,182,803 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,993 | cpp | /*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
lia2pb_tactic.cpp
Abstract:
Reduce bounded LIA benchmark into 0-1 LIA benchmark.
Author:
Leonardo de Moura (leonardo) 2012-02-07.
Revision History:
--*/
#include "tactic/tactical.h"
#include "tactic/arith/bound_manager.h"
#include "ast/rewriter/th_rewriter.h"
#include "ast/for_each_expr.h"
#include "tactic/generic_model_converter.h"
#include "ast/arith_decl_plugin.h"
#include "ast/expr_substitution.h"
#include "ast/ast_smt2_pp.h"
class lia2pb_tactic : public tactic {
struct imp {
ast_manager & m;
bound_manager m_bm;
arith_util m_util;
expr_dependency_ref_vector m_new_deps;
th_rewriter m_rw;
bool m_produce_models;
bool m_produce_unsat_cores;
bool m_partial_lia2pb;
unsigned m_max_bits;
unsigned m_total_bits;
imp(ast_manager & _m, params_ref const & p):
m(_m),
m_bm(m),
m_util(m),
m_new_deps(m),
m_rw(m, p) {
updt_params(p);
}
void updt_params_core(params_ref const & p) {
m_partial_lia2pb = p.get_bool("lia2pb_partial", false);
m_max_bits = p.get_uint("lia2pb_max_bits", 32);
m_total_bits = p.get_uint("lia2pb_total_bits", 2048);
}
void updt_params(params_ref const & p) {
m_rw.updt_params(p);
updt_params_core(p);
}
bool is_target_core(expr * n, rational & u) {
if (!is_uninterp_const(n))
return false;
rational l; bool s;
if (m_bm.has_lower(n, l, s) &&
m_bm.has_upper(n, u, s) &&
l.is_zero() &&
!u.is_neg() &&
u.get_num_bits() <= m_max_bits) {
return true;
}
return false;
}
bool is_bounded(expr * n) {
rational u;
return is_target_core(n, u);
}
bool is_target(expr * n) {
rational u;
return is_target_core(n, u) && u > rational(1);
}
struct failed {};
struct visitor {
imp & m_owner;
visitor(imp & o):m_owner(o) {}
void throw_failed(expr * n) {
TRACE("lia2pb", tout << "Failed at:\n" << mk_ismt2_pp(n, m_owner.m) << "\n";);
throw failed();
}
void operator()(var * n) {
throw_failed(n);
}
void operator()(app * n) {
family_id fid = n->get_family_id();
if (fid == m_owner.m.get_basic_family_id()) {
// all basic family ops are OK
}
else if (fid == m_owner.m_util.get_family_id()) {
// check if linear
switch (n->get_decl_kind()) {
case OP_LE: case OP_GE: case OP_LT: case OP_GT:
case OP_ADD: case OP_NUM:
return;
case OP_MUL:
if (n->get_num_args() != 2)
throw_failed(n);
if (!m_owner.m_util.is_numeral(n->get_arg(0)))
throw_failed(n);
return;
default:
throw_failed(n);
}
}
else if (is_uninterp_const(n)) {
if (m_owner.m_util.is_real(n)) {
if (!m_owner.m_partial_lia2pb)
throw_failed(n);
}
else if (m_owner.m_util.is_int(n)) {
if (!m_owner.m_partial_lia2pb && !m_owner.is_bounded(n))
throw_failed(n);
}
}
else {
sort * s = m_owner.m.get_sort(n);
if (s->get_family_id() == m_owner.m_util.get_family_id())
throw_failed(n);
}
}
void operator()(quantifier * n) {
throw_failed(n);
}
};
bool check(goal const & g) {
try {
expr_fast_mark1 visited;
visitor proc(*this);
unsigned sz = g.size();
for (unsigned i = 0; i < sz; i++) {
expr * f = g.form(i);
for_each_expr_core<visitor, expr_fast_mark1, true, true>(proc, visited, f);
}
return true;
}
catch (failed) {
return false;
}
}
bool has_target() {
bound_manager::iterator it = m_bm.begin();
bound_manager::iterator end = m_bm.end();
for (; it != end; ++it) {
if (is_target(*it))
return true;
}
return false;
}
bool check_num_bits() {
unsigned num_bits = 0;
rational u;
bound_manager::iterator it = m_bm.begin();
bound_manager::iterator end = m_bm.end();
for (; it != end; ++it) {
expr * x = *it;
if (is_target_core(x, u) && u > rational(1)) {
num_bits += u.get_num_bits();
if (num_bits > m_total_bits)
return false;
}
}
return true;
}
void operator()(goal_ref const & g,
goal_ref_buffer & result) {
SASSERT(g->is_well_sorted());
fail_if_proof_generation("lia2pb", g);
m_produce_models = g->models_enabled();
m_produce_unsat_cores = g->unsat_core_enabled();
result.reset();
tactic_report report("lia2pb", *g);
m_bm.reset(); m_rw.reset(); m_new_deps.reset();
if (g->inconsistent()) {
result.push_back(g.get());
return;
}
m_bm(*g);
TRACE("lia2pb", m_bm.display(tout););
// check if there is some variable to be converted
if (!has_target()) {
// nothing to be done
g->inc_depth();
result.push_back(g.get());
return;
}
if (!check(*g))
throw tactic_exception("goal is in a fragment unsupported by lia2pb");
if (!check_num_bits())
throw tactic_exception("lia2pb failed, number of necessary bits exceeds specified threshold (use option :lia2pb-total-bits to increase threshold)");
ref<generic_model_converter> gmc;
if (m_produce_models) {
gmc = alloc(generic_model_converter, m, "lia2pb");
}
expr_ref zero(m);
expr_ref one(m);
zero = m_util.mk_numeral(rational(0), true);
one = m_util.mk_numeral(rational(1), true);
unsigned num_converted = 0;
expr_substitution subst(m, m_produce_unsat_cores, false);
rational u;
ptr_buffer<expr> def_args;
bound_manager::iterator it = m_bm.begin();
bound_manager::iterator end = m_bm.end();
for (; it != end; ++it) {
expr * x = *it;
if (is_target_core(x, u) && u > rational(1)) {
num_converted++;
def_args.reset();
rational a(1);
unsigned num_bits = u.get_num_bits();
for (unsigned i = 0; i < num_bits; i++) {
app * x_prime = m.mk_fresh_const(nullptr, m_util.mk_int());
g->assert_expr(m_util.mk_le(zero, x_prime));
g->assert_expr(m_util.mk_le(x_prime, one));
if (a.is_one())
def_args.push_back(x_prime);
else
def_args.push_back(m_util.mk_mul(m_util.mk_numeral(a, true), x_prime));
if (m_produce_models)
gmc->hide(x_prime->get_decl());
a *= rational(2);
}
SASSERT(def_args.size() > 1);
expr * def = m_util.mk_add(def_args.size(), def_args.c_ptr());
expr_dependency * dep = nullptr;
if (m_produce_unsat_cores) {
dep = m.mk_join(m_bm.lower_dep(x), m_bm.upper_dep(x));
if (dep != nullptr)
m_new_deps.push_back(dep);
}
TRACE("lia2pb", tout << mk_ismt2_pp(x, m) << " -> " << dep << "\n";);
subst.insert(x, def, nullptr, dep);
if (m_produce_models) {
gmc->add(x, def);
}
}
}
report_tactic_progress(":converted-lia2pb", num_converted);
m_rw.set_substitution(&subst);
expr_ref new_curr(m);
proof_ref new_pr(m);
unsigned size = g->size();
for (unsigned idx = 0; idx < size; idx++) {
expr * curr = g->form(idx);
expr_dependency * dep = nullptr;
m_rw(curr, new_curr, new_pr);
if (m_produce_unsat_cores) {
dep = m.mk_join(m_rw.get_used_dependencies(), g->dep(idx));
m_rw.reset_used_dependencies();
}
if (m.proofs_enabled()) {
new_pr = m.mk_modus_ponens(g->pr(idx), new_pr);
}
g->update(idx, new_curr, new_pr, dep);
}
g->inc_depth();
g->add(gmc.get());
result.push_back(g.get());
TRACE("lia2pb", g->display(tout););
SASSERT(g->is_well_sorted());
}
};
imp * m_imp;
params_ref m_params;
public:
lia2pb_tactic(ast_manager & m, params_ref const & p):
m_params(p) {
m_imp = alloc(imp, m, p);
}
tactic * translate(ast_manager & m) override {
return alloc(lia2pb_tactic, m, m_params);
}
~lia2pb_tactic() override {
dealloc(m_imp);
}
void updt_params(params_ref const & p) override {
m_params = p;
m_imp->updt_params(p);
}
void collect_param_descrs(param_descrs & r) override {
r.insert("lia2pb_partial", CPK_BOOL, "(default: false) partial lia2pb conversion.");
r.insert("lia2pb_max_bits", CPK_UINT, "(default: 32) maximum number of bits to be used (per variable) in lia2pb.");
r.insert("lia2pb_total_bits", CPK_UINT, "(default: 2048) total number of bits to be used (per problem) in lia2pb.");
}
void operator()(goal_ref const & in,
goal_ref_buffer & result) override {
try {
(*m_imp)(in, result);
}
catch (rewriter_exception & ex) {
throw tactic_exception(ex.msg());
}
}
void cleanup() override {
imp * d = alloc(imp, m_imp->m, m_params);
std::swap(d, m_imp);
dealloc(d);
}
};
tactic * mk_lia2pb_tactic(ast_manager & m, params_ref const & p) {
return clean(alloc(lia2pb_tactic, m, p));
}
| [
"mathieu.acher@irisa.fr"
] | mathieu.acher@irisa.fr |
c5bd847e6e252a512c37c27985722904b075a6d5 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_patch_hunk_341.cpp | 4aa29eac7ee095a7e2c410eeeab7f55e586dc0bd | [] | 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 | 2,203 | cpp | if ((rv & APR_POLLERR) || (rv & APR_POLLNVAL)) {
bad++;
err_except++;
start_connect(c);
continue;
}
- if (rv & APR_POLLOUT)
- write_request(c);
+ if (rv & APR_POLLOUT) {
+ if (c->state == STATE_CONNECTING) {
+ apr_pollfd_t remove_pollfd;
+ rv = apr_connect(c->aprsock, destsa);
+ remove_pollfd.desc_type = APR_POLL_SOCKET;
+ remove_pollfd.desc.s = c->aprsock;
+ apr_pollset_remove(readbits, &remove_pollfd);
+ if (rv != APR_SUCCESS) {
+ apr_socket_close(c->aprsock);
+ err_conn++;
+ if (bad++ > 10) {
+ fprintf(stderr,
+ "\nTest aborted after 10 failures\n\n");
+ apr_err("apr_connect()", rv);
+ }
+ c->state = STATE_UNCONNECTED;
+ start_connect(c);
+ continue;
+ }
+ else {
+ c->state = STATE_CONNECTED;
+ write_request(c);
+ }
+ }
+ else {
+ write_request(c);
+ }
+ }
/*
* When using a select based poll every time we check the bits
* are reset. In 1.3's ab we copied the FD_SET's each time
* through, but here we're going to check the state and if the
* connection is in STATE_READ or STATE_CONNECTING we'll add the
* socket back in as APR_POLLIN.
*/
#ifdef USE_SSL
if (ssl != 1)
#endif
- if (c->state == STATE_READ ||
- c->state == STATE_CONNECTING) {
+ if (c->state == STATE_READ) {
apr_pollfd_t new_pollfd;
new_pollfd.desc_type = APR_POLL_SOCKET;
new_pollfd.reqevents = APR_POLLIN;
new_pollfd.desc.s = c->aprsock;
new_pollfd.client_data = c;
apr_pollset_add(readbits, &new_pollfd);
| [
"993273596@qq.com"
] | 993273596@qq.com |
af5a6c8c07df522f748934ecffce6b9b5fea396c | aeb829572bff97b016a6a0b4088d4faf4682102c | /Iterators/Functions/Creating_Multidimensional_Containers.cpp | 2c9efbab9494da07eeb866560863dd633f090453 | [] | no_license | Engineer2B/edX-Advanced-Cpp | 149e2de698be69a1287358308937bf86408aa222 | 0a92fb81755859ff10063d7804ffa012d457812e | refs/heads/master | 2020-03-30T07:54:40.168988 | 2018-10-02T17:04:06 | 2018-10-02T17:04:06 | 150,973,953 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,573 | cpp | #include <vector>
#include <iostream>
using namespace std;
template <size_t dimcount, typename T, size_t vecSize>
class multiVector
{
private:
std::vector<multiVector<dimcount - 1, T, vecSize>> vec;
public:
multiVector() : vec(vecSize)
{
multiVector<dimcount - 1, T, vecSize>();
}
const multiVector<dimcount - 1, T, vecSize> &operator[](int m) const
{
return vec.at(m);
}
multiVector<dimcount - 1, T, vecSize> &operator[](int m)
{
return vec.at(m);
}
};
template <typename T, size_t vecSize>
class multiVector<1, T, vecSize>
{
private:
std::vector<T> vec;
public:
multiVector() : vec(vecSize) {}
T &operator[](const int index)
{
return vec[index];
}
T &operator[](int m) const
{
return vec[m];
}
};
int main()
{
vector<vector<vector<int>>> vec; //3 dim vec
//Fill vectors
for (int i = 0; i < 5; i++)
{
vector<vector<int>> vv;
for (int j = 0; j < 10; j++)
{
vector<int> ve;
for (int t = 0; t < 3; t++)
{
ve.push_back(t);
}
vv.push_back(ve);
}
vec.push_back(vv);
}
//Print contents
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 10; j++)
{
for (int t = 0; t < 3; t++)
{
cout << " element index " << t << " is " << vec[i][j][t] << "\n";
}
}
}
cout << "\n\n";
multiVector<4, int, 5> vec4;
cout << "accessing vec4[1][2][3][4][4] = 7 \n";
vec4[1][2][3][4] = 7;
cout << "reading vec4[1][2][3][4][4] is ";
cout << vec4[1][2][3][4] << "\n";
//Just to prove good for N dimensions 100*100=10,000 vectors !!!.
multiVector<4, int, 100> bigVec;
cout << "\n\n";
return 0;
} | [
"borisbreuer1@gmail.com"
] | borisbreuer1@gmail.com |
c90ed272f2474869140c82ce79265bb824c46681 | c2771549f2eba083d69467d4355cc56015d38248 | /cpp/jan2017_mcs360/wk2/fr/use_phonebook2.cpp | 61ba5a20c78ac1a7a3f73821adb19d3ffa5284b1 | [] | no_license | usapes2/evening_coding | 173726329ba2ad3f0e1f2bdf4a33607889c2bbb4 | 6e410e618cb35bbae89f439a655d1e58852ee740 | refs/heads/master | 2021-01-24T03:43:27.230307 | 2018-08-26T23:36:28 | 2018-08-26T23:36:28 | 122,902,484 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp | /*// L-5 MCS 360 Fri 8 Sep 2017 : use_phonebook2.cpp
deallocation as a variation of the other program use_phonebook.cpp.
A possible application could be to keep a backup copy of the
phone book when we provide a delete operation.
For this program to execute properly, the file phonebook_data.txt
must be in the same folder as the executable.
An example of typical content for the file phonebook_data.txt is
in the three lines below (exclude the blank line):
2
111-222-4444 Elliot Koffman
333-666-9999 Paul Wolfgang
*/
#include <iostream>
#include "phonebook.h"
using namespace std;
int main ( int argc, char* argv[] )
{
PhoneBook *b;
cout << "welcome to our phone book" << endl;
cout << "reading data from file ..." << endl;
b = new PhoneBook;
int n = b->length();
cout << "number of entries : " << n << endl;
if(argc == 1)
for(int k=0; k<n; k++)
cout << " entry " << k << " : "
<< (*b)[k] << endl;
else
{
string new_entry;
cout << "give new entry : ";
getline(cin,new_entry);
b->add(new_entry);
}
b->~PhoneBook();
return 0;
}
| [
"usapeshka@gmail.com"
] | usapeshka@gmail.com |
938dd44f5d24beaef4389b291c52c2ace486760b | 11105d96f64b65ea7969ec6986db4f18c4cf65f7 | /src/cubemap/ReflectorShader.cpp | 720e8b62c53863fac6817a48bfdad467c173d265 | [
"LicenseRef-scancode-public-domain",
"Unlicense",
"MIT"
] | permissive | boonto/magnum-examples | 93468e905c036e8b08f0967af6fb04e41ab1abe8 | 3cfbbe5d3c6a244200788a58c950a9e57eaba166 | refs/heads/master | 2020-03-30T05:29:04.904081 | 2018-09-25T11:21:30 | 2018-09-25T11:21:55 | 150,801,666 | 0 | 0 | Unlicense | 2018-09-28T22:45:53 | 2018-09-28T22:45:53 | null | UTF-8 | C++ | false | false | 3,032 | cpp | /*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 —
Vladimír Vondruš <mosra@centrum.cz>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
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 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 "ReflectorShader.h"
#include <Corrade/Utility/Resource.h>
#include <Magnum/GL/CubeMapTexture.h>
#include <Magnum/GL/Shader.h>
#include <Magnum/GL/Texture.h>
#include <Magnum/GL/Version.h>
namespace Magnum { namespace Examples {
namespace {
enum: Int {
TextureLayer = 0,
TarnishTextureLayer = 1
};
}
ReflectorShader::ReflectorShader() {
Utility::Resource rs("data");
GL::Shader vert(GL::Version::GL330, GL::Shader::Type::Vertex);
GL::Shader frag(GL::Version::GL330, GL::Shader::Type::Fragment);
vert.addSource(rs.get("ReflectorShader.vert"));
frag.addSource(rs.get("ReflectorShader.frag"));
CORRADE_INTERNAL_ASSERT_OUTPUT(GL::Shader::compile({vert, frag}));
attachShaders({vert, frag});
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
_transformationMatrixUniform = uniformLocation("transformationMatrix");
_normalMatrixUniform = uniformLocation("normalMatrix");
_projectionMatrixUniform = uniformLocation("projectionMatrix");
_cameraMatrixUniform = uniformLocation("cameraMatrix");
_reflectivityUniform = uniformLocation("reflectivity");
_diffuseColorUniform = uniformLocation("diffuseColor");
setUniform(uniformLocation("textureData"), TextureLayer);
setUniform(uniformLocation("tarnishTextureData"), TarnishTextureLayer);
}
ReflectorShader& ReflectorShader::setTexture(GL::CubeMapTexture& texture) {
texture.bind(TextureLayer);
return *this;
}
ReflectorShader& ReflectorShader::setTarnishTexture(GL::Texture2D& texture) {
texture.bind(TarnishTextureLayer);
return *this;
}
}}
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
d000ca506fe574a2c2200f4dac8754cb3192cfe1 | 2129168436f603b4e54b7a31662b620e64d681de | /Falcor/Framework/Source/API/BlendState.h | 6e7b4c84221be59b279d98e96d6696e4bff46733 | [
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"CC-BY-NC-SA-3.0",
"CC-BY-4.0"
] | permissive | FisherDai/GettingStartedWithRTXRayTracing | 31094b8350acb85113d5a4a2bf212208a080177a | 9d13784985913a1c09095c5027c9a798b1f9c64c | refs/heads/master | 2020-04-01T18:02:56.151540 | 2018-10-12T14:39:00 | 2018-10-12T14:39:00 | 153,468,128 | 1 | 0 | BSD-3-Clause | 2018-10-17T14:10:03 | 2018-10-17T14:10:02 | null | UTF-8 | C++ | false | false | 9,611 | h | /***************************************************************************
# Copyright (c) 2015, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#pragma once
#include "glm/vec4.hpp"
namespace Falcor
{
/** Blend state
*/
class BlendState : public std::enable_shared_from_this<BlendState>
{
public:
using SharedPtr = std::shared_ptr<BlendState>;
using SharedConstPtr = std::shared_ptr<const BlendState>;
/** Defines how to combine the blend inputs
*/
enum class BlendOp
{
Add, ///< Add src1 and src2
Subtract, ///< Subtract src1 from src2
ReverseSubtract, ///< Subtract src2 from src1
Min, ///< Find the minimum between the sources (per-channel)
Max ///< Find the maximum between the sources (per-channel)
};
/** Defines how to modulate the fragment-shader and render-target pixel values
*/
enum class BlendFunc
{
Zero, ///< (0, 0, 0, 0)
One, ///< (1, 1, 1, 1)
SrcColor, ///< The fragment-shader output color
OneMinusSrcColor, ///< One minus the fragment-shader output color
DstColor, ///< The render-target color
OneMinusDstColor, ///< One minus the render-target color
SrcAlpha, ///< The fragment-shader output alpha value
OneMinusSrcAlpha, ///< One minus the fragment-shader output alpha value
DstAlpha, ///< The render-target alpha value
OneMinusDstAlpha, ///< One minus the render-target alpha value
BlendFactor, ///< Constant color, set using Desc#SetBlendFactor()
OneMinusBlendFactor, ///< One minus constant color, set using Desc#SetBlendFactor()
SrcAlphaSaturate, ///< (f, f, f, 1), where f = min(fragment shader output alpha, 1 - render-target pixel alpha)
Src1Color, ///< Fragment-shader output color 1
OneMinusSrc1Color, ///< One minus fragment-shader output color 1
Src1Alpha, ///< Fragment-shader output alpha 1
OneMinusSrc1Alpha ///< One minus fragment-shader output alpha 1
};
/** Descriptor used to create new blend-state
*/
class Desc
{
public:
Desc();
friend class BlendState;
/** Set the constant blend factor
\param[in] factor Blend factor
*/
Desc& setBlendFactor(const glm::vec4& factor) { mBlendFactor = factor; return *this; }
/** Enable/disable independent blend modes for different render target. Only used when multiple render-targets are bound.
\param[in] enabled True If false, will use RenderTargetDesc[0] for all the bound render-targets. Otherwise, will use the entire RenderTargetDesc[] array.
*/
Desc& setIndependentBlend(bool enabled) { mEnableIndependentBlend = enabled; return *this; }
/** Set the blend parameters
\param[in] rtIndex The RT index to set the parameters into. If independent blending is disabled, only the index 0 is used.
\param[in] rgbOp Blend operation for the RGB channels
\param[in] alphaOp Blend operation for the alpha channels
\param[in] srcRgbFunc Blend function for the fragment-shader output RGB channels
\param[in] dstRgbFunc Blend function for the render-target RGB channels
\param[in] srcAlphaFunc Blend function for the fragment-shader output alpha channel
\param[in] dstAlphaFunc Blend function for the render-target alpha channel
*/
Desc& setRtParams(uint32_t rtIndex, BlendOp rgbOp, BlendOp alphaOp, BlendFunc srcRgbFunc, BlendFunc dstRgbFunc, BlendFunc srcAlphaFunc, BlendFunc dstAlphaFunc);
/** Enable/disable blending for a specific render-target. If independent blending is disabled, only the index 0 is used.
*/
Desc& setRtBlend(uint32_t rtIndex, bool enable) { mRtDesc[rtIndex].blendEnabled = enable; return *this; }
/** Enable/disable alpha-to-coverage
\param[in] enabled True to enable alpha-to-coverage, false to disable it
*/
Desc& setAlphaToCoverage(bool enabled) { mAlphaToCoverageEnabled = enabled; return *this; }
/** Set color write-mask
*/
Desc& setRenderTargetWriteMask(uint32_t rtIndex, bool writeRed, bool writeGreen, bool writeBlue, bool writeAlpha);
struct RenderTargetDesc
{
bool blendEnabled = false;
BlendOp rgbBlendOp = BlendOp::Add;
BlendOp alphaBlendOp = BlendOp::Add;
BlendFunc srcRgbFunc = BlendFunc::One;
BlendFunc srcAlphaFunc = BlendFunc::One;
BlendFunc dstRgbFunc = BlendFunc::Zero;
BlendFunc dstAlphaFunc = BlendFunc::Zero;
struct WriteMask
{
bool writeRed = true;
bool writeGreen = true;
bool writeBlue = true;
bool writeAlpha = true;
};
WriteMask writeMask;
};
protected:
std::vector<RenderTargetDesc> mRtDesc;
bool mEnableIndependentBlend = false;
bool mAlphaToCoverageEnabled = false;
glm::vec4 mBlendFactor = glm::vec4(0, 0, 0, 0);
};
/** Create a new blend state object
\param[in] Desc Blend state descriptor
*/
static BlendState::SharedPtr create(const Desc& desc);
~BlendState();
/** Get the constant blend factor color
*/
const glm::vec4& getBlendFactor() const { return mDesc.mBlendFactor; }
/** Get the RGB blend operation
*/
BlendOp getRgbBlendOp(uint32_t rtIndex) const { return mDesc.mRtDesc[rtIndex].rgbBlendOp; }
/** Get the alpha blend operation
*/
BlendOp getAlphaBlendOp(uint32_t rtIndex) const { return mDesc.mRtDesc[rtIndex].alphaBlendOp; }
/** Get the fragment-shader RGB blend func
*/
BlendFunc getSrcRgbFunc(uint32_t rtIndex) const { return mDesc.mRtDesc[rtIndex].srcRgbFunc; }
/** Get the fragment-shader alpha blend func
*/
BlendFunc getSrcAlphaFunc(uint32_t rtIndex) const { return mDesc.mRtDesc[rtIndex].srcAlphaFunc; }
/** Get the render-target RGB blend func
*/
BlendFunc getDstRgbFunc(uint32_t rtIndex) const { return mDesc.mRtDesc[rtIndex].dstRgbFunc; }
/** Get the render-target alpha blend func
*/
BlendFunc getDstAlphaFunc(uint32_t rtIndex) const { return mDesc.mRtDesc[rtIndex].dstAlphaFunc; }
/** Check if blend is enabled
*/
bool isBlendEnabled(uint32_t rtIndex) const { return mDesc.mRtDesc[rtIndex].blendEnabled; }
/** Check if alpha-to-coverage is enabled
*/
bool isAlphaToCoverageEnabled() const { return mDesc.mAlphaToCoverageEnabled; }
/** Check if independent blending is enabled
*/
bool isIndependentBlendEnabled() const {return mDesc.mEnableIndependentBlend;}
/** Get a render-target descriptor
*/
const Desc::RenderTargetDesc& getRtDesc(size_t rtIndex) const { return mDesc.mRtDesc[rtIndex]; }
/** Get the render-target array size
*/
uint32_t getRtCount() const { return (uint32_t)mDesc.mRtDesc.size(); }
/** Get the API handle
*/
const BlendStateHandle& getApiHandle() const;
private:
BlendState(const Desc& Desc) : mDesc(Desc) {}
const Desc mDesc;
BlendStateHandle mApiHandle;
};
}
| [
"ehaines@nvidia.com"
] | ehaines@nvidia.com |
7638eb804e3fedb715ba0547aebf359cbc6dea68 | 8320bf99d5f67cdf785c4228fa786f17b11151bf | /cpp/design-patterns/strategy/quack-behaviors/quack-behavior.h | 6e019817d71ba4a19f80f1a98f0d5b1f79afa580 | [] | no_license | timpeihunghsieh/public-repo | 95d10eb1bafdb0e2287fa66a3f5618100b4d7c64 | 188a6c283a39e630221880c3f4d2fa66d55f5ba7 | refs/heads/main | 2023-02-08T14:56:14.050229 | 2020-12-23T22:11:37 | 2020-12-23T22:11:37 | 315,752,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 362 | h | #ifndef CPP_DESIGN_PATTERNS_STRATEGY_QUACK_BEHAVIORS_QUACK_BEHAVIOR_H_
#define CPP_DESIGN_PATTERNS_STRATEGY_QUACK_BEHAVIORS_QUACK_BEHAVIOR_H_
#include<iostream>
namespace strategy_pattern {
class QuackBehavior {
public:
virtual void Quack() = 0;
};
} // namespace strategy_pattern
#endif // CPP_DESIGN_PATTERNS_STRATEGY_QUACK_BEHAVIORS_QUACK_BEHAVIOR_H_ | [
"kubeuser@gmail.com"
] | kubeuser@gmail.com |
983dd1f4900ff3c7eddcee67984da9d2171ac577 | 22b633c43a0d5b2cd481711a94f27b858fe9a491 | /boggle/board.cpp | 5bed7f30aba489e88a00f27b745a7eeb3dc6bfe1 | [] | no_license | MacroGu/googleTestDemo | 069da09668a485d72b3b75e757f02138747913ec | 5a8ab4ca807c4620719721e77fccbe184a7e6af9 | refs/heads/master | 2021-05-06T08:48:18.498444 | 2017-12-14T06:58:39 | 2017-12-14T06:58:39 | 114,061,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,671 | cpp | #include "board.h"
Board::Board()
{
std::get<0>(NEIGHBORS_RANGE) = -1;
std::get<1>(NEIGHBORS_RANGE) = 0;
std::get<2>(NEIGHBORS_RANGE) = 1;
}
Board::~Board()
{
nodesMap.clear();
}
void Board::AddNode(const BoardID& id, const std::string & letter)
{
if (!&id)
{
std::cout << "error id is null " << std::endl;
return;
}
if (IsALetter(letter))
{
BoardNodes node;
std::string cLetter = letter;
std::transform(cLetter.begin(), cLetter.end(), cLetter.begin(), tolower);
node.cLetter = cLetter;
node.neighborsList.clear();
auto result = nodesMap.insert(std::make_pair(id, node));
if (false == result.second)
{
std::cout << "insert value failed id first: " << id.first
<< " ,second: " << id.second << " , letter: " << letter << std::endl;
return;
}
AddNeighbors(id);
}
else
{
std::cout << "board can only have letters as nodes" << std::endl;
}
}
void Board::FileToBoard(const std::string & boardFilePath)
{
// board file configuration
std::ifstream boardFile;
boardFile.exceptions(std::ifstream::badbit | std::ifstream::failbit);
boardFile.open(boardFilePath);
if (!boardFile.is_open())
{
std::cout << "can not open boardFilePath: " << boardFilePath << std::endl;
return;
}
boardFile.exceptions(std::ifstream::badbit);
std::string oneLine;
uint64_t i = 0;
uint64_t j = 0;
while (std::getline(boardFile, oneLine))
{
std::istringstream buf(oneLine);
std::istream_iterator<std::string> beg(buf), end;
std::vector<std::string> tokens(beg, end); // done!
for (auto& s: tokens )
{
if (IsALetter(s))
{
AddNode(BoardID(i,j), s);
}
else
{
std::cout << s << " is not a letter error! " << std::endl;
}
++j;
}
++i;
j = 0;
}
boardFile.close();
}
bool Board::CheckForWord(const std::string & word)
{
std::string tempWord = word;
while (tempWord.find("qu") != std::string::npos)
{
tempWord.replace(tempWord.find("qu"), strlen("qu"), "q");
}
for (auto nodesMapIter = nodesMap.begin(); nodesMapIter != nodesMap.end(); nodesMapIter++)
{
std::deque<BoardID> queue;
std::list<BoardID> path, neighbors;
auto TempNode = nodesMapIter->first;
queue.push_back(TempNode);
while (queue.size() > 0)
{
auto id = queue.front();
queue.pop_front();
BoardNodes node;
if (!GetNode(id, node))
{
std::cout << "can not find this id, first: " << id.first << " second: "
<< id.second << std::endl;
break;
}
if (node.cLetter.at(0) == tempWord.at(path.size())) // cLetter just one char
{
if (std::find(path.begin(), path.end(), id) != path.end()) continue; // means this char in path
path.push_back(id);
if (tempWord.length() == path.size())
return true;
if (!GetNeighbors(id, neighbors))
{
std::cout << "GetNeighbors can not find this id, first: " << id.first << " second: "
<< id.second << std::endl;
}
queue.insert(queue.begin(), neighbors.crbegin(), neighbors.crend());
}
else if (neighbors.size() > 0)
{
neighbors.pop_back();
}
if (neighbors.size() == 0 && path.size() > 0)
{
auto bad_id = path.back();
path.pop_back();
queue.clear();
if (path.size() > 0)
{
if (!GetNeighbors(path.back(), neighbors))
{
std::cout << "get neighbors failed, first: " << path.back().first
<< " second: " << path.back().second << std::endl;
}
queue.insert(queue.begin(), neighbors.crbegin(), neighbors.crend());
auto delID = std::find(queue.begin(), queue.end(), bad_id);
if (delID != queue.end())
{
queue.erase(delID);
}
}
}
}
}
return false;
}
bool Board::GetNeighbors(const BoardID& id, std::list<BoardID>& neighorsNode)
{
if (!&id)
{
std::cout << "id is null " << std::endl;
return false;
}
neighorsNode.clear();
BoardNodes boardNode ;
if (!GetNode(id, boardNode))
{
std::cout << "can not find this id, first : " << id.first
<< " second : " << id.second << std::endl;
return false;
}
std::for_each(boardNode.neighborsList.begin(),
boardNode.neighborsList.end(),
[&](const auto& oneNeighbor) { neighorsNode.push_back(oneNeighbor.first);});
return true;
}
bool Board::GetNode(const BoardID & id, BoardNodes& boardNodes)
{
if (!&id)
{
std::cout << "id is null " << std::endl;
return false;
}
auto boardNode = nodesMap.find(id);
if (boardNode != nodesMap.end())
{
boardNodes = boardNode->second;
return true;
}
else
{
std::cout << "can not find this id, first : " << id.first
<< " second : " << id.second << std::endl;
return false;
}
}
bool Board::GetNodes(std::map<BoardID, BoardNodes>& nodesMap)
{
nodesMap = this->nodesMap;
return true;
}
void Board::AddNeighbors(const BoardID & id)
{
if (!&id)
{
std::cout << "error id is null " << std::endl;
return;
}
auto owner = nodesMap.find(id);
if (owner == nodesMap.end())
{
std::cout << "can not find this id, first: " << id.first
<< " , second: " << id.second << std::endl;
return;
}
for_each(NEIGHBORS_RANGE, [&](const auto& i)
{
int32_t r = i + id.first;
for_each(NEIGHBORS_RANGE, [&](const auto& j)
{
int32_t c = j + id.second;
if (BoardID(r, c) != id)
{
auto neighbor = nodesMap.find(BoardID(r, c));
if (neighbor != nodesMap.end())
{
// merge repeat, if not exist, create it
owner->second.neighborsList[BoardID(r, c)] = 1;
neighbor->second.neighborsList[id] = 1;
}
}
});
});
}
bool Board::IsALetter(const std::string & letter)
{
if (letter.length() != 1)
{
std::cout << "letter length should be 1, letter is :" << letter << std::endl;
return false;
}
return isalpha(letter.at(0));
}
| [
"macrogu@qq.com"
] | macrogu@qq.com |
41ab2cea5b749b8db9d647996dfe4d58c78dd08a | 2e7097f6af8ff4c176ffcac8cc776df9d432d3aa | /algo/find_missing_positive_unittest.cc | 88daedf894f018515ffa62dc51dbbc56d4f23f05 | [] | no_license | morefreeze/leetcode | 9ce8c49d83c3a554ce4a4e94b0a43d219d4e7769 | 9118c11d1facaa977fb6ecbd2f7cb610a30f76af | refs/heads/master | 2022-05-20T21:55:04.914140 | 2022-05-07T06:27:13 | 2022-05-07T06:27:13 | 36,644,202 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,626 | cc | #include <gtest/gtest.h>
#include "find_missing_positive.cpp"
class FindMissingPositiveTest: public testing::Test{
protected:
Solution sol;
};
TEST_F(FindMissingPositiveTest, Small){
int a[] = {1,2,0};
VI nums(a, a+sizeof(a)/sizeof(a[0]));
EXPECT_EQ(3, sol.firstMissingPositive(nums));
}
TEST_F(FindMissingPositiveTest, Small2){
int a[] = {3,4,-1,1};
VI nums(a, a+sizeof(a)/sizeof(a[0]));
EXPECT_EQ(2, sol.firstMissingPositive(nums));
}
TEST_F(FindMissingPositiveTest, Small3){
int a[] = {3,4,-1,2};
VI nums(a, a+sizeof(a)/sizeof(a[0]));
EXPECT_EQ(1, sol.firstMissingPositive(nums));
}
TEST_F(FindMissingPositiveTest, NumBigAll){
int a[] = {0,-1,999,1000};
VI nums(a, a+sizeof(a)/sizeof(a[0]));
EXPECT_EQ(1, sol.firstMissingPositive(nums));
}
TEST_F(FindMissingPositiveTest, NumBig){
int a[] = {3,4,999,1};
VI nums(a, a+sizeof(a)/sizeof(a[0]));
EXPECT_EQ(2, sol.firstMissingPositive(nums));
}
TEST_F(FindMissingPositiveTest, Same){
int a[] = {1,1};
VI nums(a, a+sizeof(a)/sizeof(a[0]));
EXPECT_EQ(2, sol.firstMissingPositive(nums));
}
TEST_F(FindMissingPositiveTest, Order){
int a[] = {0,1,2};
VI nums(a, a+sizeof(a)/sizeof(a[0]));
EXPECT_EQ(3, sol.firstMissingPositive(nums));
}
TEST_F(FindMissingPositiveTest, RunTime){
int a[] = {0,2,2,4,0,3,2,4,0};
VI nums(a, a+sizeof(a)/sizeof(a[0]));
EXPECT_EQ(1, sol.firstMissingPositive(nums));
}
TEST_F(FindMissingPositiveTest, RunTime2){
int a[] = {10,9,8,7,6,5,4,3,2,999};
VI nums(a, a+sizeof(a)/sizeof(a[0]));
EXPECT_EQ(1, sol.firstMissingPositive(nums));
}
| [
"liuchenxing@acfun.tv"
] | liuchenxing@acfun.tv |
ceac61c13f51a35e310ce1fc2334186f534305cf | 51ab43d536e5e3b963a62601acae52abcf8b326d | /Home/else/binary_search.cpp | 570c111323cdad76d27b3b1d2682f0180efda71d | [] | no_license | NikitaGrebeniuk/cs50 | 1ca740508113ae9978059ef20aa96ad7485d5b7b | e4349ecd540e4c3185318e7b8dbc8253a07cfdf8 | refs/heads/master | 2020-04-17T14:28:55.002184 | 2019-03-31T13:13:23 | 2019-03-31T13:13:23 | 151,932,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool m (int i,int j) { return (i<j); }
int main () {
int a[] = {1,2,3,4,5,4,3,2,1};
vector<int> v(a,a+9);
sort (v.begin(), v.end());
int x;
cin >> x;
int g;
cin >> g;
cout << "Ищу переменную " << x << endl;
if (binary_search (v.begin(), v.end(), g))
cout << "Найдено!\n";
else
cout << "Не найдено.\n";
sort (v.begin(), v.end(), m);
cout << "Ищу переменную " << g << endl;
if (binary_search (v.begin(), v.end(), x, m))
cout << "Найдено!\n";
else
cout << "Не найдено.\n";
return 0;
} | [
"user.email"
] | user.email |
5aeb46bbfaf0d5fd84cc4d90c7d9b7c7d89aa113 | b9eed0d5df4aada9a98da8332e7df05c03326778 | /src/week_11/beach.cpp | 410799cf59e4b3567251b90ff9e8753a831d6218 | [] | no_license | dballesteros7/Algolab-HS13 | 2210ba4b466a525f67c6f49603fed6581a7f07c3 | 6206bbbb9dfdad69e294cdc90e94ce45751f0666 | refs/heads/master | 2020-12-30T10:36:39.960057 | 2014-07-31T08:36:19 | 2014-07-31T08:36:19 | 13,175,500 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,292 | cpp | #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, pair<int,int> > Triplet;
struct compare_strict{
bool operator()(const Triplet& a, const Triplet& b) const{
if(a.first > b.first){
return true;
} else if (a.first == b.first){
if(a.second.first < b.second.first){
return true;
} else if(a.second.first == b.second.first){
if(a.second.second < b.second.second){
return true;
}
}
}
return false;
}
};
int main(){
int n;
cin >> n;
for(int i = 0; i < n; ++i){
int p;
cin >> p;
vector<int> parasols(p);
for(int j = 0; j < p; ++j){
cin >> parasols[j];
}
sort(parasols.begin(), parasols.end());
bool stop = false;
int left_parasol, right_parasol;
int bar_loc;
vector< Triplet > bar_locations;
left_parasol = 0;
right_parasol = 0;
bar_loc = 0;
while(!stop){
bool record = false;
while(!record){
right_parasol++;
if(right_parasol == p || parasols[right_parasol] - parasols[left_parasol] > 200){
record = true;
right_parasol--;
}
}
if((parasols[left_parasol] + parasols[right_parasol]) % 2 == 0){
bar_loc = (parasols[left_parasol] + parasols[right_parasol])/2;
int locations = right_parasol - left_parasol + 1;
int max_distance = max(bar_loc - parasols[left_parasol], parasols[right_parasol] - bar_loc);
bar_locations.push_back(Triplet(locations, pair<int,int>(max_distance, bar_loc)));
} else {
bar_loc = (parasols[left_parasol] + parasols[right_parasol] + 1)/2;
int locations = right_parasol - left_parasol + 1;
int max_distance = max(bar_loc - parasols[left_parasol], parasols[right_parasol] - bar_loc);
bar_locations.push_back(Triplet(locations, pair<int,int>(max_distance, bar_loc)));
bar_loc = (parasols[left_parasol] + parasols[right_parasol] - 1)/2;
locations = right_parasol - left_parasol + 1;
max_distance = max(bar_loc - parasols[left_parasol], parasols[right_parasol] - bar_loc);
bar_locations.push_back(Triplet(locations, pair<int,int>(max_distance, bar_loc)));
}
if(right_parasol == p - 1){
stop = true;
}
left_parasol++;
}
sort(bar_locations.begin(), bar_locations.end(), compare_strict());
int max_locations = bar_locations[0].first;
int min_distance = bar_locations[0].second.first;
cout << max_locations << " " << min_distance << "\n";
cout << bar_locations[0].second.second;
for(int j = 1; j < bar_locations.size(); ++j){
if(bar_locations[j].first < max_locations || bar_locations[j].second.first > min_distance){
break;
}
cout << " " << bar_locations[j].second.second;
}
cout << "\n";
}
}
| [
"diegob@student.ethz.ch"
] | diegob@student.ethz.ch |
35c5e773844e0392fdd6c68d10e31d3467800427 | e47653f7bc03b901e9d8223e19155eac173c2bc8 | /main.cpp | c1b7dc3985c7f1450e7579ad14fdffc1e223a06f | [] | no_license | aslindamood/SudokuBacktracking | 28f157b3b821069050eba76a44a71d433448ce6d | 21b5c031c8a259c46b136731c038273eab2388ea | refs/heads/master | 2020-03-12T08:14:13.774271 | 2019-01-13T23:32:28 | 2019-01-13T23:32:28 | 130,523,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 394 | cpp | // Allister Lindamood - aslindamood@alaska.edu
// Peter Trinh - pptrinh@alaska.edu
//
// Homework assignment 4
// 11/16/17
//
// main.cpp
// A test routine for the sudoku CSP-solving algorithms
//
#include "puzzle.hpp"
int main()
{
Puzzle puzzle;
puzzle.readFromFile("tests/17-1.txt");
puzzle.print();
puzzle.solve();
puzzle.print();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
2bf9e02b23b7c2b8398aafbf1a329dd0082af0c9 | 6f05f7d5a67b6bb87956a22b988067ec772ba966 | /data/train/cpp/26b9c1adf36f4da552909a85cbf3bdd3c51f5fbeUnknownChunk.h | 26b9c1adf36f4da552909a85cbf3bdd3c51f5fbe | [
"MIT"
] | permissive | harshp8l/deep-learning-lang-detection | 93b6d24a38081597c610ecf9b1f3b92c7d669be5 | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | refs/heads/master | 2020-04-07T18:07:00.697994 | 2018-11-29T23:21:23 | 2018-11-29T23:21:23 | 158,597,498 | 0 | 0 | MIT | 2018-11-21T19:36:42 | 2018-11-21T19:36:41 | null | UTF-8 | C++ | false | false | 513 | h | /*
* File: UnknownChunk.h
* Author: rd
*
* Created on 2 Июнь 2010 г., 22:35
*/
#ifndef _UNKNOWNCHUNK_H
#define _UNKNOWNCHUNK_H
#include "WaveChunk.h"
class UnknownChunk: public WaveChunk {
public:
UnknownChunk();
UnknownChunk(const UnknownChunk& orig);
virtual ~UnknownChunk();
virtual char *getData();
protected:
virtual void loadData(std::ifstream& in);
virtual void saveData(std::ofstream& out)const;
private:
char *data;
};
#endif /* _UNKNOWNCHUNK_H */
| [
"aliostad+github@gmail.com"
] | aliostad+github@gmail.com |
484c6ba8361f5e9ffa21d9119dd51f15ea4bc2aa | 504fa56796d605107ac43c8a43a794b338079d75 | /hmailserver/source/Server/COM/InterfaceDeliveryQueue.h | 57c3b347b78082f92184795fa7e670ddb59c3cc9 | [] | no_license | bighossbiz/hmailserver | 5877796f95d2c19c34744fdbefb06d819c58410d | 39506daf6b95e554bd3153206eaaf0bd22affdf1 | refs/heads/master | 2021-01-21T04:04:09.604030 | 2014-08-31T13:15:06 | 2014-08-31T13:15:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,268 | h | // Copyright (c) 2010 Martin Knafve / hMailServer.com.
// http://www.hmailserver.com
#pragma once
#include "../hMailServer/resource.h" // main symbols
#include "../hMailServer/hMailServer.h"
// InterfaceDeliveryQueue
class ATL_NO_VTABLE InterfaceDeliveryQueue :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<InterfaceDeliveryQueue, &CLSID_DeliveryQueue>,
public IDispatchImpl<IInterfaceDeliveryQueue, &IID_IInterfaceDeliveryQueue, &LIBID_hMailServer, /*wMajor =*/ 1, /*wMinor =*/ 0>,
public HM::COMAuthenticator
{
public:
InterfaceDeliveryQueue()
{
}
void SetAuthentication(shared_ptr<HM::COMAuthentication> pAuthentication);
DECLARE_REGISTRY_RESOURCEID(IDR_INTERFACEDELIVERYQUEUE)
BEGIN_COM_MAP(InterfaceDeliveryQueue)
COM_INTERFACE_ENTRY(IInterfaceDeliveryQueue)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct()
{
return S_OK;
}
void FinalRelease()
{
}
public:
STDMETHOD(Clear());
STDMETHOD(ResetDeliveryTime)(hyper iMessageID);
STDMETHOD(Remove)(hyper iMessageID);
STDMETHOD(StartDelivery());
private:
shared_ptr<HM::COMAuthentication> authentication_;
};
OBJECT_ENTRY_AUTO(__uuidof(DeliveryQueue), InterfaceDeliveryQueue)
| [
"knafve@gmail.com"
] | knafve@gmail.com |
7a3d577fe7f9323c93c661a8ac2616aea3b99e92 | d4b4b3f23f7e610507d92f12475b0997e06b5517 | /2ndSem/Lab4/filesystem.h | ca930ee2ee69c1acc02ccbdec946fdd15ebc0206 | [] | no_license | starquell/labs | 2725ce8101d7379c643651a21d88f2eb938bebb7 | 8288a9c2d8a6a0f0ee2ba5fddb3ca28c503766c5 | refs/heads/master | 2020-04-18T18:42:14.055434 | 2020-04-17T14:18:54 | 2020-04-17T14:18:54 | 167,692,397 | 12 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,741 | h | #ifndef FILESYSTEM_H
#define FILESYSTEM_H
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <algorithm>
#include <optional>
#include <limits>
#include <regex>
#include "directory.h"
#include "file.h"
struct FilterForm {
std::optional <std::regex> name;
size_t minSize;
std::optional <size_t> maxSize;
FilterForm (std::optional <std::regex> _name, std::optional <size_t> _maxSize, size_t _minSize)
: name (std::move (_name)),
minSize (_minSize),
maxSize (_maxSize)
{}
};
class Filesystem { // Task 1
Directory *mRoot;
public:
Filesystem ()
: mRoot (new Directory ("home")) {}
explicit Filesystem (std::string_view startName)
: mRoot(new Directory(startName)) {}
Directory* root() const {
return mRoot;
}
Directory* findDirectory (std::string path) const { // part of task 2
using namespace boost::algorithm;
std::vector<std::string> directories;
split (directories, path, is_any_of("/"));
auto temp = mRoot;
for (const auto &i : directories) {
for (const auto &j : temp->children)
if (j->name == i) {
temp = j;
break;
}
}
if (directories.back() != temp->name || directories.empty())
temp = nullptr;
return temp;
}
File* findFile (std::string path) const { // part of task 2
size_t point = path.rfind('/');
auto filename = path.substr (point + 1, path.size());
path.resize(point);
auto ourDir = findDirectory(path);
for (auto &i : ourDir->files)
if (i->name() == filename)
return i;
return nullptr;
}
std::vector <std::string> findByName (std::string_view name) const { // part of task 2
std::vector <std::string> paths;
mRoot->findByNameHelper (name, paths);
return paths;
}
void createDir (std::string path, std::string_view _name) { // part of task 3
findDirectory(std::move(path))->createDir(_name);
}
void createFile (std::string path, std::string_view _name, size_t size) { // part of task 3
findDirectory (std::move(path))->createFile(_name, size);
}
Directory* deleteDir (std::string_view path) { // task 13
const auto foundDir = findDirectory(path.data());
auto parent = foundDir->parent;
std::string ourName = foundDir->name;
Directory *newDir = nullptr;
parent->children.erase (std::remove_if (
parent->children.begin(), parent->children.end(),
[&ourName, &newDir] (auto dir) mutable {
if (dir->name == ourName) {
newDir = dir;
return true;
}
return false;
}));
newDir->parent = nullptr;
for (auto &i : newDir->children)
i->parent = newDir;
for (auto &i : newDir->files)
i->dir = newDir;
return newDir;
}
File* deleteFile (std::string_view path) { //task 13
auto parent = findFile (path.data())->directory();
std::string ourName = findFile (path.data())->name();
File *newFile;
parent->files.erase (std::remove_if (parent->files.begin(), parent->files.end(),
[&ourName, &newFile] (auto file) {
if (file->name() == ourName) {
newFile = file;
return true;
}
}));
newFile->dir = nullptr;
return newFile;
}
void filter (const FilterForm &criteria) {
filterHelper (mRoot, criteria);
}
private:
void filterHelper (Directory *dir, const FilterForm &criteria) {
for (auto it = dir->children.begin(); it < dir->children.end();) {
if (!std::regex_match((*it)->name.begin(), (*it)->name.end(), criteria.name.value_or (std::regex (".*"))))
it = dir->children.erase (it);
else {
filterHelper (*it, criteria);
++it;
}
}
for (auto it = dir->files.begin(); it < dir->files.end();) {
if (!std::regex_match((*it)->name().begin(), (*it)->name().end(), criteria.name.value_or (std::regex (".*")))
|| (*it)->size() < criteria.minSize
|| (*it)->size() > criteria.maxSize.value_or (std::numeric_limits<size_t>::max()))
it = dir->files.erase (it);
else
++it;
}
}
};
#endif
| [
"illia.gide@gmail.com"
] | illia.gide@gmail.com |
a817b8f10445da3843a1406e95b1e8e3daa4fa47 | 84c3c55ea8a062be80da3eb53634a9de461550c3 | /src/rpcwallet.cpp | ec33150ad6325b9975f4e367d87421d451eebd6f | [
"MIT"
] | permissive | Cryptotest/Cryptotest | ee540e6ed35937db607d8cce7c3560f1deee2b17 | 172d96b94ad3a90aba48ab97c0ad9282c0f7c2f2 | refs/heads/master | 2021-01-01T05:50:23.808279 | 2014-02-04T13:50:12 | 2014-02-04T13:50:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,940 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2013-2014 Cryptotest Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
}
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", fTestNet));
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new Cryptotest address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current Cryptotest address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <cryptotestaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptotest address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <cryptotestaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptotest address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value setmininput(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"setmininput <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nMinimumInputValue = nAmount;
return true;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <cryptotestaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptotest address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <cryptotestaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <cryptotestaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <cryptotestaddress> [minconf=1]\n"
"Returns the total amount received by <cryptotestaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptotest address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsConfirmed())
continue;
int64 allFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <tocryptotestaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptotest address");
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Cryptotest address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
//
// Used by addmultisigaddress / createmultisig:
//
static CScript _createmultisig(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Cryptotest address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
return result;
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a Cryptotest address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n"
"Creates a multi-signature address and returns a json object\n"
"with keys:\n"
"address : Cryptotest address\n"
"redeemScript : hex-encoded redemption script";
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
struct tallyitem
{
int64 nAmount;
int nConf;
vector<uint256> txids;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
Array transactions;
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& item, (*it).second.txids)
{
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included\n"
" \"txids\" : list of transactions with outputs to the address\n");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString()));
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString()));
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
entry.push_back(Pair("category", "receive"));
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about in-wallet transaction <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(wtx, "*", 0, false, details);
entry.push_back(Pair("details", details));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool();
if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("bitcoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("bitcoin-lock-wa");
int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
MilliSleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
NewThread(ThreadTopUpKeyPool, NULL);
int64* pnSleepTime = new int64(params[1].get_int64());
NewThread(ThreadCleanWalletPassphrase, pnSleepTime);
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; Cryptotest server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <cryptotestaddress>\n"
"Return information about <cryptotestaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value lockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock? [array-of-Objects]\n"
"Updates list of temporarily unspendable outputs.");
if (params.size() == 1)
RPCTypeCheck(params, list_of(bool_type));
else
RPCTypeCheck(params, list_of(bool_type)(array_type));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
Array outputs = params[1].get_array();
BOOST_FOREACH(Value& output, outputs)
{
if (output.type() != obj_type)
throw JSONRPCError(-8, "Invalid parameter, expected object");
const Object& o = output.get_obj();
RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(-8, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(-8, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
Value listlockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"Returns list of temporarily unspendable outputs.");
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
Array ret;
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
Object o;
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
| [
"justkay@Kays-Mac-mini.local"
] | justkay@Kays-Mac-mini.local |
a7b27ad2d5a7b2f29eef1114e5d23ad6c8e0ffe8 | 552e1b1feb898786ece125684a3dd1c2f87b88ac | /Projekt/BigHead/BigHead/Alien.h | f3134695b9303793da28f8e8d4a6e09e9a168b7f | [] | no_license | paweszw608/Cpp | fd0a8d8674c105867c7ee5042658d62ae74222e1 | 3efc4923f7a0c6556f20fd9cf5cacfd0e4f44f5f | refs/heads/master | 2020-04-28T07:34:54.497325 | 2019-03-19T15:31:09 | 2019-03-19T15:31:09 | 175,097,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | h | #pragma once
#include "Movealbe.h"
#include "AnimationManager.h"
class Alien : public Moveable<Sprite>
{
public:
Alien();
Alien(Vector2f scale);
~Alien();
void updateAnimation(int index);
private:
AnimationManager alienAnim;
void setAnimations();
}; | [
"millhavenx666@gmail.com"
] | millhavenx666@gmail.com |
fdf8233929b6bfb7336e7162ba4ff1c0da18eb01 | a7123308718ecb8e7df65937d21b0b686e44b459 | /Plugins/Procedural/Source/Procedural/Private/ProceduralModule.cpp | f0fcb1dd9fba5357ee0740e8ebdbc69736d83bbc | [] | no_license | ren19890419/UE4PluginDevCollection | 99cfc6fc9f678de53e6682c14e7745c33c423d3b | 7f85a357350b1f181d64f87b990f830695e70c3e | refs/heads/master | 2022-02-03T20:44:14.857022 | 2019-06-12T04:24:08 | 2019-06-12T04:24:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Procedural.h"
#if WITH_EDITOR
#include "AssetRegistryModule.h"
#include "UnrealEd.h"
#endif
#include "Classes/ArcComponent.h"
#define LOCTEXT_NAMESPACE "FProceduralModule"
void FProceduralModule::StartupModule()
{
#if WITH_EDITOR
if (GUnrealEd)
{
GUnrealEd->RegisterComponentVisualizer(UArcComponent::StaticClass()->GetFName(), MakeShareable(new FArcCompVisualizer));
}
#endif
}
void FProceduralModule::ShutdownModule()
{
#if WITH_EDITOR
if (GUnrealEd)
{
GUnrealEd->UnregisterComponentVisualizer(UArcComponent::StaticClass()->GetFName());
}
#endif
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FProceduralModule, Procedural) | [
"dsotsen@gmail.com"
] | dsotsen@gmail.com |
e6b3a29bec734c7f0fdeb7c3771b739619057cbc | da540288cc194baf0dc4731e6bf621d20def4a10 | /8. Composite/1.1 Composite (Primitives, Composites).cpp | c51dcf696389b1b2ed8395b71dd8b1a77fb4a871 | [] | no_license | Serhiy-Boyko/Design_patterns | 3df7dbe0dda3bc0cf97970c70d2b3980500ebe36 | 09dab45ad4990844b8364017253951c9345d3818 | refs/heads/master | 2021-07-15T17:07:59.570396 | 2020-10-19T10:17:55 | 2020-10-19T10:17:55 | 217,768,599 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,483 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <assert.h>
// Component
class Unit {
protected:
std::string name;
Unit(std::string n) : name(n) {}
public:
virtual void Info() = 0;
virtual int getCount() = 0;
virtual bool PutInside(Unit* p) = 0;
virtual bool checkComposite() = 0;
virtual ~Unit() {}
};
// -----------------------------------------------------
/* Primitives - класи простих речей
кількість 1 для кожного предмету */
class Primitive : public Unit {
public:
Primitive(std::string n) : Unit(n) {}
virtual void Info() final{ std::cout << " " << name << std::endl;}
virtual int getCount() final { return 1; };
virtual bool PutInside(Unit* p) { return false; }
virtual bool checkComposite() final { return false; }
virtual ~Primitive() {}
};
class Pen : public Primitive {
public:
Pen() : Primitive("pen") {}
virtual ~Pen() {}
};
class Pencil : public Primitive {
public:
Pencil() : Primitive("pencil") {}
virtual ~Pencil() {}
};
class Needle : public Primitive { // Голка
public:
Needle() : Primitive("needle") {}
virtual ~Needle() {}
};
// -----------------------------------------------------
/* Composite - класи складних речей (класи коробок)
кількість 1 + речі в коробці */
class Composite : public Unit {
protected:
std::vector<Unit*> inside;
public:
Composite(std::string n) : Unit(n) {}
// virtual void Info() = 0;
virtual bool checkComposite() final { return true; }
virtual int getCount() final { // кількість речей в коробці
int res = 0;
for (auto i : inside)
res += i->getCount();
return res + 1;
};
virtual bool PutInside(Unit* p) final {
inside.push_back(p);
return true;
}
virtual ~Composite() {
for (auto i : inside)
i->~Unit();
}
};
class smallBox : public Composite {
public:
smallBox() : Composite("smallBox") {}
virtual void Info() override {
std::cout << "-----------------------" << std::endl;
std::cout << " " << name << ": " << std::endl;
for (auto i:inside)
i->Info();
}
virtual ~smallBox() {}
};
class bigBox : public Composite {
public:
bigBox() : Composite("bigBox") {}
virtual void Info() override {
std::cout << "==============================" << std::endl;
std::cout << " " << name << ": " << std::endl;
for (auto i : inside)
i->Info();
}
virtual ~bigBox() {}
};
int main()
{
// створюємо малу коробку
Unit *sbox = new smallBox();
// створюємо речі і кладемо в малу коробку
for (int i = 0; i < 3; i++)
sbox->PutInside(new Pen());
sbox->PutInside(new Needle());
// перелік речей в малій коробці
sbox->Info();
// к-ть речей в малій коробці
std::cout << " count in smallBox: " << sbox->getCount() << std::endl;
// створюємо велику коробку
Unit *bbox = new bigBox();
// створюємо речі і кладемо у велику коробку
bbox->PutInside(new Pencil());
bbox->PutInside(new Pencil());
// кладемо малу коробку у велику коробку
bbox->PutInside(sbox);
// перелік речей у великій коробці
bbox->Info();
// к-ть речей у великій коробці
std::cout << " count in Bigbox: " << bbox->getCount() << std::endl;
delete bbox;
system("Pause");
return 0;
}
| [
"Serhiy@ukr.net"
] | Serhiy@ukr.net |
291eadcf92058003c67833c417afaaf61310e348 | 6822d7a1de1268cdd7ad52b6a18c206a41077fbd | /aws-cpp-sdk-firehose/source/model/PutRecordBatchResponseEntry.cpp | 6f99a46b161f906136adbef3b413335a4c1d71c4 | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | edolstra/aws-sdk-cpp | 57c924ef54f17a67a955c34239622851a9d52ed8 | b2d6affb450a7e276d39f1590bb644d73d721082 | refs/heads/master | 2020-04-05T14:25:50.895804 | 2016-02-16T02:04:09 | 2016-02-16T02:04:09 | 51,923,609 | 0 | 0 | null | 2016-02-17T13:15:00 | 2016-02-17T13:14:59 | null | UTF-8 | C++ | false | false | 2,102 | cpp | /*
* Copyright 2010-2015 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 <aws/firehose/model/PutRecordBatchResponseEntry.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Firehose::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
PutRecordBatchResponseEntry::PutRecordBatchResponseEntry() :
m_recordIdHasBeenSet(false),
m_errorCodeHasBeenSet(false),
m_errorMessageHasBeenSet(false)
{
}
PutRecordBatchResponseEntry::PutRecordBatchResponseEntry(const JsonValue& jsonValue) :
m_recordIdHasBeenSet(false),
m_errorCodeHasBeenSet(false),
m_errorMessageHasBeenSet(false)
{
*this = jsonValue;
}
PutRecordBatchResponseEntry& PutRecordBatchResponseEntry::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("RecordId"))
{
m_recordId = jsonValue.GetString("RecordId");
m_recordIdHasBeenSet = true;
}
if(jsonValue.ValueExists("ErrorCode"))
{
m_errorCode = jsonValue.GetString("ErrorCode");
m_errorCodeHasBeenSet = true;
}
if(jsonValue.ValueExists("ErrorMessage"))
{
m_errorMessage = jsonValue.GetString("ErrorMessage");
m_errorMessageHasBeenSet = true;
}
return *this;
}
JsonValue PutRecordBatchResponseEntry::Jsonize() const
{
JsonValue payload;
if(m_recordIdHasBeenSet)
{
payload.WithString("RecordId", m_recordId);
}
if(m_errorCodeHasBeenSet)
{
payload.WithString("ErrorCode", m_errorCode);
}
if(m_errorMessageHasBeenSet)
{
payload.WithString("ErrorMessage", m_errorMessage);
}
return std::move(payload);
} | [
"henso@amazon.com"
] | henso@amazon.com |
89d5d4d757ec8abea4d686552fae4f3923c3734b | 4d9bbd510b0af8778daba54fe2b1809216463fa6 | /build/Android/Debug/app/src/main/include/_root.FuseCommon_bundle.h | 365dc4b2bd1a587c8e7fc879c821528261f215df | [] | no_license | Koikka/mood_cal | c80666c4930bd8091e7fbe4869f5bad2f60953c1 | 9bf73aab2998aa7aa9e830aefb6dd52e25db710a | refs/heads/master | 2021-06-23T20:24:14.150644 | 2020-09-04T09:25:54 | 2020-09-04T09:25:54 | 137,458,064 | 0 | 0 | null | 2020-12-13T05:23:20 | 2018-06-15T07:53:15 | C++ | UTF-8 | C++ | false | false | 1,125 | h | // This file was generated based on node_modules/@fuse-open/fuselibs/Source/build/Fuse.Common/1.12.0/.uno/package.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Uno{namespace Runtime{namespace Implementation{namespace ShaderBackends{namespace OpenGL{struct GLProgram;}}}}}}
namespace g{struct FuseCommon_bundle;}
namespace g{
// public static generated class FuseCommon_bundle
// {
uClassType* FuseCommon_bundle_typeof();
struct FuseCommon_bundle : uObject
{
static uSStrong< ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLProgram*> Blitter147b1372_;
static uSStrong< ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLProgram*>& Blitter147b1372() { return FuseCommon_bundle_typeof()->Init(), Blitter147b1372_; }
static uSStrong< ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLProgram*> Blitter5b549637_;
static uSStrong< ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLProgram*>& Blitter5b549637() { return FuseCommon_bundle_typeof()->Init(), Blitter5b549637_; }
};
// }
} // ::g
| [
"antti.koivisto@samk.fi"
] | antti.koivisto@samk.fi |
655c919e7f9109ab7193847e1bcc77313b073197 | b2922f9f7f84679009b24a5504ff7c3598a6c087 | /Casino Game.cpp | 59e41e51cbfa33fa75c7a2eb4bd41d6e88a5ba73 | [] | no_license | nishu6499/C-and-C- | b9254a17c6f063a4152707f6b9f1d46e6151200d | 5b655497567c21f409348c65cf11b2826f6d3c5f | refs/heads/master | 2022-12-19T02:57:40.600364 | 2020-09-09T14:12:16 | 2020-09-09T14:12:16 | 278,843,935 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,954 | cpp | #include<iostream>
#include<stdlib.h>
#include<string.h>
#include<time.h>
using namespace std;
int main()
{
char username[50];
int bet=0, num, key=0, prize, bal=0, ans;
cout<<"\t\t_____________________________"<<endl<<endl;
cout<<"\t\t CASINO GAME"<<endl<<endl;
cout<<"\t\t_____________________________"<<endl;
cout<<"Enter your username: "<<endl;
cin>>username;
cout<<endl;
cout<<"Enter deposit amount to play the game: "<<endl;
cin>>bal;
cout<<endl;
cout<<"----------------------------------------------------------------"<<endl;
cout<<" RULES"<<endl;
cout<<"----------------------------------------------------------------"<<endl;
cout<<"1. Choose any number between 1 to 10."<<endl;
cout<<"2. If you guess the correct number, you'll get 10 times your bet."<<endl;
cout<<"3. If you guess the wrong number, you'll lose you bet."<<endl<<endl<<endl;
cout<<"-----------------------------------------------------------------"<<endl<<endl;
cout<<"Your current balance is: "<<bal<<endl;
t:
{
cout<<username<<", place the bet: "<<endl;
cin>>bet;
s:
{
if(bet<=bal)
{
srand(time(0));
key=rand() %10 + 1;
cout<<"Choose a number between 1 to 10: "<<endl;
cin>>num;
if(num>key||num<key)
{
cout<<"Bad Luck this time!! You lost "<<bet<<endl;
cout<<"The winning number was "<<key<<endl;
bal=bal-bet;
cout<<username<<", your current balance is "<<bal<<endl;
cout<<"Do you want to play again"<<endl;
cout<<"(press 0 to leave or 1 to proceed)"<<endl;
cin>>ans;
if(ans==1)
{
cout<<"Your current balance is: "<<bal<<endl;
cout<<username<<", place the bet: "<<endl;
cin>>bet;
goto s;
}
if(ans==0)
{
cout<<"Thanks for playing."<<endl;
return 0;
}
}
else if(num==key)
{
cout<<"You win."<<endl;
prize=10*bal;
cout<<"Awesome!! You won "<<prize<<endl;
bal=bal+prize;
cout<<username<<", your current balance is "<<bal<<endl;
cout<<"Do you want to play again"<<endl;
cout<<"(press 0 to leave or 1 to proceed)"<<endl;
cin>>ans;
if(ans==1)
{
cout<<"Your current balance is: "<<bal<<endl;
cout<<username<<", place the bet: "<<endl;
cin>>bet;
goto s;
}
if(ans==0)
{
cout<<"Thanks for playing."<<endl;
return 0;
}
}
}
else if(bet>bal)
{
cout<<"Sorry you don't have enough balance! Please try again."<<endl;
goto t;
}
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
0c7e0baaf4003ba80c2c31dfb22cc3b01216c0dc | 41ec0ccf925ca4aea2b8688e247ca0cfa3f7a37b | /gpu/utils/src/repacks.cpp | cfb82a49acfc53e6de320c113a706913384f51b7 | [
"BSD-3-Clause"
] | permissive | 0000duck/PCL-1 | 3a46d1ec48c772a82d0cc886cd8fbb1df153964a | 7b828f3f4319f6c15e6a063d881be098d9ddef0e | refs/heads/master | 2021-12-02T11:54:13.877225 | 2012-02-15T23:38:58 | 2012-02-15T23:38:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,831 | cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com)
*/
#include <assert.h>
#include "pcl/gpu/utils/repacks.hpp"
#include "internal.hpp"
| [
"koenbuys@a9d63959-f2ad-4865-b262-bf0e56cfafb6"
] | koenbuys@a9d63959-f2ad-4865-b262-bf0e56cfafb6 |
3e940f3fae7cf96bac76f407e7f1fc1969504550 | 4021dbc4f970a8dbd9d7868316f3dfdb4ed87328 | /Tic-Tac-Toe/gamePlay.hpp | 41628853f75a48af348a52c68719f925da0911ee | [] | no_license | danielmbradley/TicTacToe | 5d3488ddf530b99bff9dbe11b17998f832ef352d | d42e05817e217f98ea781b8ddc9fb69110b76553 | refs/heads/master | 2020-04-06T08:14:05.698024 | 2018-03-16T23:15:55 | 2018-03-16T23:15:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | hpp | //
// gamePlay.hpp
// Tic-Tac-Toe
//
// Created by Daniel Bradley on 10/02/2018.
// Copyright © 2018 Perawk. All rights reserved.
//
#ifndef gamePlay_hpp
#define gamePlay_hpp
#include <stdio.h>
#include "printBoard.hpp"
extern Board playboard;
void levelOne();
void levelTwo();
void levelThree();
void levelFour();
void runGame();
char changePlayer(char);
void movement(char);
#endif /* gamePlay_hpp */
| [
"fiddle3@hotmail.co.uk"
] | fiddle3@hotmail.co.uk |
9dce80a3af7fbc6a8f0eddd074d9546a356b0e86 | b9e4f272762d5cf871653e4b4a3aa9ad33b05117 | /ACM/cccc 练习2017-4-2 1contest-1/C - L1 - 3 ZOJ - 3174.cpp | a47522f5aa61d4da0e9f6789379cac9522656c0e | [] | no_license | haozx1997/C | e799cb25e1fa6c86318721834032c008764066ed | afb7657a58b86bf985c4a44bedfaf1c9cff30cf4 | refs/heads/master | 2021-07-11T23:54:17.357536 | 2017-10-12T03:42:23 | 2017-10-12T03:42:23 | 106,662,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | cpp | #include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int b,e;
int ans = 0;
scanf("%d%d",&b,&e);
for(int i = b;i <= e;i++)
{
int two = i%100;
int three = i%1000;
double root;
root = sqrt(two);
if(root == (int)root &&(int)root<=12&&(int)root>0)
{
// printf("root %d\n",(int)root);
ans++;
}
// printf("nm %d %d %d\n",two!=three,two,three);
if(two!=three)
{
root = sqrt(three);
if(root == (int)root &&(int)root<=12&&(int)root>0)
{
//printf("root %d\n",(int)root);
ans++;
}
}
}
printf("%d\n",ans);
}
}
| [
"haozx1997@users.noreply.github.com"
] | haozx1997@users.noreply.github.com |
a53507adad045cc04602be162c9ab8e062df492d | 27f4e702b2646a351498836573ef6bae575c86ae | /src/hmstl/heightmap.hpp | 93472bc4fb52bc01ab6aab1689f435596a7bcae7 | [] | no_license | ghorn/zion | f5bb12439790bb7e2dd8f91241175d31aadd2948 | d92e5ecfd9260772ff26fa177100cfe068314dbd | refs/heads/master | 2023-02-05T10:35:53.344087 | 2020-12-26T21:19:30 | 2020-12-26T21:19:30 | 303,895,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 426 | hpp | #pragma once
#include <inttypes.h>
#include <vector>
#include <string>
typedef struct {
// xy dimensions (size = width * height)
uint32_t width, height;
uint64_t size;
// z dimensions
float min, max;
// raster with size pixels ranging in value from min to max
std::vector<float> data;
} Heightmap;
void ReadHeightmap(const std::string &path, Heightmap * const hm);
void DumpHeightmap(const Heightmap &hm);
| [
"greg@kittyhawk.aero"
] | greg@kittyhawk.aero |
1ccea506f98de2bd4a9da777d3f6fccc97cdc497 | 91587eb04109f20cedfdad938b01fee4fb4439ce | /code/toolkit/levelviewer/gamestates/viewergamestate.cc | 0447e4920c92ca308bb47e88c87aa46e59c147e2 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | Lyriviel/nebula-trifid | 627900b3cc24f7006da5db07a8b582eb3cf71235 | db4fe422e55989c0f8d811e966f82deba90f8e53 | refs/heads/master | 2021-01-22T19:15:10.164093 | 2016-04-04T18:36:39 | 2016-04-04T18:36:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,705 | cc | //------------------------------------------------------------------------------
// levelviewergamestate.cc
// (C) 2013-2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "viewergamestate.h"
#include "graphics/stage.h"
#include "math/vector.h"
#include "math/matrix44.h"
#include "graphicsfeatureunit.h"
#include "managers/factorymanager.h"
#include "managers/entitymanager.h"
#include "posteffect/posteffectmanager.h"
#include "managers/enventitymanager.h"
#include "scriptfeature/managers/scripttemplatemanager.h"
#include "attr/attribute.h"
#include "graphicsfeature/graphicsattr/graphicsattributes.h"
#include "managers/focusmanager.h"
#include "input/keyboard.h"
#include "scriptingfeature/properties/scriptingproperty.h"
#include "scriptingfeature/scriptingprotocol.h"
#include "remoteinterface/qtremoteserver.h"
#include "basegamefeature/basegameprotocol.h"
#include "../levelviewerapplication.h"
#include "basegametiming/gametimesource.h"
#include "debugrender/debugrender.h"
namespace Tools
{
__ImplementClass(Tools::LevelViewerGameState, 'DMGS', BaseGameFeature::GameStateHandler);
using namespace BaseGameFeature;
using namespace GraphicsFeature;
using namespace PostEffect;
using namespace Graphics;
using namespace Util;
using namespace Math;
//------------------------------------------------------------------------------
/**
*/
LevelViewerGameState::LevelViewerGameState():applyTransform(true),entitiesLoaded(false)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
LevelViewerGameState::~LevelViewerGameState()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
LevelViewerGameState::OnStateEnter( const Util::String& prevState )
{
Util::String newLevel = this->GetLevelName();
if(this->lastLevel.IsEmpty())
{
this->lastLevel = newLevel;
}
GameStateHandler::OnStateEnter(prevState);
if(prevState == "Reload" && this->lastLevel == newLevel && this->applyTransform)
{
Ptr<BaseGameFeature::SetTransform> msg = BaseGameFeature::SetTransform::Create();
msg->SetMatrix(this->focusTransform);
BaseGameFeature::FocusManager::Instance()->GetCameraFocusEntity()->SendSync(msg.cast<Messaging::Message>());
}
}
//------------------------------------------------------------------------------
/**
*/
void
LevelViewerGameState::OnStateLeave( const Util::String& nextState )
{
if(nextState == "Reload")
{
Ptr<Game::Entity> ent = BaseGameFeature::FocusManager::Instance()->GetCameraFocusEntity();
if(ent.isvalid())
{
this->focusTransform = ent->GetMatrix44(Attr::Transform);
}
}
GameStateHandler::OnStateLeave(nextState);
}
//------------------------------------------------------------------------------
/**
*/
Util::String
LevelViewerGameState::OnFrame()
{
Dynui::ImguiAddon::BeginFrame();
Dynui::ImguiConsole::Instance()->Render();
//handle all user input
if (Input::InputServer::HasInstance() && this->entitiesLoaded)
{
this->HandleInput();
}
// test text rendering
Timing::Time frameTime = (float)BaseGameFeature::GameTimeSource::Instance()->GetFrameTime();
Util::String fpsTxt;
fpsTxt.Format("Game FPS: %.2f", 1/frameTime);
_debug_text(fpsTxt, Math::float2(0.0,0.0), Math::float4(1,1,1,1));
QtRemoteInterfaceAddon::QtRemoteServer::Instance()->OnFrame();
Dynui::ImguiAddon::EndFrame();
return GameStateHandler::OnFrame();
}
//------------------------------------------------------------------------------
/**
*/
void
LevelViewerGameState::OnLoadBefore()
{
this->entitiesLoaded = false;
}
//------------------------------------------------------------------------------
/**
*/
void
LevelViewerGameState::OnLoadAfter()
{
this->entitiesLoaded = true;
}
//------------------------------------------------------------------------------
/**
*/
void
LevelViewerGameState::HandleInput()
{
const Ptr<Input::Keyboard>& kbd = Input::InputServer::Instance()->GetDefaultKeyboard();
if(kbd->KeyDown(Input::Key::F5))
{
bool applyTrans = false;
if(kbd->KeyPressed(Input::Key::Shift))
{
applyTrans = true;
}
this->ReloadLevel(applyTrans);
const Ptr<BaseGameFeature::GameStateHandler>& state = App::GameApplication::Instance()->FindStateHandlerByName("Reload").cast<BaseGameFeature::GameStateHandler>();
state->SetLevelName(BaseGameFeature::BaseGameFeatureUnit::Instance()->GetCurrentLevel());
LevelViewerGameStateApplication::Instance()->RequestState("Reload");
}
if (kbd->KeyDown(Input::Key::F10))
{
if (UI::UiFeatureUnit::Instance()->HasLayout("_levellist"))
{
UI::UiFeatureUnit::Instance()->GetLayout("_levellist")->Toggle();
}
}
if (kbd->KeyDown(Input::Key::F11))
{
if (UI::UiFeatureUnit::Instance()->HasLayout("_layoutlist"))
{
UI::UiFeatureUnit::Instance()->GetLayout("_layoutlist")->Toggle();
}
}
}
//------------------------------------------------------------------------------
/**
*/
void
LevelViewerGameState::LoadLevel(const Util::String &level, bool applyTransform)
{
this->applyTransform = applyTransform;
const Ptr<BaseGameFeature::GameStateHandler>& state = App::GameApplication::Instance()->FindStateHandlerByName("Reload").cast<BaseGameFeature::GameStateHandler>();
state->SetLevelName(level);
LevelViewerGameStateApplication::Instance()->RequestState("Reload");
}
//------------------------------------------------------------------------------
/**
*/
void
LevelViewerGameState::ReloadLevel(bool keepTransform)
{
this->LoadLevel(BaseGameFeature::BaseGameFeatureUnit::Instance()->GetCurrentLevel(), keepTransform);
}
} // namespace Tools | [
"johannes@gscept.com"
] | johannes@gscept.com |
79f1485cc0fcbc0d6a32ed608eb1b02df3cd8626 | 6e90b0e4b74be26c3f196227b803d6daff57805f | /tests/functional/wrap_if_mem_fn.cc | c73bc927aa1ce51a8a9ae400ca9e639091e4be4c | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | gintenlabo/etude | 52472b652004383c76089f5145a7cab350b6eb05 | c9e9db5cce72d560a50b1ab27a0ee675a725aefa | refs/heads/master | 2016-09-07T19:08:57.455833 | 2013-08-09T09:54:51 | 2013-08-09T09:54:51 | 1,121,611 | 14 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,050 | cc | //
// wrap_if_mem_fn のテストです。
//
// Copyright (C) 2011 Takaya Saito (SubaruG)
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
//
#include "../../etude/functional/wrap_if_mem_fn.hpp"
#include <type_traits>
#include <boost/test/minimal.hpp>
#define STATIC_ASSERT( expr ) static_assert( expr, #expr )
struct X
{
X() : member() {}
explicit X( int x ) : member(x) {}
int member;
int foo() const { return member; }
void bar( int i ) { member += i; }
};
// 普通の関数
int f() { return 42; }
double g( int i ) { return i / 2.0; }
int test_main( int, char** )
{
// メンバポインタ
{
X x(1);
// rvalue
auto pm = etude::wrap_if_mem_fn( &X::member );
STATIC_ASSERT((
std::is_same<decltype(pm), decltype(std::mem_fn(&X::member))>::value
));
BOOST_CHECK( pm(x) == x.member );
// lvalue
auto foo = &X::foo;
auto pf = etude::wrap_if_mem_fn( foo );
STATIC_ASSERT((
std::is_same<decltype(pf), decltype(std::mem_fn(foo))>::value
));
BOOST_CHECK( pf(x) == x.member );
// const lvalue
auto const bar = &X::bar;
auto pb = etude::wrap_if_mem_fn( bar );
STATIC_ASSERT((
std::is_same<decltype(pb), decltype(std::mem_fn(bar))>::value
));
pb( &x, 1 );
BOOST_CHECK( x.member == 2 );
}
// メンバポインタ以外
{
auto f_ = etude::wrap_if_mem_fn( f );
STATIC_ASSERT((
std::is_same<decltype(f_), int (*)()>::value
));
BOOST_CHECK( f_() == 42 );
// && で束縛すると…
auto && g_ = etude::wrap_if_mem_fn( g );
STATIC_ASSERT((
std::is_same<decltype(g_), double (&)(int)>::value
));
BOOST_CHECK( g_(11) == g(11) );
// ファンクタ
std::plus<int> const plus = {};
auto && plus_ = etude::wrap_if_mem_fn( plus );
STATIC_ASSERT((
std::is_same<decltype(plus_), std::plus<int> const&>::value
));
BOOST_CHECK( plus_( 1, 1 ) == 2 );
}
return 0;
}
| [
"gintensubaru@gmail.com"
] | gintensubaru@gmail.com |
9d6dd2a4903d242c3e0e61e00356b7187c36ecb8 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/abc078/B/4560253.cpp | b7adc3028479026189ebe35673932f8e66069a13 | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 215 | cpp | #include <iostream>
int main(){
int x, y, z;
std::cin >> x >> y >> z;
int i = 1;
while(z + i * (y + z) <= x){
++i;
}
std::cout << i - 1 << std::endl;
return 0;
} | [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
cd45d87f1938cce77921b3b92402855255c45526 | d49637822e1ec08cc4c1598c1c8f1d7a91b286b9 | /week1/opgave6/train.hpp | edb5ae56e545c5b1655c6775629292897488c6e1 | [] | no_license | SonicwaveNL/V1C_OOP | bc120f71176e14f40072b84fa49d27bdb2b653d4 | 6949e9ba7a9a33ffe2b9f8df9beb483b65e03eb1 | refs/heads/master | 2020-05-19T06:34:13.152219 | 2019-05-09T08:52:09 | 2019-05-09T08:52:09 | 184,876,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | hpp | #ifndef TRAIN_HPP
#define TRAIN_HPP
#include "hwlib.hpp"
class train {
private:
hwlib::window & w;
int carts;
public:
train(
hwlib::window & w,
int carts
):
w( w ),
carts( carts )
{}
void print_down();
void print_up();
void print_track();
void run();
};
#endif | [
"justin.van.ziel@gmail.com"
] | justin.van.ziel@gmail.com |
e5b011241860818e9a477a64fa01d827c604678e | fc409746d93317c5fa9d3b230f7ab8dc40d05c9c | /CSC8503/Coursework/KatamariState.cpp | dbcc5ba7426080c0eec84974b0978947a11c6a3f | [] | no_license | Csmidget/Advanced-Game-Technologies-Codebase | fd0125bb5d05123289d2ffdedcd3f41e7f30f3f3 | 9811b183dcf27226f82635e160e3580fd5f244e2 | refs/heads/main | 2023-02-21T18:48:24.128905 | 2021-01-21T19:15:35 | 2021-01-21T19:15:35 | 319,304,461 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,823 | cpp | #include "KatamariState.h"
#include "PlayerObject.h"
#include "AIObject.h"
#include "DebugState.h"
#include "EndState.h"
#include "Game.h"
#include "Checkpoint.h"
#include "BoidSwarm.h"
#include "ObjectFactory.h"
#include "../CSC8503Common/CollisionDetection.h"
using namespace NCL::CSC8503;
KatamariState::KatamariState(Game* game, int boidLayers) : GameState(game) {
camera = game->GetWorld()->GetMainCamera();
game->InitKatamariWorld();
boidSwarm = new BoidSwarm(game);
Vector3 start(-40.0f, 2.0f, -40.0f);
float step = 40.0f / (boidLayers / 2);
for (int x = 0; x < boidLayers; x++) {
for (int y = 0; y < boidLayers; y++) {
game->GetObjectFactory()->CreateBoid(game, &boidSwarm, start + Vector3(x* step,0,y* step));
}
}
requiredBoids = (int)pow(boidLayers, 2) / 5;
boidSwarm->Avoid(game->GetPlayerObject());
for (auto opponent : game->GetOpponents()) {
boidSwarm->Avoid((GameObject*)opponent);
}
}
KatamariState::~KatamariState() {
delete boidSwarm;
}
PushdownState::PushdownResult KatamariState::OnUpdate(float dt, PushdownState** newState) {
Debug::Print("Press 'Backspace' to return to the menu.", Vector2(45, 91), Debug::YELLOW, 1.2f);
if (Window::GetKeyboard()->KeyPressed(KeyboardKeys::BACK)) {
return PushdownResult::Pop;
}
Debug::Print("Press 'P' to pause the game", Vector2(45, 94), Debug::YELLOW, 1.2f);
if (Window::GetKeyboard()->KeyPressed(KeyboardKeys::P)) {
game->SetPause(!game->IsPaused());
}
Debug::Print("Press 'Tab' to enter debug mode", Vector2(45, 97), Debug::YELLOW, 1.2f);
if (Window::GetKeyboard()->KeyPressed(KeyboardKeys::TAB)) {
*newState = new DebugState(game);
return PushdownResult::Push;
}
Debug::Print("Catch balls and be the first to " + std::to_string(requiredBoids) + " points!", Vector2(15, 5), Vector4(1, 1, 0, 1), 1.5f);
int playerScore = game->GetPlayerObject()->GetScore();
if (playerScore >= requiredBoids) {
*newState = new EndState(game, "You win!", "You were the first to reach " + std::to_string(requiredBoids) + " points!");
return PushdownResult::Replace;
}
Debug::Print("Player: " + std::to_string(playerScore), Vector2(2, 20), Debug::YELLOW, 1.1f);
auto opponents = game->GetOpponents();
for (int i = 0; i < opponents.size(); ++i) {
Debug::Print(opponents[i]->GetName() + ": " + std::to_string(opponents[i]->GetScore()), Vector2(2, 23.0f + i * 3.0f),Debug::YELLOW,1.1f);
if (opponents[i]->GetScore() >= requiredBoids) {
*newState = new EndState(game, "You lose!", "One of your opponents caught " + std::to_string(requiredBoids) + " first!");
return PushdownResult::Replace;
}
}
//camera->UpdateCamera(dt);
game->GetPlayerObject()->UpdateControls(camera);
boidSwarm->Update();
return PushdownResult::NoChange;
}
void KatamariState::OnAwake() {
}
void KatamariState::OnSleep() {
} | [
"charles@minidev.co.uk"
] | charles@minidev.co.uk |
d0963950230f9b89109305bad80639a7fcb25c7a | eb5a688501c763f5593c2acb002e0dea133be2de | /Source/Turn_Game/Turn_GameGameModeBase.cpp | 7f5f5384ec686c858300803b7a5eb7a84f7c2370 | [] | no_license | DefineJH/Turn_Game | 08ba7cb86d54ee81cd464ac163fa2abaa3cb5435 | 51473514a931c374700d11869a51e67f63b894b3 | refs/heads/master | 2023-02-28T17:03:23.545072 | 2021-02-14T07:52:45 | 2021-02-14T07:52:45 | 302,867,780 | 0 | 1 | null | 2020-12-01T14:44:39 | 2020-10-10T09:42:05 | C++ | UTF-8 | C++ | false | false | 1,773 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "Turn_GameGameModeBase.h"
#include "Kismet/GameplayStatics.h"
#include "ExplorerChar.h"
#include "GameSaver.h"
#include "GI_Archive.h"
void ATurn_GameGameModeBase::BeginPlay()
{
Super::BeginPlay();
}
void ATurn_GameGameModeBase::Save(int idx)
{
UGI_Archive* arch = Cast<UGI_Archive>(GetGameInstance());
if (arch)
{
arch->SaveCurrentData(idx);
}
}
void ATurn_GameGameModeBase::Load(int idx)
{
UGameSaver* LoadGameInstance = Cast<UGameSaver>(UGameplayStatics::CreateSaveGameObject(UGameSaver::StaticClass()));
if (LoadGameInstance)
{
LoadGameInstance->SaveSlotName = L"Slot" + FString::FromInt(idx);
LoadGameInstance->SaveIndex = 0;
LoadGameInstance = Cast<UGameSaver>(UGameplayStatics::LoadGameFromSlot(LoadGameInstance->SaveSlotName, LoadGameInstance->SaveIndex));
if (LoadGameInstance)
{
UGI_Archive* arch = Cast<UGI_Archive>(GetGameInstance());
if (arch)
{
arch->LoadGameFromData(LoadGameInstance);
}
}
}
}
USkeletalMesh* ATurn_GameGameModeBase::GetCharMesh(FString CharName , AExplorerChar* ToSet)
{
UGI_Archive* GameInst = Cast<UGI_Archive>(GetGameInstance());
if (GameInst)
{
bool MeshSet = GameInst->LoadModels({ CharName });
if (MeshSet)
return GameInst->QueryModel(CharName).GetValue();
else
{
MeshLoadChar = ToSet;
GameInst->MeshLoadDelegate.BindUFunction(this, L"SetCharMesh");
return nullptr;
}
}
return nullptr;
}
void ATurn_GameGameModeBase::SetCharMesh(const TArray<FString>& CharName)
{
UGI_Archive* GameInst = Cast<UGI_Archive>(GetGameInstance());
if (GameInst)
{
auto mesh = GameInst->QueryModel(CharName[0]);
if(MeshLoadChar && mesh.IsSet())
MeshLoadChar->GetMesh()->SetSkeletalMesh(mesh.GetValue());
}
}
| [
"wlghks1502@gmailc.om"
] | wlghks1502@gmailc.om |
a1b3e41ddf204b5f97c98755dfb3070c0dd0cfff | 83740ae21697569a10e118cfd9d8a2299add5c8a | /scripting_engine/api/wizard.cpp | 24d2a6078ea968a83cae21f4666cd153b0f3cbdf | [
"MIT"
] | permissive | 5cript/minide | d2770c1e8251766450d239cc6567da42cd2e07f8 | 0964ae51512eb7ba1ee44d828d27e5b73da32245 | refs/heads/master | 2021-05-12T11:35:42.711075 | 2019-07-20T22:00:19 | 2019-07-20T22:00:19 | 117,390,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,119 | cpp | #include "wizard.hpp"
#include "../common_state_setup.hpp"
#include <sol/sol.hpp>
namespace MinIDE::Scripting::Api
{
//#####################################################################################################################
Wizard::Parameters Wizard::retrieveParameters() const
{
sol::state lua;
commonStateSetup(lua);
lua.open_libraries(sol::lib::table, sol::lib::math);
lua["debugging"] = false;
lua.script(script());
auto getParameters = lua["getParameters"];
sol::table retVal = getParameters();
Parameters params;
for (auto const& [key, value] : retVal)
{
sol::table tab = value;
Wizard::Parameter param =
{
key.as <std::string>(),
tab["prettyName"].get <std::string>(),
tab["value"].get <std::string>(),
tab["description"].get <std::string>(),
tab["isOptional"].get <bool>(),
tab["orderHint"].get <int>()
};
params[key.as <std::string>()] = param;
}
return params;
}
//---------------------------------------------------------------------------------------------------------------------
std::string Wizard::retrieveType() const
{
sol::state lua;
commonStateSetup(lua);
lua.open_libraries(sol::lib::table, sol::lib::math);
lua["debugging"] = false;
lua.script(script());
std::string result = lua["getType"]();
return result;
}
//---------------------------------------------------------------------------------------------------------------------
std::vector <std::pair <std::string, std::string>> Wizard::getFilters()
{
sol::state lua;
commonStateSetup(lua);
lua.open_libraries(sol::lib::table, sol::lib::math);
lua["debugging"] = false;
lua.script(script());
sol::protected_function getType = lua["getType"];
if (!getType.valid())
return {};
std::string type = getType();
if (type != "file")
return {};
std::vector <std::pair <std::string, std::string>> result;
sol::protected_function getFilters = lua["getFilters"];
if (!getFilters.valid())
return {};
sol::table filters = getFilters();
for (auto const& [index, value] : filters)
{
sol::table filter = value;
result.push_back(std::make_pair(
filter["name"].get <std::string>(),
filter["filter"].get <std::string>()
));
}
return result;
}
//---------------------------------------------------------------------------------------------------------------------
std::vector <Wizard::Creation> Wizard::runWizard(Parameters const& params)
{
sol::state lua;
commonStateSetup(lua);
lua.open_libraries(sol::lib::table, sol::lib::math);
lua["debugging"] = false;
sol::table parameterTable = lua.create_table();
for (auto const& [key, param] : params)
{
sol::table parameter = lua.create_table();
parameter["prettyName"] = param.prettyName;
parameter["value"] = param.defaultValue;
parameter["description"] = param.description;
parameter["isOptional"] = param.isOptional;
parameter["orderHint"] = param.orderHint;
parameterTable[key] = parameter;
}
lua.script(script());
std::string type = lua["getType"]();
if (type == "directory")
{
std::vector <std::pair <int, Creation>> creas;
sol::table creatables = lua["runWizard"](parameterTable);
for (auto const& [index, value] : creatables)
{
sol::table crea = value;
Creation c {
crea["name"].get <std::string>(),
crea["content"].get <std::string>(),
crea["type"].get <std::string>()
};
creas.push_back({index.as <int>(), c});
}
std::sort(std::begin(creas), std::end(creas), [](auto const& lhs, auto const& rhs) {
return lhs.first < rhs.first;
});
std::vector <Creation> unzipped;
for (auto const& c : creas) // now sorted
unzipped.push_back(c.second);
return unzipped;
}
else if (type == "file")
{
std::string content = lua["runWizard"](parameterTable);
Creation file;
file.content = content;
return {file};
}
else
throw std::runtime_error("Unexpected wizard type.");
}
//#####################################################################################################################
}
| [
"Tim06TR@gmail.com"
] | Tim06TR@gmail.com |
f4a9e6c1f5ecbf5c3f1ff5784df13f3a8a3cf265 | 3d0a5b32c2abab05e67d34598180b7c5575ea5ba | /SFMLEngine/SimpleSfmlEngine/core/InputManager.h | 3688acef781b8e03430b733e2a190cf8d3845b43 | [] | no_license | oj002/Snowfall_LD40 | 2c9e4d7a1e72e8bd6d7122c0e6af9ab98c4b5dc6 | 4a13a88b694eaa6d7433df325c3a07f208fcd5ff | refs/heads/master | 2021-08-23T11:21:41.304899 | 2017-12-04T17:28:17 | 2017-12-04T17:28:17 | 113,073,203 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,492 | h | #pragma once
#include <SFML/Graphics.hpp>
namespace sse
{
class InputManager
{
public:
InputManager() {}
~InputManager() {}
bool IsPointOnSprite(sf::Sprite object, sf::Vector2i point)
{
sf::IntRect tempRect(static_cast<int>(object.getPosition().x), static_cast<int>(object.getPosition().y), static_cast<int>(object.getGlobalBounds().width), static_cast<int>(object.getGlobalBounds().height));
if (tempRect.contains(point))
{
return true;
}
return false;
}
bool IsSpriteClicked(sf::Sprite object, sf::Mouse::Button button, const sf::RenderWindow &window)
{
if (sf::Mouse::isButtonPressed(button))
{
sf::IntRect tempRect(static_cast<int>(object.getPosition().x), static_cast<int>(object.getPosition().y), static_cast<int>(object.getGlobalBounds().width), static_cast<int>(object.getGlobalBounds().height));
if (tempRect.contains(sf::Mouse::getPosition(window)))
{
return true;
}
}
return false;
}
bool IsCursorOnSprite(sf::Sprite object, const sf::RenderWindow &window)
{
sf::IntRect tempRect(static_cast<int>(object.getPosition().x), static_cast<int>(object.getPosition().y), static_cast<int>(object.getGlobalBounds().width), static_cast<int>(object.getGlobalBounds().height));
if (tempRect.contains(sf::Mouse::getPosition(window)))
{
return true;
}
return false;
}
sf::Vector2i GetCursorPosition(sf::RenderWindow &window)
{
return sf::Mouse::getPosition();
}
private:
};
}
| [
"olaf2@iris-volker.de"
] | olaf2@iris-volker.de |
3f1303945dc0745b575564c1145232751c9a4d4a | 75452de12ec9eea346e3b9c7789ac0abf3eb1d73 | /src/storage/blobfs/test/integration/sync_test.cc | bb9d2252f5ccd9026f3f1d0c7989731981afcb73 | [
"BSD-3-Clause"
] | permissive | oshunter/fuchsia | c9285cc8c14be067b80246e701434bbef4d606d1 | 2196fc8c176d01969466b97bba3f31ec55f7767b | refs/heads/master | 2022-12-22T11:30:15.486382 | 2020-08-16T03:41:23 | 2020-08-16T03:41:23 | 287,920,017 | 2 | 2 | BSD-3-Clause | 2022-12-16T03:30:27 | 2020-08-16T10:18:30 | C++ | UTF-8 | C++ | false | false | 5,201 | cc | // Copyright 2020 The Fuchsia 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 <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fdio/fdio.h>
#include <blobfs/mkfs.h>
#include <blobfs/mount.h>
#include <block-client/cpp/block-device.h>
#include <block-client/cpp/fake-device.h>
#include <zxtest/zxtest.h>
#include "blobfs.h"
#include "fdio_test.h"
#include "nand_test.h"
#include "runner.h"
#include "test/blob_utils.h"
namespace blobfs {
namespace {
using SyncFdioTest = FdioTest;
using SyncNandTest = NandTest;
uint64_t GetSucceededFlushCalls(block_client::FakeBlockDevice* device) {
fuchsia_hardware_block_BlockStats stats;
device->GetStats(true, &stats);
return stats.flush.success.total_calls;
}
} // namespace
// Verifies that fdio "fsync" calls actually sync blobfs files to the block device and verifies
// behavior for different lifecycles of creating a file.
TEST_F(SyncFdioTest, Sync) {
std::unique_ptr<BlobInfo> info;
ASSERT_NO_FAILURES(GenerateRandomBlob("", 64, &info));
memmove(info->path, info->path + 1, strlen(info->path)); // Remove leading slash.
int file = openat(root_fd(), info->path, O_RDWR | O_CREAT);
EXPECT_TRUE(file >= 1);
// We have not written any data to the file. Blobfs requires the file data to be written so the
// name is the hash of the contents.
EXPECT_EQ(-1, fsync(file));
// Write the contents. The file must be truncated before writing to declare its size.
EXPECT_EQ(0, ftruncate(file, info->size_data));
EXPECT_EQ(info->size_data, write(file, info->data.get(), info->size_data));
// Sync the file. This will block until woken up by the file_wake_thread.
EXPECT_EQ(0, fsync(file));
// fsync on a file will flush the writes to the block device but not actually flush the block
// device itself.
fuchsia_hardware_block_BlockStats stats;
block_device()->GetStats(true, &stats);
EXPECT_LE(1u, stats.write.success.total_calls);
EXPECT_EQ(0u, stats.flush.success.total_calls);
// Sync the root directory. Syncing a directory will force the block device to flush.
EXPECT_EQ(0, fsync(root_fd()));
EXPECT_EQ(1u, GetSucceededFlushCalls(block_device()));
}
// Verifies that fdio "sync" actually flushes a NAND device. This tests the fdio, blobfs, block
// device, and FTL layers.
TEST_F(SyncNandTest, Sync) {
// Make a VMO to give to the RAM-NAND.
const size_t vmo_size = Connection::GetVMOSize();
zx::vmo initial_vmo;
ASSERT_OK(zx::vmo::create(vmo_size, 0, &initial_vmo));
// NAND VMOs must be prepopulated with 0xff.
zx_vaddr_t vmar_address = 0;
ASSERT_OK(zx::vmar::root_self()->map(0, initial_vmo, 0, vmo_size,
ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, &vmar_address));
char* initial_vmo_data = reinterpret_cast<char*>(vmar_address);
std::fill(initial_vmo_data, &initial_vmo_data[vmo_size], 0xff);
// Create a second VMO for later use.
zx::vmo second_vmo;
ASSERT_OK(zx::vmo::create(vmo_size, 0, &second_vmo));
ASSERT_OK(zx::vmar::root_self()->map(0, second_vmo, 0, vmo_size,
ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, &vmar_address));
char* second_vmo_data = reinterpret_cast<char*>(vmar_address);
std::unique_ptr<BlobInfo> info;
ASSERT_NO_FAILURES(GenerateRandomBlob("", 64, &info));
{
Connection initial_connection("/initial/dev", std::move(initial_vmo), true);
memmove(info->path, info->path + 1, strlen(info->path)); // Remove leading slash.
fbl::unique_fd file(openat(initial_connection.root_fd(), info->path, O_RDWR | O_CREAT));
ASSERT_TRUE(file.is_valid());
// Write the contents. The file must be truncated before writing to declare its size.
ASSERT_EQ(0, ftruncate(file.get(), info->size_data));
ASSERT_EQ(info->size_data, write(file.get(), info->data.get(), info->size_data));
// This should block until the sync is complete. fsync-ing the root FD is required to flush
// everything.
ASSERT_EQ(0, fsync(file.get()));
ASSERT_EQ(0, fsync(initial_connection.root_fd()));
// Without closing the file or tearing down the existing connection (which may add extra
// flushes, etc.), create a snapshot of the current memory in the second VMO. This will emulate
// a power cycle
memcpy(second_vmo_data, initial_vmo_data, vmo_size);
}
// New connection with a completely new NAND controller reading the same memory.
//
// This call may fail if the above fsync on the root directory is not successful because the
// device will have garbage data in it.
Connection second_connection("/second/dev", std::move(second_vmo), false);
// The blob file should exist.
fbl::unique_fd file(openat(second_connection.root_fd(), info->path, O_RDONLY));
ASSERT_TRUE(file.is_valid());
// The contents should be exactly what we wrote.
std::unique_ptr<char[]> read_data = std::make_unique<char[]>(info->size_data);
ASSERT_EQ(info->size_data, read(file.get(), read_data.get(), info->size_data));
EXPECT_BYTES_EQ(info->data.get(), &read_data[0], info->size_data, "mismatch");
}
} // namespace blobfs
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
5f87292bf7dbb8095f9c1137abf82c1d9838bfca | 420b57ed4dd5bf0026d03b368ee21cf74d80b726 | /test_12_17/test_12_17/源.cpp | efbc98e3f609845a0ae0741e14d770d762b301e0 | [] | no_license | Hidden-Forest/C-CODE | 12b648053818e8eab6077e16113bac6544b606ac | 033f7832ab83886c4133b5e5ae376ba2176c5302 | refs/heads/master | 2023-02-21T18:04:13.074919 | 2021-01-27T15:53:25 | 2021-01-27T15:53:25 | 263,583,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 964 | cpp | #define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == NULL)
return NULL;
if (root->val == val)
return root;
while (root){
if (root->val == val)
return root;
else if (root->val < val)
root = root->left;
else
root = root->right;
}
return NULL;
}
};
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
vector<ListNode *> array;
while (headA){
array.push_back(headA);
headA = headA->next;
}
while (headB){
for (int i = 0; i < array.size(); ++i){
if (array[i] == headB){
return headB;
}
}
}
return NULL;
}
}; | [
"376695558@qq.com"
] | 376695558@qq.com |
b1a6cf1cba9b2c4e91222f73e3ec312b22b80072 | ce7876095646b3da23811753cd1850f7dde2d673 | /highland2/highlandUtils/v2r19/src/HighlandTreeConverterUtils.cxx | 5e96350bcda608f7eac12f42bb0c90fa2faee466 | [] | no_license | Balthazar6969/T2K | 63d7bd6dc2ef9eb1d8e33311d220bf8eb8b61828 | 14709b0dbe1f9b22992efecf30c50d9b8f8bba5c | refs/heads/master | 2020-09-09T18:19:24.346765 | 2019-11-19T07:01:44 | 2019-11-19T07:01:44 | 221,523,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,773 | cxx | #include "HighlandTreeConverterUtils.hxx"
//*****************************************************************************
bool anaUtils::FillTrueVertexRooInfo(AnaTrueVertexB* vertexB, Int_t RunID, bool Neut, bool Genie,
Int_t NNVtx, TClonesArray* NVtx, Int_t NGVtx, TClonesArray* GVtx,
bool& foundCohOnH, bool& foundPauliBlocked ) {
//*****************************************************************************
// TODO: a template could avoid the doubled code for genie and neut:
// template<class T>
// void HandleRooTrackerVertex(T *RooTrackerVtx){
// Do stuff with data members that are identical between N/GRooTrackerVtx
// }
// ND::RooTrackerVtxBase lvtx = (ND::RooTrackerVtxBase) (*NVtx)[roov];
// if (Neut) HandleRooTrackerVertex(static_cast<(ND::NRooTrackerVtx) (NVtx)[roov]>(lvtx));
// if (Genie) HandleRooTrackerVertex(static_cast<(ND::GRooTrackerVtx) (NVtx)[roov]>(lvtx));
//
// NOTE: This was done in xsTool, check $XSTOOLROOT/src/xsGenerator.hxx
AnaTrueVertex* vertex = static_cast<AnaTrueVertex*>(vertexB);
if ( ! Neut && ! Genie) return true;
std::stringstream ssRun; ssRun << RunID;
bool issand = ((ssRun.str())[4]=='7');
bool foundVertex = false;
bool foundLepton = false;
int leptonPDG_StdHep = 0;
TLorentzVector leptonMom_StdHep;
TLorentzVector neutrinoMom_StdHep;
if (Neut) {
for (int roov = 0; roov < NNVtx; roov++) {
ND::NRooTrackerVtx *lvtx = (ND::NRooTrackerVtx*) (*NVtx)[roov];
// this is needed otherwise when running with highland for pro6 over a prod5 file
// it crashes before doing the versioning check (as far as IsMC is taken reading the first entry)
if ( ! lvtx->StdHepPdg) continue;
// look for the current vertex
if (vertex->ID != lvtx->TruthVertexID) continue;
foundVertex = true;
neutrinoMom_StdHep = lvtx->StdHepP4[0]; // needed for Q2 later
vertex->RooVtxIndex = roov;
vertex->NuParentPDG = lvtx->NuParentPdg;
anaUtils::CopyArray(lvtx->NuParentDecX4,vertex->NuParentDecPoint,4);
// tag coherent interaction on hydrogen, wrongly produced because of a bug in neut,
// both in prod 5 and 6, see bugzilla 1056:
// the related reconstructed tracks will be discarded, as well as these true vertices
if (lvtx->StdHepPdg[1] == 1000010010) { // hit nucleus is hydrogen
if (abs(vertex->ReacCode) == 16 || abs(vertex->ReacCode) == 36) { // coherent interactions
foundCohOnH = true;
vertex->IsCohOnH = true;
} else if (lvtx->StdHepPdg[2] == 1000000010) // should happens only for coh on H
std::cout << "minor error in oaAnalysisConverter (ref 1056)" << std::endl;
}
// tag Pauli blocked vertices
// there are single gamma and 1pi Pauli-blocked events without outgoing particles (see bugzilla 1011), but in prod 5
// for a neut bug, only the lepton was set as not-trackable (NEiflgvc == 5), while the other particles were saved:
// the related reconstructed tracks will be discarded, as well as these true vertices
if (lvtx->NEipvc && lvtx->NEipvc[0] != -1) { //otherwise it is NuWro or sand muons prod 5
int leptonIndex = 2;
if (abs(vertex->ReacCode) == 2) leptonIndex = 3; // lepton is shifted for 2p2h that have an extra row for the 2nd nucleon
if (abs(lvtx->NEipvc[leptonIndex]) > 10 && abs(lvtx->NEipvc[leptonIndex]) < 19) { // it is the primary lepton
if (lvtx->NEiflgvc[leptonIndex] == 5) vertex->IsPauliBlocked = true; // the primary lepton is set as not trackable
} else {
std::cout << "ERROR in NRooTrackerVtx: (see bug 1090) the particle with the neutrino as parent is not a lepton, PDG code " << lvtx->NEipvc[leptonIndex] << ", in ID " << vertex->ID <<std::endl;
}
/*
// look into pre-FSI vars (it works, but need to check how much the file size increases)
// store in PreFSIParticles particles escaping the nucleus w/o being affected by FSI (other than the lepton, for which FSI in not applied)
for (int i = 0; i < lvtx->NEnvc; i++) {
// only consider particle escaping the nucleus
if (lvtx->NEicrnvc[i] == 0 ) continue;
// consider only particle pre-FSI, i.e. the parent is the hit nucleon (nucleons if 2p2h)
if (lvtx->NEiorgvc[i] == 2 || (abs(vertex->ReacCode) == 2 && lvtx->NEiorgvc[i] == 3)) {
Float_t thispdg = (Float_t)lvtx->NEipvc[i];
TLorentzVector thisMomentum = lvtx->NEpvc[i]; // already in MeV
Float_t thismom = thisMomentum.Vect().Mag();
Float_t thiscostheta = -999;
if (thismom > 0) thiscostheta = 1/thismom*thisMomentum.Z();
TVector3 thistraj(thispdg,thismom,thiscostheta);
vertex->PreFSIParticles.push_back(thistraj);
}
}
*/
}
// loop over StdHep
for (int i = 0; i < lvtx->StdHepN; i++) {
int outgoingCode = 1; // 0: initial state particle (incoming); 1: stable final state outgoing (GENIE has also other values for intermediate states)
if (issand) outgoingCode = 2; // 0: idem; 2: stable final state outgoing; 1: reach nd280 (listed again, see bug 1128); no sand for genie
if (lvtx->StdHepStatus[i] != outgoingCode) continue;
// fill NPrimaryParticles: count the primary particles of each type (i.e. particles escaping the nucleus)
int index = ParticleId::GetParticle((int)lvtx->StdHepPdg[i],false);
vertex->NPrimaryParticles[index]++;
if (abs(lvtx->StdHepPdg[i]) > 1000 && abs(lvtx->StdHepPdg[i]) < 10000) vertex->NPrimaryParticles[ParticleId::kBaryons]++;
if (abs(lvtx->StdHepPdg[i]) > 100 && abs(lvtx->StdHepPdg[i]) < 1000) vertex->NPrimaryParticles[ParticleId::kMesons]++;
if (abs(lvtx->StdHepPdg[i]) > 10 && abs(lvtx->StdHepPdg[i]) < 19) vertex->NPrimaryParticles[ParticleId::kLeptons]++;
if (lvtx->StdHepPdg[i] == +12 || lvtx->StdHepPdg[i] == +14 || lvtx->StdHepPdg[i] == +16) vertex->NPrimaryParticles[ParticleId::kNeutrinos]++;
if (lvtx->StdHepPdg[i] == -12 || lvtx->StdHepPdg[i] == -14 || lvtx->StdHepPdg[i] == -16) vertex->NPrimaryParticles[ParticleId::kAntiNeutrinos]++;
// primary lepton
if ( ! foundLepton && lvtx->StdHepStatus[i] == outgoingCode) { // the lepton is the first with Status = 1
if (abs(lvtx->StdHepPdg[i]) > 10 && abs(lvtx->StdHepPdg[i]) < 19) { // it is the primary lepton; this is needed for bug 1090
foundLepton = true;
leptonPDG_StdHep = lvtx->StdHepPdg[i];
leptonMom_StdHep = lvtx->StdHepP4[i];
}
}
// fill true proton vars
if (lvtx->StdHepPdg[i] == 2212) {
// if many, take the first one, that more likely should be the interacted one
// 08/02/2017[AI], the above treatment is confusing for the user (e.g. if
// one tries to use the info to unfold to, do studies etc) and the
// underlying assumptions in sorting may be different between
// generators + we already use the info of the post FSI proton
// so changed to use the one with highest momentum
TLorentzVector thisMomentum = lvtx->StdHepP4[i];
Double_t p = thisMomentum.Vect().Mag() * 1000.; // converting from GeV to MeV
if (vertex->ProtonMom < p) {
vertex->ProtonMom = p;
if (vertex->ProtonMom > 0){
anaUtils::VectorToArray((1. / vertex->ProtonMom) * thisMomentum.Vect(), vertex->ProtonDir);
}
}
}
// fill true pion vars
if (lvtx->StdHepPdg[i] == 211) {
// if many, take the highest momentum one, that should be most likely to be reconstructed
TLorentzVector thisMomentum = lvtx->StdHepP4[i];
Double_t p = thisMomentum.Vect().Mag()*1000; // converting from GeV to MeV
if (vertex->PionMom < p) {
vertex->PionMom = p;
if (vertex->PionMom > 0)
anaUtils::VectorToArray((1. / vertex->PionMom) * thisMomentum.Vect(), vertex->PionDir);
}
}
} // end loop over StdHep
break;
} // end loop over vertices
} // end if Neut
else if (Genie) {
for (int roov = 0; roov < NGVtx; roov++) {
ND::GRooTrackerVtx *lvtx = (ND::GRooTrackerVtx*) (*GVtx)[roov];
// this is needed otherwise when running with highland for pro6 over a prod5 file
// it crashes before doing the versioning check
if ( ! lvtx->StdHepPdg) continue;
// look for the current vertex
if (vertex->ID != lvtx->TruthVertexID) continue;
foundVertex = true;
neutrinoMom_StdHep = lvtx->StdHepP4[0]; // needed for Q2 later
vertex->RooVtxIndex = roov;
vertex->NuParentPDG = lvtx->NuParentPdg;
anaUtils::CopyArray(lvtx->NuParentDecX4,vertex->NuParentDecPoint,4);
// if (lvtx->G2NeutEvtCode != vertex->ReacCode) // it happens often!
vertex->ReacCode = lvtx->G2NeutEvtCode;
// loop over StdHep
for (int i = 0; i < lvtx->StdHepN; i++) {
if (lvtx->StdHepStatus[i] != 1) continue; // 0 is incoming particle, 1 for outgoing (GENIE has also other values for intermediate states)
// fill NPrimaryParticles: count the primary particles of each type
int index = ParticleId::GetParticle((int)lvtx->StdHepPdg[i],false);
vertex->NPrimaryParticles[index]++;
if (abs(lvtx->StdHepPdg[i]) > 1000 && abs(lvtx->StdHepPdg[i]) < 10000) vertex->NPrimaryParticles[ParticleId::kBaryons]++;
if (abs(lvtx->StdHepPdg[i]) > 100 && abs(lvtx->StdHepPdg[i]) < 1000) vertex->NPrimaryParticles[ParticleId::kMesons]++;
if (abs(lvtx->StdHepPdg[i]) > 10 && abs(lvtx->StdHepPdg[i]) < 19) vertex->NPrimaryParticles[ParticleId::kLeptons]++;
if (lvtx->StdHepPdg[i] == +12 || lvtx->StdHepPdg[i] == +14 || lvtx->StdHepPdg[i] == +16) vertex->NPrimaryParticles[ParticleId::kNeutrinos]++;
if (lvtx->StdHepPdg[i] == -12 || lvtx->StdHepPdg[i] == -14 || lvtx->StdHepPdg[i] == -16) vertex->NPrimaryParticles[ParticleId::kAntiNeutrinos]++;
// this is the primary lepton
// in Genie the first with Status 1 is not enough, it might be listed later, but it's always the one with StdHepFm = 0
if ( ! foundLepton && lvtx->StdHepStatus[i] == 1 && lvtx->StdHepFm[i] == 0) {
foundLepton = true;
leptonPDG_StdHep = lvtx->StdHepPdg[i];
leptonMom_StdHep = lvtx->StdHepP4[i];
}
// fill true proton vars
if (lvtx->StdHepPdg[i] == 2212) {
// if many, take the first one, that more likely should be the interacted one
// 08/02/2017[AI], the above treatment is confusing for the user (e.g. if
// one tries to use the info to unfold to, do studies etc) and the
// underlying assumptions in sorting may be different between
// generators + we already use the info of the post FSI proton
// so changed to use the one with highest momentum
TLorentzVector thisMomentum = lvtx->StdHepP4[i];
Double_t p = thisMomentum.Vect().Mag() * 1000.; // converting from GeV to MeV
if (vertex->ProtonMom < p) {
vertex->ProtonMom = p;
if (vertex->ProtonMom > 0){
anaUtils::VectorToArray((1. / vertex->ProtonMom) * thisMomentum.Vect(), vertex->ProtonDir);
}
}
}
// fill true pion vars
if (lvtx->StdHepPdg[i] == 211) {
// if many, take the highest momentum one, that should be most likely to be reconstructed
TLorentzVector thisMomentum = lvtx->StdHepP4[i];
Double_t p = thisMomentum.Vect().Mag()*1000; // converting from GeV to MeV
if (vertex->PionMom < p) {
vertex->PionMom = p;
if (vertex->PionMom > 0)
anaUtils::VectorToArray((1. / vertex->PionMom) * thisMomentum.Vect(), vertex->PionDir);
}
}
} // end loop StdHep
break;
} // end loop over vertices
} // end if Genie
if ( ! foundVertex) {
std::cout << "ERROR: true vertex not found in RooTrackerVtx!!! ID = " << vertex->ID << std::endl;
return true;
}
// Fill NPrimaryParticles for kPions and Kaons
vertex->NPrimaryParticles[ParticleId::kPions] = vertex->NPrimaryParticles[ParticleId::kPi0] +
vertex->NPrimaryParticles[ParticleId::kPiPos] +
vertex->NPrimaryParticles[ParticleId::kPiNeg] ;
vertex->NPrimaryParticles[ParticleId::kKaons] = vertex->NPrimaryParticles[ParticleId::kK0] +
vertex->NPrimaryParticles[ParticleId::kAntiK0] +
vertex->NPrimaryParticles[ParticleId::kK0L] +
vertex->NPrimaryParticles[ParticleId::kK0S] +
vertex->NPrimaryParticles[ParticleId::kKPos] +
vertex->NPrimaryParticles[ParticleId::kKNeg] ;
if (vertex->NPrimaryParticles[ParticleId::kMuon] > 1) std::cout << "INFO: lepton pair produced by FSI: Nmuon " << vertex->NPrimaryParticles[ParticleId::kMuon] << ", Nantimuon " << vertex->NPrimaryParticles[ParticleId::kAntiMuon] << ", NuPDG " << vertex->NuPDG << ", ReacCode " << vertex->ReacCode << ", in detector " << vertex->Detector << std::endl;
// no lepton --> Pauli blocked event
if ( ! foundLepton || abs(leptonPDG_StdHep) > 18) {
// double-check that this is a Pauli blocked vertex
if (vertex->IsPauliBlocked &&
(abs(vertex->ReacCode) == 11 || abs(vertex->ReacCode) == 12 || abs(vertex->ReacCode) == 13 || // 1pi nu/antinu CC
abs(vertex->ReacCode) == 31 || abs(vertex->ReacCode) == 32 || abs(vertex->ReacCode) == 33 || abs(vertex->ReacCode) == 34 || // 1pi nu/antinu NC
abs(vertex->ReacCode) == 17 || abs(vertex->ReacCode) == 38 || abs(vertex->ReacCode) == 39 ) // single gamma from delta resonance nu/antinu
) {
foundPauliBlocked = true;
// std::cout << "INFO: this is a Pauli blocked vertex (single gamma or 1pi), ReacCode " << vertex->ReacCode << std::endl; // TOO MANY!
} else {
if ( ! issand) // suppress for sand muons even though it's not clear why it happens: see bug 1136
std::cout << "ERROR in oaAnalysisConverter (ignore for run 91300010-0028 since it's caused by bug 1368): primary lepton in StdHepPdg with PDG code "
<< leptonPDG_StdHep << " (0='not found') for ID " << vertex->ID <<std::endl;
}
}
// fill DataClasses members
neutrinoMom_StdHep = neutrinoMom_StdHep*1000; // converting from GeV to MeV
neutrinoMom_StdHep[3] = sqrt(pow(neutrinoMom_StdHep[0],2)+pow(neutrinoMom_StdHep[1],2)+pow(neutrinoMom_StdHep[2],2));
// not sure why (likely float casting) but StdHepP4[vertex][0][3] is not equal to the sqrt of the power of the other 3 components
// while Vertices.NeutrinoMomentum.E() it is! (evidently it is re-calculated in TruthTrajectoriesModule of oaAnalysis)
vertex->NuEnergy = neutrinoMom_StdHep[3];
if (foundLepton) {
leptonMom_StdHep = leptonMom_StdHep*1000; // converting from GeV to MeV
vertex->LeptonPDG = leptonPDG_StdHep;
vertex->Q2 = - (leptonMom_StdHep - neutrinoMom_StdHep).Mag2();
vertex->LeptonMom = leptonMom_StdHep.Vect().Mag();
if (vertex->LeptonMom > 0)
anaUtils::VectorToArray((1 / vertex->LeptonMom) * leptonMom_StdHep.Vect(),vertex->LeptonDir);
}
return true; // return false not to save this true vertex
}
| [
"conor.francois@gmail.com"
] | conor.francois@gmail.com |
b98884053a2ed2adbc6a8b2a8409b9fae9dc446d | 9132b3355e78822fbbc9a4a5c37afc51f2b544f0 | /src/attack/attack_server.h | 2fab8c303befc75140039a4e2621650af4ad9b45 | [
"MIT"
] | permissive | chris-wood/fiblib | 8784721372342f8a2dbefe508d04336b6dfd1aec | f21773610d6e6447b8f0418922b9d8813495aee8 | refs/heads/master | 2021-08-22T02:45:08.992205 | 2017-11-29T04:18:19 | 2017-11-29T04:18:19 | 53,748,091 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | #ifndef ATTACK_SERVER_H_
#define ATTACK_SERVER_H_
using namespace std;
#include <vector>
class AttackServer
{
public:
AttackServer(int sock) {
sockfd = sock;
}
void Run();
void SetNumberOfNames(int num) {
numberOfNames = num;
}
int sockfd;
int numberOfNames;
std::vector<struct timespec> times;
};
void *runServer(void *arg);
#endif // ATTACK_SERVER_H_ | [
"christopherwood07@gmail.com"
] | christopherwood07@gmail.com |
39d2baf4bb3e3c7d3ac408e268a1e738cf8d3ab1 | ad90fd7724d8bf72f3e8b3d967799e317769430a | /HelloWorld/win32/Action_Card.cpp | ece8b228df3cf275b38679b2f782569c149b5256 | [] | no_license | geniikw/myFirst2DGame | f71865ec8eabdff35c33b2a013b3afd1711b7776 | d9050e71913000e9147fa3f889d4b6c7c35fda94 | refs/heads/master | 2021-07-09T21:09:57.886694 | 2016-12-15T16:50:51 | 2016-12-15T16:50:51 | 19,765,521 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,198 | cpp | #include"Action_Card.h"
#include"header.h"
#include"Manager_Resource.h"
Action_Card::Action_Card(int CardNumber)
{
init();
CCAnimation *pAni = new CCAnimation;
pAni->initWithName("CARD");
for (int n = 0; n < MAX_CARD_NUMBER; n++)
{
pAni->addFrameWithTexture(Manager_Resource::getInstance()->getResourceWithString("ACardRes"), CGRect(70*n,0,70,100));
}
this->addAnimation(pAni);
if (CardNumber < AC_NOCARD_BACK)
setCardNumber(CardNumber);
}
void Action_Card::setCardAngle(float angle)
{
if (angle < 90.f)
{
setDisplayFrame("CARD", m_iCardNumber);
setScaleX(linear(1, 0, angle, 90.f));
}
else if (angle < 180.f)
{
setDisplayFrame("CARD", 0);
angle = angle - 90.f;
setScaleX(linear(0, 1, angle, 90.f));
}
else if (angle < 270.f)
{
setDisplayFrame("CARD", 0);
angle = angle - 180.f;
setScaleX(linear(1, 0, angle, 90.f));
}
else if (angle < 360.f)
{
setDisplayFrame("CARD", m_iCardNumber);
angle = angle - 270.f;
setScaleX(linear(0, 1, angle, 90.f));
}
}
void Action_Card::setCardNumber(int CardNumber)
{
if (m_iCardNumber == 0)
{
errorBOX("0번카드는 없다.-_-q");
}
m_iCardNumber = CardNumber;
setDisplayFrame("CARD", m_iCardNumber);
}
| [
"geniikw@gmail.com"
] | geniikw@gmail.com |
f8918df048826ac4f2ce365e5dfb31dce2bd5ed3 | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/gen/gen_combined/third_party/blink/renderer/bindings/core/v8/v8_garbage_collected_script_wrappable.h | 8044706bee9980735ab5c3ef00ec5909336a9435 | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,019 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/interface.h.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_V8_GARBAGE_COLLECTED_SCRIPT_WRAPPABLE_H_
#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_V8_GARBAGE_COLLECTED_SCRIPT_WRAPPABLE_H_
#include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/testing/garbage_collected_script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h"
#include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
extern const WrapperTypeInfo v8_garbage_collected_script_wrappable_wrapper_type_info;
class V8GarbageCollectedScriptWrappable {
STATIC_ONLY(V8GarbageCollectedScriptWrappable);
public:
static bool HasInstance(v8::Local<v8::Value>, v8::Isolate*);
static v8::Local<v8::Object> FindInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*);
static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&);
static GarbageCollectedScriptWrappable* ToImpl(v8::Local<v8::Object> object) {
return ToScriptWrappable(object)->ToImpl<GarbageCollectedScriptWrappable>();
}
static GarbageCollectedScriptWrappable* ToImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>);
static constexpr const WrapperTypeInfo* GetWrapperTypeInfo() {
return &v8_garbage_collected_script_wrappable_wrapper_type_info;
}
static constexpr int kInternalFieldCount = kV8DefaultWrapperInternalFieldCount;
// Callback functions
static void ToStringMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&);
static void InstallRuntimeEnabledFeaturesOnTemplate(
v8::Isolate*,
const DOMWrapperWorld&,
v8::Local<v8::FunctionTemplate> interface_template);
};
template <>
struct NativeValueTraits<GarbageCollectedScriptWrappable> : public NativeValueTraitsBase<GarbageCollectedScriptWrappable> {
static GarbageCollectedScriptWrappable* NativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&);
static GarbageCollectedScriptWrappable* NullValue() { return nullptr; }
};
template <>
struct V8TypeOf<GarbageCollectedScriptWrappable> {
typedef V8GarbageCollectedScriptWrappable Type;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_V8_GARBAGE_COLLECTED_SCRIPT_WRAPPABLE_H_
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
4f93a8f4e7fb971fa27a4056f499a0034e076ca7 | bb5258ea8c1f8cbcc247b92971cd926264479002 | /ds4/code/4_core/object/time/timer.h | 7b861250190b84163aec19332f0cf6ff3f3ef24f | [
"MIT"
] | permissive | demonsaw/Code | 16fa41f07600e83f16713a657ac8fffa0b6b7f9b | b036d455e9e034d7fd178e63d5e992242d62989a | refs/heads/master | 2021-11-07T21:37:03.738542 | 2021-10-26T03:47:14 | 2021-10-26T03:47:14 | 98,356,418 | 134 | 19 | MIT | 2019-01-06T03:20:12 | 2017-07-25T22:50:36 | C++ | UTF-8 | C++ | false | false | 3,040 | h | //
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef _EJA_TIMER_H_
#define _EJA_TIMER_H_
#include <chrono>
#include "object/object.h"
#include "system/type.h"
namespace eja
{
class timer : public object
{
make_factory(timer);
protected:
std::chrono::system_clock::time_point m_start;
std::chrono::system_clock::time_point m_stop;
protected:
// Utility
template <typename T>
size_t get_elapsed() const;
public:
timer() { }
timer(const timer& obj) : m_start(obj.m_start), m_stop(obj.m_stop) { }
// Operator
timer& operator=(const timer& obj);
// Interface
virtual void start();
virtual void restart();
virtual void stop() { m_stop = std::chrono::system_clock::now(); }
virtual void resume() { m_stop = std::chrono::system_clock::time_point(); }
// Utility
virtual bool valid() const override { return m_start != std::chrono::system_clock::time_point(); }
bool elapsed(const size_t ms) const { return get_milliseconds() >= ms; }
std::string str() const;
// Get
size_t get_time() const { return get_milliseconds(); }
size_t get_hours() const { return get_elapsed<std::chrono::hours>(); }
size_t get_minutes() const { return get_elapsed<std::chrono::minutes>(); }
size_t get_seconds() const { return get_elapsed<std::chrono::seconds>(); }
size_t get_milliseconds() const { return get_elapsed<std::chrono::milliseconds>(); }
size_t get_microseconds() const { return get_elapsed<std::chrono::microseconds>(); }
size_t get_nanoseconds() const { return get_elapsed<std::chrono::nanoseconds>(); }
};
// Utility
template <typename T>
size_t timer::get_elapsed() const
{
if (valid())
{
const auto now = (m_stop.time_since_epoch() == std::chrono::steady_clock::duration::zero()) ? std::chrono::system_clock::now() : m_stop;
const auto duration = now - m_start;
return static_cast<size_t>(std::chrono::duration_cast<T>(duration).count());
}
return 0;
}
}
#endif
| [
"eric@codesiren.com"
] | eric@codesiren.com |
0f979e2ffc1580169aaa38ce88a6bb44ecadb29d | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/skia/ext/platform_device.h | 8e23de5a23f762b3655e98a45a7393f3024f1b13 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 3,440 | h | // Copyright (c) 2012 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.
#ifndef SKIA_EXT_PLATFORM_DEVICE_H_
#define SKIA_EXT_PLATFORM_DEVICE_H_
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <vector>
#endif
#include "skia/ext/platform_surface.h"
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkTypes.h"
class SkMatrix;
class SkPath;
namespace skia {
class PlatformDevice;
class ScopedPlatformPaint;
// The following routines provide accessor points for the functionality
// exported by the various PlatformDevice ports.
// All calls to PlatformDevice::* should be routed through these
// helper functions.
// Bind a PlatformDevice instance, |platform_device| to |device|. Subsequent
// calls to the functions exported below will forward the request to the
// corresponding method on the bound PlatformDevice instance. If no
// PlatformDevice has been bound to the SkBaseDevice passed, then the
// routines are NOPS.
SK_API void SetPlatformDevice(SkBaseDevice* device,
PlatformDevice* platform_device);
SK_API PlatformDevice* GetPlatformDevice(SkBaseDevice* device);
// A SkBitmapDevice is basically a wrapper around SkBitmap that provides a
// surface for SkCanvas to draw into. PlatformDevice provides a surface
// Windows can also write to. It also provides functionality to play well
// with GDI drawing functions. This class is abstract and must be subclassed.
// It provides the basic interface to implement it either with or without
// a bitmap backend.
//
// PlatformDevice provides an interface which sub-classes of SkBaseDevice can
// also provide to allow for drawing by the native platform into the device.
// TODO(robertphillips): Once the bitmap-specific entry points are removed
// from SkBaseDevice it might make sense for PlatformDevice to be derived
// from it.
class SK_API PlatformDevice {
public:
virtual ~PlatformDevice() {}
#if defined(OS_MACOSX)
// The CGContext that corresponds to the bitmap, used for CoreGraphics
// operations drawing into the bitmap. This is possibly heavyweight, so it
// should exist only during one pass of rendering.
virtual CGContextRef GetBitmapContext(const SkMatrix& transform,
const SkIRect& clip_bounds) = 0;
#endif
#if defined(OS_WIN)
// Draws to the given screen DC, if the bitmap DC doesn't exist, this will
// temporarily create it. However, if you have created the bitmap DC, it will
// be more efficient if you don't free it until after this call so it doesn't
// have to be created twice. If src_rect is null, then the entirety of the
// source device will be copied.
virtual void DrawToHDC(HDC source_dc, HDC destination_dc, int x, int y,
const RECT* src_rect, const SkMatrix& transform);
#endif
private:
// The DC that corresponds to the bitmap, used for GDI operations drawing
// into the bitmap. This is possibly heavyweight, so it should be existant
// only during one pass of rendering.
virtual PlatformSurface BeginPlatformPaint(const SkMatrix& transform,
const SkIRect& clip_bounds);
friend class ScopedPlatformPaint;
};
} // namespace skia
#endif // SKIA_EXT_PLATFORM_DEVICE_H_
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
cbbe588c239ae5d8b1a46c5c2e9097fa0d365a76 | 4f26ffb33ca2f9ebcc96ace332d1f38f34f74c04 | /src/cliente/lanzador/ventana_juego_terminado.h | 9a9a18a19462b816acf92ffcedd4e2b5dd943ee4 | [] | no_license | sportelliluciano/tp-final-taller-1 | 7eaccbc0ac58a53c8de504a12856c9d5a8bbb4ee | c25ac32821ee88d65956cb705968c06233d46c31 | refs/heads/master | 2020-03-31T15:43:48.613932 | 2018-12-04T21:02:17 | 2018-12-04T21:02:17 | 152,349,087 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | h | #ifndef _VENTANA_JUEGO_TERMINADO_H_
#define _VENTANA_JUEGO_TERMINADO_H_
#include <string>
#include <QWidget>
#include "cliente/lanzador/ui_ventana_juego_terminado.fwd.h"
class VentanaJuegoTerminado : public QWidget {
Q_OBJECT
public:
VentanaJuegoTerminado(const std::string& ganador, QWidget *parent = 0);
virtual ~VentanaJuegoTerminado();
private:
Ui::VentanaJuegoTerminado *ui;
};
#endif // _VENTANA_JUEGO_TERMINADO_H_ | [
"sportelliluciano@gmail.com"
] | sportelliluciano@gmail.com |
0577da3fc43aab2dc3c83e0208e731179d0c1897 | 1fbb86a68429b4a013e4dd5536bd11b5f01bd481 | /libs/glbinding/include/glbinding/gl12/boolean.h | faf57a97bc34446df47a2b2be338b48b89adcc57 | [
"MIT"
] | permissive | drzajwo/UJ-Programowanie-grafiki-3D | e1dfcf0c6ba7706eada293425262905588136f26 | 9e76ed4d528208bb18525e2b5e80a74944a9b67d | refs/heads/master | 2020-08-28T12:06:27.049514 | 2019-11-23T12:49:47 | 2019-11-23T12:49:47 | 217,693,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | h |
#pragma once
#include <glbinding/nogl.h>
#include <glbinding/gl/boolean.h>
namespace gl12
{
// import booleans to namespace
using gl::GL_FALSE;
using gl::GL_TRUE;
} // namespace gl12
| [
"Iwo.Wojciechowski@pega.com"
] | Iwo.Wojciechowski@pega.com |
4837a57656a00abdbea815016055c08bbc387c5c | ad5b72656f0da99443003984c1e646cb6b3e67ea | /src/tests/functional/shared_test_classes/src/subgraph/preprocess.cpp | 4f16483e9b1955cfd613094b11c9cf64d501123e | [
"Apache-2.0"
] | permissive | novakale/openvino | 9dfc89f2bc7ee0c9b4d899b4086d262f9205c4ae | 544c1acd2be086c35e9f84a7b4359439515a0892 | refs/heads/master | 2022-12-31T08:04:48.124183 | 2022-12-16T09:05:34 | 2022-12-16T09:05:34 | 569,671,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,381 | cpp | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "shared_test_classes/subgraph/preprocess.hpp"
#include "ngraph_functions/preprocess/preprocess_builders.hpp"
#include "openvino/core/preprocess/pre_post_process.hpp"
using namespace ov;
using namespace ov::preprocess;
using namespace ov::builder::preprocess;
namespace SubgraphTestsDefinitions {
std::string PrePostProcessTest::getTestCaseName(
const testing::TestParamInfo<preprocessParamsTuple> &obj) {
std::string targetName;
preprocess_func func;
std::tie(func, targetName) = obj.param;
std::ostringstream result;
result << "Func=" << func.m_name << "_";
result << "Device=" << targetName << "";
return result.str();
}
void PrePostProcessTest::SetUp() {
preprocess_func func;
std::tie(func, targetDevice) = GetParam();
function = func.m_function();
rel_threshold = func.m_accuracy;
functionRefs = ngraph::clone_function(*function);
abs_threshold = func.m_accuracy;
if (func.m_shapes.empty()) {
for (const auto& input : function->inputs()) {
func.m_shapes.push_back(input.get_shape());
}
}
init_input_shapes(ov::test::static_shapes_to_test_representation(func.m_shapes));
}
TEST_P(PrePostProcessTest, CompareWithRefs) {
run();
}
} // namespace SubgraphTestsDefinitions
| [
"noreply@github.com"
] | noreply@github.com |
0bea7f76533d30a221d3c2bd570bc5e65c091a85 | 12330f413270714472c0332efd8a85baa6e88bf9 | /ReportService.cpp | 9f4b17160ade449598aec4eb4d0276752cef6a45 | [] | no_license | anosenko1/task0b | a15d2148200a0dd092315440481d3c2eff1bc148 | c47847cb0587fb6141eba2befa0dbe4a803c4383 | refs/heads/master | 2022-12-30T15:46:20.359744 | 2020-10-17T21:35:59 | 2020-10-17T21:35:59 | 304,636,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | cpp | #include "ReportService.h"
#include <iostream>
ReportService::ReportService(string file_name, vector<pair<string, pair<int, double>> > dict) {
this->file_name = move(file_name);
this->dict = move(dict);
FileOpen();
}
ReportService::~ReportService(){
FileClose();
}
void ReportService::Write(){
file << "word,count,frequency" << endl;
for (const auto& p : dict)
file << p.first << ',' << p.second.first << ',' << p.second.second << '%' << endl;
}
void ReportService::FileOpen() {
file.open(file_name);
if (!file.is_open()) {
cout << "file opening error" << endl;
exit(0);
}
}
void ReportService::FileClose() {
if (file.is_open())
file.close();
} | [
"a.nosenko1@g.nsu.ru"
] | a.nosenko1@g.nsu.ru |
759c778111edec8ae29066d0efb9e5a8e17e5bd7 | 9ebc7a3e353400d81746f46a6d40a105a1af2b72 | /boca/comb.cpp | cf5a540ed5d4fbfc225f2f16c9d5ca0c73ed5a10 | [] | no_license | gabrielms98/inf110 | d8e30547f8d19e19e8946905c218f2ea254953e0 | cff35bdc088978f39284d153b1049d14741bdb8d | refs/heads/master | 2020-03-21T16:56:23.624177 | 2019-09-18T12:43:29 | 2019-09-18T12:43:29 | 138,803,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | cpp | #include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
//Retorna o valor de x!
long long int fatorial (int x){
long long int fat=1;
for(int i=2; i<=x; i++)
fat*=i;
return fat;
}
int main(){
int n, k;
int ncomissoes;
cin >> n >> k;
ncomissoes = (fatorial(n))/(fatorial(k)*fatorial(n-k));
cout << ncomissoes << endl;
return 0;
}
| [
"gabrielsilva@200-235-207-113.wifi.ufv.br"
] | gabrielsilva@200-235-207-113.wifi.ufv.br |
7c3187627fbed4449a0cc8a1f8166b26c9d720fa | 89b83d2a6b1c67274c7b660ba59115c587bdeefd | /Platform/Platform/General.cpp | 591d966a452328591ab9ce31eabc68bb91c5eeea | [] | no_license | Mielniu/Platforma | a9b19047758040c6dbed571fce0cfb49779892f8 | 5fd44d6dfbba55395c06cabf2b6b861fb0be4a53 | refs/heads/master | 2020-12-29T01:41:41.058117 | 2016-09-19T14:19:14 | 2016-09-19T14:19:14 | 65,823,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,535 | cpp | #include "General.h"
#include <iostream>
General::General()
{
windows.create(sf::VideoMode(static_cast<int> (windowsWidth), static_cast<int>(windowsHeight)), windowsName, sf::Style::Close);
windows.setVerticalSyncEnabled(true);
}
General::~General()
{
}
void General::run()
{
startmap();
while (windows.isOpen())
{
while (windows.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
windows.close();
break;
case sf::Event::KeyPressed:
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) { windows.close(); break; }
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) ruch(3);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) ruch(4);
ruch(1);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { ruch(2); break; }
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { ruch(3); break; }
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { ruch(4); break; }
break;
default:
break;
}
}
fizyka();
draw();
//std::cout << "test" << std::endl;
}
}
void General::startmap()
{
int level[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
};
if (!map.load("Texture\\Textur.png", sf::Vector2u(40, 40), level, 20, 14))
windows.close();
postac();
}
void General::postac()
{
// wczytanie textur
if (!texturepostac.loadFromFile("Texture\\Postac.png"))
std::cout << "Erroe: load postac\n";
// rysowanie postaci
spritepostac.setTexture(texturepostac);
spritepostac.setTextureRect(sf::IntRect(0, 0, 40, 120));
// wyznaczanie position
//positionpostacx = 1;
//positionpostacy = 1;
spritepostac.setPosition(0, kolizja - wysokoscpostaci);
} | [
"McMichael@KOMPUTER"
] | McMichael@KOMPUTER |
1875cbf569261b0117c00695d56458898906eb21 | 231eb13586f81657f665ce9afd38631e078dc33c | /Network Security/Ns HW3 Q5/methods/tdes-cfb.cpp | fc36ad39eb991f89972c5ad0898dc935313bf9db | [] | no_license | PatKevorkian/Code-Examples | e067b641db317459cbeda771a0ebbc8044c946f0 | 2021228d6aa76f449644d6b42ba51c6259e2ddcc | refs/heads/master | 2020-04-09T03:09:12.790118 | 2018-12-01T18:14:15 | 2018-12-01T18:14:15 | 150,888,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,675 | cpp | #include <iostream>
#include <iomanip>
using namespace std;
#include <string>
#include "cryptopp/cryptlib.h"
using CryptoPP::Exception;
#include "cryptopp/hex.h"
using CryptoPP::HexEncoder;
using CryptoPP::HexDecoder;
#include "cryptopp/filters.h"
using CryptoPP::StringSink;
using CryptoPP::StringSource;
using CryptoPP::StreamTransformationFilter;
#include "cryptopp/des.h"
using CryptoPP::DES_EDE3;
#include "cryptopp/modes.h"
using CryptoPP::CFB_Mode;
#include "cryptopp/secblock.h"
using CryptoPP::SecByteBlock;
int main(int argc, char* argv[])
{
byte key[CryptoPP::DES_EDE3::DEFAULT_KEYLENGTH] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0x01,0x45,0x67,0x89,0xab,0xcd,0xef,0x01,0x23};
byte iv[DES_EDE3::BLOCKSIZE] = {0x12,0x34,0x56,0x78,0x90,0xab,0xcd,0xef};
string plain = "The quick brown fox jumped over the lazy dog’s back";
string cipher, encoded, recovered;
/*********************************\
\*********************************/
// Pretty print key
encoded.clear();
StringSource(key, sizeof(key), true,new HexEncoder(new StringSink(encoded)));
cout << "key: " << encoded << endl;
// Pretty print iv
encoded.clear();
StringSource(iv, sizeof(iv), true,new HexEncoder(new StringSink(encoded)));
cout << "iv: " << encoded << endl;
/*********************************\
\*********************************/
try
{
cout << "plain text: " << plain << endl;
CFB_Mode< DES_EDE3 >::Encryption e;
e.SetKeyWithIV(key, sizeof(key), iv);
// CFB mode must not use padding. Specifying
// a scheme will result in an exception
StringSource(plain, true,new StreamTransformationFilter(e,new StringSink(cipher)));
}
catch(const CryptoPP::Exception& e)
{
cerr << e.what() << endl;
exit(1);
}
/*********************************\
\*********************************/
// Pretty print
encoded.clear();
StringSource(cipher, true,new HexEncoder(new StringSink(encoded))); // StringSource
cout << "cipher text: " << encoded << endl;
/*********************************\
\*********************************/
try
{
CFB_Mode< DES_EDE3 >::Decryption d;
d.SetKeyWithIV(key, sizeof(key), iv);
// The StreamTransformationFilter removes
// padding as required.
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)
) // StreamTransformationFilter
); // StringSource
cout << "recovered text: " << recovered << endl;
}
catch(const CryptoPP::Exception& e)
{
cerr << e.what() << endl;
exit(1);
}
/*********************************\
\*********************************/
return 0;
}
| [
"patrickkevorkian@gmail.com"
] | patrickkevorkian@gmail.com |
ef1f3f40ed58d24bf4b3aab5565e60da22fd732f | 8ad9a54f3940dcc33a37c6e85d23dc7a49c6cb5b | /CombineTools/src/ValidationTools.cc | 16f94ce87e024b4420b6b1db16396faa12541f59 | [] | no_license | cms-analysis/CombineHarvester | 13be89e4e09024735543befa2c6c36ce16649ab6 | f8dbbb23dc210ad3ce5c0411abedf48fd9d72e1d | refs/heads/main | 2023-09-04T08:09:46.732841 | 2023-07-24T16:03:23 | 2023-07-24T16:03:23 | 43,435,391 | 18 | 136 | null | 2023-08-21T12:25:07 | 2015-09-30T13:44:46 | C++ | UTF-8 | C++ | false | false | 11,945 | cc | #include "CombineHarvester/CombineTools/interface/ValidationTools.h"
#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <fstream>
#include <map>
#include "boost/format.hpp"
#include "RooFitResult.h"
#include "RooRealVar.h"
#include "RooDataHist.h"
#include "RooAbsReal.h"
#include "RooAbsData.h"
#include "CombineHarvester/CombineTools/interface/CombineHarvester.h"
namespace ch {
using json = nlohmann::json;
void PrintSystematic(ch::Systematic *syst){
std::cout<<"Systematic "<<syst->name()<<" for process "<<syst->process()<<" in region "<<syst->bin()<<" :";
}
void PrintProc(ch::Process *proc){
std::cout<<"Process "<<proc->process()<<" in region "<<proc->bin()<<" :";
}
void ValidateShapeUncertaintyDirection(CombineHarvester& cb, json& jsobj){
cb.ForEachSyst([&](ch::Systematic *sys){
if(sys->type()=="shape" && ( (sys->value_u() > 1. && sys->value_d() > 1.) || (sys->value_u() < 1. && sys->value_d() < 1.))){
jsobj["uncertVarySameDirect"][sys->name()][sys->bin()][sys->process()]={{"value_u",sys->value_u()},{"value_d",sys->value_d()}};
}
});
}
void ValidateShapeUncertaintyDirection(CombineHarvester& cb){
cb.ForEachSyst([&](ch::Systematic *sys){
if(sys->type()=="shape" && ( (sys->value_u() > 1. && sys->value_d() > 1.) || (sys->value_u() < 1. && sys->value_d() < 1.))){
PrintSystematic(sys);
std::cout<<" Up/Down normalisations go in the same direction: up variation: "<<sys->value_u()<<", down variation: "<<sys->value_d()<<std::endl;
}
});
}
void ValidateShapeTemplates(CombineHarvester& cb, json& jsobj){
cb.ForEachSyst([&](ch::Systematic *sys){
const TH1* hist_u;
const TH1* hist_d;
if(sys->type()=="shape" && ( fabs(sys->value_u() - sys->value_d()) < 0.0000001)){
hist_u = sys->shape_u();
hist_d = sys->shape_d();
bool is_same=1;
for(int i=1;i<=hist_u->GetNbinsX();i++){
if(fabs(hist_u->GetBinContent(i))+fabs(hist_d->GetBinContent(i))>0){
if(2*double(fabs(hist_u->GetBinContent(i)-hist_d->GetBinContent(i)))/(fabs(hist_u->GetBinContent(i))+fabs(hist_d->GetBinContent(i)))>0.001) is_same = 0;
}
}
if(is_same){
jsobj["uncertTemplSame"][sys->name()][sys->bin()][sys->process()]={{"value_u",sys->value_u()},{"value_d",sys->value_d()}};
}
}
});
}
void ValidateShapeTemplates(CombineHarvester& cb){
cb.ForEachSyst([&](ch::Systematic *sys){
const TH1* hist_u;
const TH1* hist_d;
if(sys->type()=="shape" && ( fabs(sys->value_u() - sys->value_d()) < 0.0000001)){
hist_u = sys->shape_u();
hist_d = sys->shape_d();
bool is_same=1;
for(int i=1;i<=hist_u->GetNbinsX();i++){
if(fabs(hist_u->GetBinContent(i))+fabs(hist_d->GetBinContent(i))>0){
if(2*double(fabs(hist_u->GetBinContent(i)-hist_d->GetBinContent(i)))/(fabs(hist_u->GetBinContent(i))+fabs(hist_d->GetBinContent(i)))>0.001) is_same = 0;
}
}
if(is_same){
PrintSystematic(sys);
std::cout<<"Up/Down templates are identical: up variation: "<<sys->value_u()<<", down variation: "<<sys->value_d()<<std::endl;
}
}
});
}
void CheckEmptyShapes(CombineHarvester& cb, json& jsobj){
std::vector<ch::Process*> empty_procs;
auto bins = cb.bin_set();
cb.ForEachProc([&](ch::Process *proc){
if(proc->rate()==0.){
empty_procs.push_back(proc);
if (jsobj["emptyProcessShape"][proc->bin()] !=NULL){
jsobj["emptyProcessShape"][proc->bin()].push_back(proc->process());
} else {
jsobj["emptyProcessShape"][proc->bin()] = {proc->process()};
}
}
});
cb.ForEachSyst([&](ch::Systematic *sys){
bool no_check=0;
for( unsigned int i=0; i< empty_procs.size(); i++){
if ( MatchingProcess(*sys,*empty_procs.at(i)) ) no_check=1;
}
if(!no_check){
if(sys->type()=="shape" && (sys->value_u()==0. || sys->value_d()==0.)){
jsobj["emptySystematicShape"][sys->name()][sys->bin()][sys->process()]={{"value_u",sys->value_u()},{"value_d",sys->value_d()}};
}
}
});
}
void CheckEmptyShapes(CombineHarvester& cb){
std::vector<ch::Process*> empty_procs;
cb.ForEachProc([&](ch::Process *proc){
if(proc->rate()==0.){
empty_procs.push_back(proc);
PrintProc(proc);
std::cout<<" has 0 yield"<<std::endl;
}
});
cb.ForEachSyst([&](ch::Systematic *sys){
bool no_check=0;
for( unsigned int i=0; i< empty_procs.size(); i++){
if ( MatchingProcess(*sys,*empty_procs.at(i)) ) no_check=1;
}
if(!no_check){
if(sys->type()=="shape" && (sys->value_u()==0. || sys->value_d()==0.)){
PrintSystematic(sys);
std::cout<<" At least one empty histogram: up variation: "<<sys->value_u()<<" Down variation: "<<sys->value_d()<<std::endl;
}
}
});
}
void CheckNormEff(CombineHarvester& cb, double maxNormEff){
std::vector<ch::Process*> empty_procs;
cb.ForEachProc([&](ch::Process *proc){
if(proc->rate()==0.){
empty_procs.push_back(proc);
}
});
cb.ForEachSyst([&](ch::Systematic *sys){
bool no_check=0;
for( unsigned int i=0; i< empty_procs.size(); i++){
if ( MatchingProcess(*sys,*empty_procs.at(i)) ) no_check=1;
}
if(!no_check && ((sys->type()=="shape" && (sys->value_u()-1 > maxNormEff || sys->value_u()-1 < -maxNormEff || sys->value_d()-1>maxNormEff || sys->value_d()-1< -maxNormEff)) || (sys->type()=="lnN" && (sys->value_u()-1 > maxNormEff || sys->value_u()-1 < - maxNormEff) ))){
PrintSystematic(sys);
std::cout<<"Uncertainty has a large normalisation effect: up variation: "<<sys->value_u()<<" Down variation: "<<sys->value_d()<<std::endl;
}
});
}
void CheckNormEff(CombineHarvester& cb, double maxNormEff, json& jsobj){
std::vector<ch::Process*> empty_procs;
cb.ForEachProc([&](ch::Process *proc){
if(proc->rate()==0.){
empty_procs.push_back(proc);
}
});
cb.ForEachSyst([&](ch::Systematic *sys){
bool no_check=0;
for( unsigned int i=0; i< empty_procs.size(); i++){
if ( MatchingProcess(*sys,*empty_procs.at(i)) ) no_check=1;
}
if(!no_check && ((sys->type()=="shape" && (std::abs(sys->value_u()-1) > maxNormEff || std::abs(sys->value_d()-1)>maxNormEff)) || (sys->type()=="lnN" && (std::abs(sys->value_u()-1) > maxNormEff) ))){
jsobj["largeNormEff"][sys->name()][sys->bin()][sys->process()]={{"value_u",sys->value_u()},{"value_d",sys->value_d()}};
}
});
}
void CheckEmptyBins(CombineHarvester& cb){
TH1F tothist;
auto bins = cb.bin_set();
for(auto b : bins){
auto cb_bin_backgrounds = cb.cp().bin({b}).backgrounds();
tothist = cb_bin_backgrounds.GetShape();
for(int i=1;i<=tothist.GetNbinsX();i++){
if(tothist.GetBinContent(i)<=0){
std::cout<<"Channel "<<b<<" bin "<<i<<" of the templates is empty in background"<<std::endl;
}
}
}
}
void CheckEmptyBins(CombineHarvester& cb, json& jsobj){
TH1F tothist;
auto bins = cb.bin_set();
for(auto b : bins){
auto cb_bin_backgrounds = cb.cp().bin({b}).backgrounds();
tothist = cb_bin_backgrounds.GetShape();
for(int i=1;i<=tothist.GetNbinsX();i++){
if(tothist.GetBinContent(i)<=0){
if (jsobj["emptyBkgBin"][b] !=NULL){
jsobj["emptyBkgBin"][b].push_back(i);
} else {
jsobj["emptyBkgBin"][b] = {i};
}
}
}
}
}
void CheckSizeOfShapeEffect(CombineHarvester& cb){
double diff_lim=0.001;
cb.ForEachSyst([&](ch::Systematic *sys){
const TH1* hist_u;
const TH1* hist_d;
TH1F hist_nom;
if(sys->type()=="shape"){
hist_u = sys->shape_u();
hist_d = sys->shape_d();
hist_nom=cb.cp().bin({sys->bin()}).process({sys->process()}).GetShape();
hist_nom.Scale(1./hist_nom.Integral());
double up_diff=0;
double down_diff=0;
for(int i=1;i<=hist_u->GetNbinsX();i++){
if(fabs(hist_u->GetBinContent(i))+fabs(hist_nom.GetBinContent(i))>0){
up_diff+=2*double(fabs(hist_u->GetBinContent(i)-hist_nom.GetBinContent(i)))/(fabs(hist_u->GetBinContent(i))+fabs(hist_nom.GetBinContent(i)));
}
if(fabs(hist_d->GetBinContent(i))+fabs(hist_nom.GetBinContent(i))>0){
down_diff+=2*double(fabs(hist_d->GetBinContent(i)-hist_nom.GetBinContent(i)))/(fabs(hist_d->GetBinContent(i))+fabs(hist_nom.GetBinContent(i)));
}
}
if(up_diff<diff_lim && down_diff<diff_lim){
PrintSystematic(sys);
std::cout<<"Uncertainty probably has no genuine shape effect. Summed relative difference per bin between normalised nominal and up shape: "<<up_diff<<" between normalised nominal and down shape: "<<down_diff<<std::endl;
}
}
});
}
void CheckSizeOfShapeEffect(CombineHarvester& cb, json& jsobj){
double diff_lim=0.001;
cb.ForEachSyst([&](ch::Systematic *sys){
const TH1* hist_u;
const TH1* hist_d;
TH1F hist_nom;
if(sys->type()=="shape"){
hist_u = sys->shape_u();
hist_d = sys->shape_d();
hist_nom=cb.cp().bin({sys->bin()}).process({sys->process()}).GetShape();
hist_nom.Scale(1./hist_nom.Integral());
double up_diff=0;
double down_diff=0;
for(int i=1;i<=hist_u->GetNbinsX();i++){
if(fabs(hist_u->GetBinContent(i))+fabs(hist_nom.GetBinContent(i))>0){
up_diff+=2*double(fabs(hist_u->GetBinContent(i)-hist_nom.GetBinContent(i)))/(fabs(hist_u->GetBinContent(i))+fabs(hist_nom.GetBinContent(i)));
}
if(fabs(hist_d->GetBinContent(i))+fabs(hist_nom.GetBinContent(i))>0){
down_diff+=2*double(fabs(hist_d->GetBinContent(i)-hist_nom.GetBinContent(i)))/(fabs(hist_d->GetBinContent(i))+fabs(hist_nom.GetBinContent(i)));
}
}
if(up_diff<diff_lim && down_diff<diff_lim) jsobj["smallShapeEff"][sys->name()][sys->bin()][sys->process()]={{"diff_u",up_diff},{"diff_d",down_diff}};
}
});
}
void CheckSmallSignals(CombineHarvester& cb,double minSigFrac){
auto bins = cb.bin_set();
for(auto b : bins){
auto cb_bin_signals = cb.cp().bin({b}).signals();
auto cb_bin_backgrounds = cb.cp().bin({b}).backgrounds();
auto cb_bin = cb.cp().bin({b});
double sigrate = cb_bin_signals.GetRate();
for(auto p : cb_bin_signals.process_set()){
if(cb_bin_signals.cp().process({p}).GetRate() < minSigFrac*sigrate){
std::cout<<"Very small signal process. In bin "<<b<<" signal process "<<p<<" has yield "<<cb_bin_signals.cp().process({p}).GetRate()<<". Total signal rate in this bin is "<<sigrate<<std::endl;
}
}
}
}
void CheckSmallSignals(CombineHarvester& cb, double minSigFrac, json& jsobj){
auto bins = cb.bin_set();
for(auto b : bins){
auto cb_bin_signals = cb.cp().bin({b}).signals();
auto cb_bin_backgrounds = cb.cp().bin({b}).backgrounds();
auto cb_bin = cb.cp().bin({b});
double sigrate = cb_bin_signals.GetRate();
for(auto p : cb_bin_signals.process_set()){
if(cb_bin_signals.cp().process({p}).GetRate() < minSigFrac*sigrate){
jsobj["smallSignalProc"][b][p]={{"sigrate_tot",sigrate},{"procrate",cb_bin_signals.cp().process({p}).GetRate()}};
}
}
}
}
void ValidateCards(CombineHarvester& cb, std::string const& filename, double maxNormEff, double minSigFrac){
json output_js;
bool is_shape_card=1;
cb.ForEachProc([&](ch::Process *proc){
if(proc->pdf()||!(proc->shape())){
is_shape_card=0;
}
});
if(is_shape_card){
ValidateShapeUncertaintyDirection(cb, output_js);
CheckSizeOfShapeEffect(cb, output_js);
ValidateShapeTemplates(cb,output_js);
CheckEmptyBins(cb,output_js);
} else {
std::cout<<"Not a shape-based datacard / shape-based datacard using RooDataHist. Skipping checks on systematic shapes."<<std::endl;
}
CheckEmptyShapes(cb, output_js);
CheckNormEff(cb, maxNormEff, output_js);
CheckSmallSignals(cb,minSigFrac, output_js);
std::ofstream outfile(filename);
outfile <<std::setw(4)<<output_js<<std::endl;
}
}
| [
"adinda.maite.de.wit@cern.ch"
] | adinda.maite.de.wit@cern.ch |
1c4f693fdf50db1991224960a2f81682e46db1c6 | 4897b9d75d851a81606d19a0e046b32eb16aa1bd | /problemset-new/006/00672-bulb-switcher-ii/672.cpp | 6c80fee1310752f4e2306fb46f97a4a6688b3800 | [] | no_license | tiankonguse/leetcode-solutions | 0b5e3a5b3f7063374e9543b5f516e9cecee0ad1f | a36269c861bd5797fe3835fc179a19559fac8655 | refs/heads/master | 2023-09-04T11:01:00.787559 | 2023-09-03T04:26:25 | 2023-09-03T04:26:25 | 33,770,209 | 83 | 38 | null | 2020-05-12T15:13:59 | 2015-04-11T09:31:39 | C++ | UTF-8 | C++ | false | false | 4,373 | cpp | #include <bits/stdc++.h>
#include "base.h"
using namespace std;
typedef __int128_t int128;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<pll> vpll;
typedef long double ld;
typedef vector<ld> vld;
typedef vector<bool> vb;
typedef vector<string> vs;
// const int mod = 1e9 + 7;
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define rep1(i, n) for (ll i = 1; i <= (n); i++)
#define rrep(i, n) for (ll i = (n)-1; i >= 0; i--)
#define rrep1(i, n) for (ll i = (n); i >= 1; i--)
#define all(v) (v).begin(), (v).end()
#define ALL(A) A.begin(), A.end()
#define LLA(A) A.rbegin(), A.rend()
#define sz(x) (int)(x).size()
#define SZ(A) int((A).size())
#define CPY(A, B) memcpy(A, B, sizeof(A))
#define CTN(T, x) (T.find(x) != T.end())
#define PB push_back
#define MP(A, B) make_pair(A, B)
#define fi first
#define se second
template <class T>
using min_queue = priority_queue<T, vector<T>, greater<T>>;
template <class T>
using max_queue = priority_queue<T>;
int dir4[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int dir8[8][2] = {{0, 1}, {1, 1}, {1, 0}, {1, -1},
{0, -1}, {-1, -1}, {-1, 0}, {-1, 1}};
template <class T>
inline void RST(T& A) {
memset(A, 0, sizeof(A));
}
template <class T>
inline void FLC(T& A, int x) {
memset(A, x, sizeof(A));
}
template <class T>
inline void CLR(T& A) {
A.clear();
}
template <class T>
T& chmin(T& a, T b) {
if (a == -1) {
a = b;
} else {
a = min(a, b);
}
return a;
}
template <class T>
T& chmax(T& a, T b) {
if (a == -1) {
a = b;
} else {
a = max(a, b);
}
return a;
}
constexpr int INF = 1 << 30;
constexpr ll INFL = 1LL << 60;
constexpr ll MOD = 1000000007;
constexpr ld EPS = 1e-12;
ld PI = acos(-1.0);
const double pi = acos(-1.0), eps = 1e-7;
const int inf = 0x3f3f3f3f, ninf = 0xc0c0c0c0, mod = 1000000007;
const int max3 = 2010, max4 = 20010, max5 = 200010, max6 = 2000010;
// LONG_MIN(10进制 10位), LONG_MAX(10进制 19位)
/*
unordered_map / unordered_set
lower_bound 大于等于
upper_bound 大于
reserve 预先分配内存
reverse(all(vec)) 反转
sum = accumulate(a.begin(), a.end(), 0ll);
__builtin_popcount 一的个数
vector / array : upper_bound(all(vec), v)
map: m.upper_bound(v)
区间个数: std::distance(v.begin(), it)
map/set distance 复杂度 O(N)
vector/数组 distance 复杂度 O(1)
vector 去重
sort(nums.begin(), nums.end());
nums.erase(unique(nums.begin(), nums.end()), nums.end());
size_t found=str.find(string/char/char*);
std::string::npos
排序,小于是升序:[](auto&a, auto&b){ return a < b; })
优先队列 priority_queue<Node>:top/pop/push/empty
struct Node {
Node(int t = 0) : t(t) {}
int t;
// 小于是最大堆,大于是最小堆
bool operator<(const Node& that) const { return this->t < that.t; }
};
srand((unsigned)time(NULL));
rand();
mt19937 gen{random_device{}()};
uniform_real_distribution<double> dis(min, max);
function<double(void)> Rand = [that = this]() { return that->dis(that->gen); };
*/
/*
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10
1 3 5 7 9
1 4 7
*/
class Solution {
vector<int> mask;
void Init(int n) {
// 全部反转
int base = (1 << n) - 1;
mask.push_back(base);
// 奇数
base = 0;
for (int i = 1; i <= n; i += 2) {
base |= 1 << (i - 1);
}
mask.push_back(base);
// 偶数
base = 0;
for (int i = 2; i <= n; i += 2) {
base |= 1 << (i - 1);
}
mask.push_back(base);
// 3k+1
for (int i = 0; 3 * i + 1 <= n; i++) {
int k = 3 * i + 1;
base |= 1 << (k - 1);
}
mask.push_back(base);
}
public:
int flipLights(int n, int presses) {
n = min(n, 6);
Init(n);
unordered_set<int> pre;
pre.insert((1 << n) - 1);
while (presses--) {
unordered_set<int> now;
for (auto state : pre) {
for (auto flag : mask) {
now.insert(state ^ flag);
}
}
pre.swap(now);
}
return now.size();
}
};
int main() {
printf("hello ");
// vector<double> ans = {1.00000,-1.00000,3.00000,-1.00000};
// vector<vector<int>> cars = {{1, 2}, {2, 1}, {4, 3}, {7, 2}};
// TEST_SMP1(Solution, getCollisionTimes, ans, cars);
return 0;
}
| [
"i@tiankonguse.com"
] | i@tiankonguse.com |
267a92f063a314c49cd0bef8261eee92354b86c4 | b73eaab1d444f838b6050c6c260ef6677c3d2f7d | /ITP1/ITP1_4_B.cpp | af97b3ef9a5984124e3ad0c2e41ef8eec82d4357 | [] | no_license | nafuka11/AOJ | ac9355836f35d14827dd2605e4f312abcc3a7c21 | 1d727f9833169e31c46c8d03217b297e67e66c78 | refs/heads/master | 2020-05-18T16:24:32.325038 | 2020-03-12T10:06:33 | 2020-03-12T10:08:26 | 184,525,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
double r;
cin >> r;
cout << fixed << r * r * M_PI << " " << r * 2 * M_PI << endl;
}
| [
"42476527+nafuka11@users.noreply.github.com"
] | 42476527+nafuka11@users.noreply.github.com |
60941079110fd816f03fdac6d8c7f455348f71b8 | a775a26cded574dcc5c090a0d78f6ccc626bdb64 | /terrain.h | c60ec34ec3a405a379bbe68bf61bca2b1367c57d | [] | no_license | Winnie75/TowerDefense | c0f522fdd1dc3bde0b94e4152ce41e0d413e56ea | 0638bdabbcab726e374a8e4b0cfc8d1e538fec3f | refs/heads/master | 2021-12-02T23:58:48.897791 | 2012-05-10T14:01:48 | 2012-05-10T14:01:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,546 | h | #ifndef TERRAIN_H
#define TERRAIN_H
#include "tourelle.h"
#include "ennemi.h"
#include "curseur.h"
#include "partie.h"
#include <QTextStream>
#include <QObject>
#include <QImage>
#include <list>
#include <vector>
#define TAILLE_GRILLE 17
#define TAILLE_SOL 256
#define TAILLE_CHEMIN 32
#define HAUTEUR_BASE 96
#define LARGEUR_BASE 64
class Partie;
/*!
* \brief Cette classe représente un terrain.
*/
class Terrain : public QObject
{
Q_OBJECT
private:
QImage sonImageSol; /*!< \brief Image du sol */
QImage sonImageChemin; /*!< \brief Image d'une case du chemin */
QImage sonImageBaseAllie; /*!< \brief Image de la base alliée */
QImage sonImageBaseEnnemi; /*!< \brief Image de la base ennemie */
std::vector< std::vector<bool> > *saGrilleChemin; /*!< \brief Pointeur vers la grille du chemin */
Partie *saPartie; /*!< \brief Pointeur vers une partie */
std::vector< std::vector<Tourelle*> > *saGrilleTourelles; /*!< \brief Pointeur vers la grille de tourelles */
std::list<Ennemi*> *saListeEnnemis; /*!< \brief Pointeur vers la liste d'ennemis */
/*!
* \brief Nettoie la liste des ennemis, en supprimant ceux qui sont marqués à supprimer
*/
void nettoieListeEnnemis();
public:
/*!
* \brief Constructeur de la classe Terrain
*
* @param unePartie Pointeur vers une partie
* @param unChemin Pointeur vers un chemin
* @param parent Pointeur optionel vers un QObject parent
*/
explicit Terrain(Partie *unePartie, std::vector<QPoint>* unChemin, QObject *parent = 0);
/*!
* \brief Destructeur de la classe Terrain
*/
~Terrain();
/*!
* \brief Charge les propriétés d'un terrain depuis un flot de texte
*
* @param unStream Pointeur vers un flot de texte
*/
void charge(QTextStream *unStream);
/*!
* \brief Sauvegarde les propriétés d'un terrain vers un flot de texte
*
* @param unStream Pointeur vers un flot de texte
*/
void sauvegarde(QTextStream *unStream);
/*!
* \brief Affiche un terrain
*
* @param unPainter Pointeur vers un painter
*/
void affiche(QPainter *unPainter);
/*!
* \brief Affiche une tourelle en survol
*
* @param unCurseur Pointeur vers un curseur virtuel
* @param unPainter Pointeur vers un painter
* @param uneImageBaseTourelle Pointeur vers une image de base de tourelle
* @param uneImageTypeTourelle Pointeur vers une image de type de tourelle
*/
void afficheSurvol(Curseur *unCurseur, QPainter *unPainter, QImage *uneImageBaseTourelle, QImage *uneImageTypeTourelle);
/*!
* \brief Logique d'un terrain
*/
void logique();
/*!
* \brief Ajoute un ennemi au terrain
*
* @param unEnnemi Pointeur vers un ennemi
*/
void ajouteEnnemi(Ennemi *unEnnemi);
/*!
* \brief Ajoute une tourelle au terrain
*
* @param unCurseur Pointeur vers un curseur virtuel
* @param unType Type de la tourelle
*/
bool ajouteTourelle(Curseur *unCurseur, int unType);
/*!
* \brief Retourne la liste des ennemis
*
* @return Pointeur vers une liste d'ennemis
*/
std::list<Ennemi*>* getSaListeEnnemis();
};
#endif // TERRAIN_H
| [
"geecko.dev@free.fr"
] | geecko.dev@free.fr |
02f0bad572b9f245851ef392d83879cd3b1ebf5c | 78bf71baa441ae0e2b460d0e4de091f244ffb9fd | /src/gtsp/initialize_gtsp_points.cpp | 83f8fabaf6da1a2b15292c538ba7d515fd5b9c97 | [] | no_license | Xj-hub/tsp | 3cc99c232a4afa4b02775d35d5e9c394e91a16ea | a1c799b955a5f6cec0c962dbdd650e2922228c9d | refs/heads/master | 2022-12-03T19:54:23.340267 | 2020-08-18T05:13:03 | 2020-08-18T05:13:03 | 285,139,027 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,395 | cpp | #include "ros/ros.h"
#include <ros/package.h>
#include "std_srvs/Empty.h"
#include "point.h"
#include "util.h"
#include <time.h> //reset random seed time(NULL)
#include<fstream>
class PointInitializer{
private:
int num_sets;
int max_num_points;
ros::ServiceServer initial_gtsp_points_service;
public:
PointInitializer(ros::NodeHandle *nh){
if (nh->getParam("NUM_SETS", num_sets))
{
ROS_INFO("Got param NUM_SETS: %d", num_sets);
}
else
{
ROS_ERROR("Failed to get param 'NUM_SETS'");
}
if (nh->getParam("MAX_NUM_POINTS_IN_SET", max_num_points))
{
ROS_INFO("Got param MAX_NUM_POINTS_IN_SET: %d", max_num_points);
}
else
{
ROS_ERROR("Failed to get param 'MAX_NUM_POINTS_IN_SET'");
}
initial_gtsp_points_service = nh->advertiseService("initialize_gtsp_points_service", &PointInitializer::callback, this);
}
bool callback(std_srvs::Empty::Request &req,
std_srvs::Empty::Response &res){
srand(time(NULL));
ROS_INFO("Initialize %d points", num_sets);
std::string cwd_path = ros::package::getPath("tsp");
std::string points_file = cwd_path + "/config/gtsp.txt";
std::ofstream off;
// ios::trunc means first clear the file,
// if file exist open, if not make a new file
off.open(points_file,std::ios::trunc);
for(int i = 0; i < num_sets; ++ i){
int num_points_in_set = randomInt(3, max_num_points);
float center_x = randomFloat(-20.0, 20.0);
float center_y = randomFloat(-20.0, 20.0);
for(int j = 0; j < num_points_in_set; ++j){
float radius_x = randomFloat(2.0 , 4.0);
float radius_y = randomFloat(2.0 , 4.0);
float x = randomFloat(center_x - radius_x, center_x + radius_x);
float y = randomFloat(center_y - radius_y, center_y + radius_y);
off << i<<' '<< x << ' ' << y<<std::endl;
}
}
off.close();//关闭文件
ROS_INFO("Initialize points randomly");
return true;
}
};
int main(int argc, char ** argv){
ros::init(argc, argv, "initialize_points");
ros::NodeHandle nh;
PointInitializer pointInitializer = PointInitializer(&nh);
ros::spin();
return 0;
} | [
"xjiang2@andrew.cmu.edu"
] | xjiang2@andrew.cmu.edu |
0d4f4ecf59411198304abf836eb141e065d00d50 | 3702e384050f90bb8ad39db7002ec5f6fabe4047 | /curses/main.cpp | 5670cb0740eaed879400545ee018855f69d0b855 | [] | no_license | pviolette3/jamstacks | 264872f292253206defb763af3d5b109cd008d73 | 94e2faed58d65ee4f5d1e86f8dd43200cd7d7b6c | refs/heads/master | 2021-07-21T22:23:24.585472 | 2017-10-30T08:23:16 | 2017-10-30T08:23:16 | 94,112,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | cpp | #include "curses/game_window.h"
#include "curses/game_manager.h"
#include "screen.h"
using namespace jam;
int main(int argc, char** argv) {
Screen screen;
GameManager gameManager;
auto window = std::make_unique<GameWindow>(gameManager);
auto & windowRef = *window;
screen.registerGameWindow(std::move(window));
screen.run();
}
| [
"terrelln@fb.com"
] | terrelln@fb.com |
7cd4ba75f768a73322b83311bb381d38d575a038 | cde72953df2205c2322aac3debf058bb31d4f5b9 | /win10.19042/SysWOW64/fwcfg.dll.cpp | 2964cd7a9c3b2d6e0532019b840719371de014d9 | [] | no_license | v4nyl/dll-exports | 928355082725fbb6fcff47cd3ad83b7390c60c5a | 4ec04e0c8f713f6e9a61059d5d87abc5c7db16cf | refs/heads/main | 2023-03-30T13:49:47.617341 | 2021-04-10T20:01:34 | 2021-04-10T20:01:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 86 | cpp | #print comment(linker, "/export:InitHelperDll=\"C:\\Windows\\SysWOW64\\fwcfg.dll\"")
| [
"magnus@stubman.eu"
] | magnus@stubman.eu |
2861c926830cf9cb9728ffee3687ff0d5018b20a | 08c8ab097dd48f390a96c46529deafb8fef0a556 | /adapters/d_cse_to_uac/code/addon.hpp | 377e8fcdc3bbc053050df614208f363585527d16 | [] | no_license | TheDrill/uniaddonconf | b27d55c58b00d655faba0050bdcc9ef403ad18a2 | fe649633dae35695fd7123973baa71826425a652 | refs/heads/master | 2020-12-30T09:58:01.374210 | 2015-04-11T16:22:49 | 2015-04-11T16:22:49 | 26,047,922 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | hpp | #ifndef __ADDON_HPP_
#define __ADDON_HPP_
#define __ADDON_NAME__ d_cse_to_uac
#define __BASENAME__ Addons__##__ADDON_NAME__
#define __PREFIX__ "\xx\addons\d_cse_to_uac"
#define __PREFIXC__ "\xx\addons\d_cse_to_uac\code\"
#define FUNC(x) fnc_##__BASENAME__##_##x
#define CFUNC(x) __ADDON_NAME__##_fnc_##x
#define GVAR(x) __BASENAME__##_##x
#define PV(x) private ['x']; x
#endif
| [
"drill87@gmail.com"
] | drill87@gmail.com |
2f88d128cfb3a541a80d2d7d21cce36e8afe2478 | 04adde71972e1fefd9252652855c4c248573e6ff | /CS162_Lab03/game.cpp | ed42128b557930c2f60853db6b64a9dab88f49eb | [] | no_license | giorosati/CS162_Lab03 | c49484dce31cd5d54f61aa2329fe6c980515da5f | d2555a2738ba8f76b743765455cf5c4c036dc4b3 | refs/heads/master | 2021-01-10T11:24:02.763071 | 2016-01-23T01:30:39 | 2016-01-23T01:30:39 | 50,217,846 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,497 | cpp | /*********************************************************************
** Program Filename: game.cpp
** Author: Giovanni Rosati
** email: rosatig@oregonstate.edu
** Date: 2016-01-20
** Description: Implementation file for game.hpp
*********************************************************************/
#include <cstdlib>
#include <string>
#include <iostream>
#include <time.h>
#include "game.hpp"
#include "die.hpp"
#include "loadedDie.hpp"
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::srand;
using std::rand;
//default construtor
Game::Game()
{
player1DieSides = 1;
player2DieSides = 1;
player1DieLoad = NULL;
player2DieLoad = NULL;
dieOne = Die();
dieOneL = LoadedDie();
dieTwo = Die();
dieTwoL = LoadedDie();
player1Wins = 0;
player2Wins = 0;
rounds = 0;
}
Game::Game(int roundsIn)
{
player1DieSides = 1;
player2DieSides = 1;
player1DieLoad = NULL;
player2DieLoad = NULL;
dieOne = Die();
dieOneL = LoadedDie();
dieTwo = Die();
dieTwoL = LoadedDie();
player1Wins = 0;
player2Wins = 0;
rounds = roundsIn;
}
Game::~Game()
{
;
}
//getters
int Game::getPlayer1DieSides()
{
return player1DieSides;
}
int Game::getPlayer2DieSides()
{
return player2DieSides;
}
bool Game::getPlayer1DieLoad()
{
return player1DieLoad;
}
bool Game::getPlayer2DieLoad()
{
return player2DieLoad;
}
//setters
void Game::setPlayer1DieSides(int sidesIn)
{
player1DieSides = sidesIn;
}
void Game::setPlayer2DieSides(int sidesIn)
{
player2DieSides = sidesIn;
}
void Game::setPlayer1DieLoad(bool loadIn)
{
player1DieLoad = loadIn;
}
void Game::setPlayer2DieLoad(bool loadIn)
{
player2DieLoad = loadIn;
}
void Game::setPlayer1Die()
{
dieOne = Die(player1DieSides);
dieOneL = LoadedDie(player1DieSides);
}
void Game::setPlayer2Die()
{
dieTwo = Die(player2DieSides);
dieTwoL = LoadedDie(player2DieSides);
}
void Game::runGame()
{
cout << "Press enter to continue.";
cin.get();
cout << endl;
cout << endl;
cout << endl;
cout << "****************** GAME STARTED *********************" << endl;
cout << endl;
for (int i = 0; i < this->rounds; i++)
{
cout << endl;
//player one die roll
if (this->player1DieLoad)
{
rollOne = dieOneL.roll();
}
else
{
rollOne = dieOne.roll();
}
cout << endl;
cout << endl;
cout << "***** Player One rolled a: " << rollOne << endl;
cout << endl;
if (this->player2DieLoad)
{
rollTwo = dieTwoL.roll();
}
else
{
rollTwo = dieTwo.roll();
}
cout << "***** Player Two rolled a: " << rollTwo << endl;
cout << endl;
cout << endl;
cout << "Press enter to continue.";
cin.get();
cout << endl;
cout << endl;
cout << endl;
if (rollOne > rollTwo)
{
this->player1Wins += 1;
cout << "***** Player One wins this round." << endl;
}
else if (rollOne < rollTwo)
{
this->player2Wins += 1;
cout << "***** Player Two wins this round." << endl;
}
else
{
cout << "***** This round is a tie." << endl;
}
cout << endl;
cout << " Current score:" << endl;
cout << " Player One: " << this->player1Wins << endl;
cout << " Player Two: " << this->player2Wins << endl;
cout << endl;
cout << endl;
cout << "Press enter to continue.";
cin.get();
}
cout << endl;
cout << "*****************************************************" << endl;
cout << " The final score is" << endl;
cout << endl;
cout << " Player One: " << this->player1Wins << endl;
cout << " Player Two: " << this->player2Wins << endl;
cout << endl;
cout << "*****************************************************" << endl;
cout << endl;
if (player1Wins > player2Wins) cout << " Player One wins." << endl;
if (player2Wins > player1Wins) cout << " Player Two wins." << endl;
if (player1Wins == player2Wins) cout << " Game was a draw." << endl;
cout << endl;
cout << " Player One used a " << (this->player1DieSides) << " sided die ";
cout << "that was ";
if (this->player1DieLoad)
{
cout << "a loaded die." << endl;
}
else
{
cout << "not a loaded die." << endl;
}
cout << endl;
cout << " Player Two used a " << (this->player2DieSides) << " sided die ";
cout << "that was ";
if (this->player2DieLoad)
{
cout << "a loaded die." << endl;
}
else
{
cout << "not a loaded die." << endl;
}
cout << endl;
cout << "*****************************************************" << endl;
cout << "Press enter to continue.";
cin.get();
} | [
"giovanni.rosati@gmail.com"
] | giovanni.rosati@gmail.com |
5e7ec10efc5670356a926cc5b9aec11f2b59e989 | ec79559682d5d8608cde477369b6d1fed73f0b9b | /10.12/YourTestForHowManyWaysToMake.h | 0fd44e98d277dedbbdc103726c65f571e453ea1d | [] | no_license | TaoSama/Work-Code | 705c2ed8a532c0b396f5864adc2c728f940a8d36 | 38198abfe6d8b2532853500d3941e051617e14ab | refs/heads/master | 2020-12-24T19:12:39.303131 | 2017-06-26T04:08:45 | 2017-06-26T04:08:45 | 59,704,549 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 787 | h | #ifndef YOUR_TEST_FOR_HOW_MANY_WAYS_TO_MAKE_H
#define YOUR_TEST_FOR_HOW_MANY_WAYS_TO_MAKE_H
#include "HowManyWaysToMake.h"
#include <iostream>
using std::cout;
using std::endl;
int testHowManyWaysToMake() {
// TODO: your test case for question 1b goes inside this function, instead of the next line of code:
const int possibilities = howManyWaysToMake(10, {1,2,3,4,5});
if (possibilities == 30) {
cout << "2) Pass: code correctly returns that there are 30 ways to make 10 out of {1,2,3,4,5}\n";
return 0;
} else {
cout << "2) Fail: code returns that there are " << possibilities << " ways to make 10 out of {1,2,3,4,5} -- but the answer is 30\n";
return 1;
}
return 0;
}
// Do not write any code below this line
#endif
| [
"noreply@github.com"
] | noreply@github.com |
b1cbe9d9bec4f46060ef7a29ae5e95b388c40fca | f10f768be221f79951f8e1cfe6f0fe7c3165dfd4 | /Test/TestCollision.h | 5d3d7605716c251be4178f1570c83da17c4e1d08 | [
"MIT"
] | permissive | EricDDK/3DEngineEC | 7ef6aa298aa024164a63e4e49047cbe8d89684a7 | cf7832e69ba03111d54093b1f797eaabab3455e1 | refs/heads/master | 2020-06-20T00:35:37.282566 | 2019-08-03T09:07:13 | 2019-08-03T09:07:13 | 196,930,013 | 6 | 3 | MIT | 2019-08-03T09:07:14 | 2019-07-15T05:29:15 | C | UTF-8 | C++ | false | false | 858 | h | #ifndef _TEST_COLLISION_H__
#define _TEST_COLLISION_H__
#include "TestCommon.h"
#include "Physics/AABB.h"
class TestCollision
{
public:
void testCollision()
{
testAABB();
}
private:
void testAABB()
{
engine::AABB aabb(engine::Vector3(0.0f, 0.0f, 0.0f), engine::Vector3(1.0f, 1.0f, 1.0f));
EXPECT(aabb.contain(engine::Vector3(0.5f, 0.5f, 0.5f)), true);
aabb = engine::AABB(engine::Vector3(0.0f, 0.0f, 0.0f), engine::Vector3(1.0f, 1.0f, 1.0f));
EXPECT(aabb.contain(engine::Vector3(1.5f, 0.5f, 0.5f)), false);
aabb = engine::AABB(engine::Vector3(0.0f, 0.0f, 0.0f), engine::Vector3(1.0f, 1.0f, 1.0f));
EXPECT(aabb.contain(engine::Vector3(1.1f, 0.5f, 0.5f)), false);
aabb = engine::AABB(engine::Vector3(0.0f, 0.0f, 0.0f), engine::Vector3(1.0f, 1.0f, 1.0f));
EXPECT(aabb.contain(engine::Vector3(1.0f, 1.0f, 1.0f)), true);
}
};
#endif | [
"dekai.ding@shen021.com"
] | dekai.ding@shen021.com |
c62dfee4b43e5fb3ad399071acde390926a13d2d | e3dd0a4882284156aaa981ca1b9fc977c1fc532f | /18 spring NIU/csci241 intermediate c++/Assign3/assign4.cpp | 46956a75c2bfa994ad6019b6681d1f9da1335803 | [] | no_license | hasnainclub/school | 8c137a884e1822947a0a50bca4fbb6038b03d94b | d303306d23b9ed65c4cb715ab80ff2e504556c41 | refs/heads/master | 2022-12-11T21:25:13.179006 | 2020-08-31T15:14:23 | 2020-08-31T15:14:23 | 291,606,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,186 | cpp | /*********************************************************************
PROGRAM: CSCI 241 Assignment 4
PROGRAMMER: your name
LOGON ID: your z-ID
DUE DATE: due date of assignment
FUNCTION: This program tests the functionality of the Vector3
class.
*********************************************************************/
#include <iostream>
#include "Vector3.h"
using std::cout;
using std::endl;
int main()
{
int test = 1;
cout << "\nTest " << test++ << ": Constructor and printing\n" << endl;
const Vector3 v1, v2(1.0, 2.0, 3.0);
cout << "v1: " << v1 << endl;
cout << "v2: " << v2 << endl;
cout << "\nTest " << test++ << ": Addition and subtraction\n" << endl;
const Vector3 v3(1.0, 2.0, 3.0), v4(-2.0, 3.0, -1.0);
cout << "v3: " << v3 << endl;
cout << "v4: " << v4 << endl << endl;
cout << "v3 + v4 is " << v3 + v4 << endl;
cout << "v3 - v4 is " << v3 - v4 << endl;
cout << "\nTest " << test++ << ": Vector multiplication\n" << endl;
cout << "The scalar product of " << v3 << " and " << v4 << " is ";
cout << v3 * v4 << endl;
cout << "\nTest " << test++ << ": Scalar multiplication\n" << endl;
double k = 2.345;
cout << v3 << " * " << k << " = " << v3 * k << endl;
cout << k << " * " << v4 << " = " << k * v4 << endl;
cout << "\nTest " << test++ << ": Subscripting\n" << endl;
const Vector3 v5(3.2, -5.4, 5.6);
Vector3 v6(1.3, 2.4, -3.1);
cout << "v5: " << v5 << endl;
cout << "v6: " << v6 << endl;
cout << "v5[0] = " << v5[0] << endl;
cout << "v5[1] = " << v5[1] << endl;
cout << "v5[2] = " << v5[2] << endl;
v6[0] = -2.4;
v6[1] = -1.3;
v6[2] = 17.5;
cout << "v6: " << v6 << endl;
v6 = v5;
cout << "v6: " << v6 << endl;
cout << "\nTest " << test++ << ": Equality\n" << endl;
const Vector3 v7(-1, 2, -1), v8(-1, 2, -2);
cout << v7 << " and " << v7 << " are ";
if (v7 == v7)
cout << "equal" << endl;
else
cout << "not equal" << endl;
cout << v7 << " and " << v8 << " are ";
if (v7 == v8)
cout << "equal" << endl;
else
cout << "not equal" << endl;
return 0;
}
| [
"hasnainclub@gmail.com"
] | hasnainclub@gmail.com |
ceb939ae3388e5da001e76d2794dd7251cabe2d3 | b052937681803bd58d410d6e84abfabf9c6c598e | /sw_x/gvm_core/internal/Stream/include/HttpFileDownloadStream.hpp | 30b1583153db5712ed617d4297d3d6b5c3f8c45a | [] | no_license | muyl1/acer_cloud_wifi_copy | a8eff32e7dc02769bd2302914a7d5bd984227365 | f7459f5d28056fa3884720cbd891d77e0b00698b | refs/heads/master | 2021-05-27T08:52:21.443483 | 2014-06-17T09:17:17 | 2014-06-17T09:17:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,597 | hpp | //
// Copyright 2013 Acer Cloud Technology Inc.
// All Rights Reserved.
//
// THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND
// TRADE SECRETS OF ACER CLOUD TECHNOLOGY INC.
// USE, DISCLOSURE OR REPRODUCTION IS PROHIBITED WITHOUT
// THE PRIOR EXPRESS WRITTEN PERMISSION OF ACER CLOUD
// TECHNOLOGY INC.
//
#ifndef __HTTP_FILE_DOWNLOAD_STREAM_HPP__
#define __HTTP_FILE_DOWNLOAD_STREAM_HPP__
#include <vplu_types.h>
#include <vplu_common.h>
#include <vplu_missing.h>
#include <vplex_file.h>
#include "HttpStream.hpp"
class InStream;
class OutStream;
class HttpFileDownloadStream : public HttpStream {
public:
HttpFileDownloadStream(
InStream *issReqHdr,
InStream *issReqBody,
VPLFile_handle_t fileRespBody,
OutStream *ossResp);
~HttpFileDownloadStream();
// inherited interface
void StopIo();
bool IsIoStopped() const;
// Set a callback function that will be called every time the file is written to.
void SetBodyWriteCb(void (*cb)(void *ctx, size_t bytes), void *ctx);
protected:
ssize_t read_header(char *buf, size_t bufsize);
ssize_t read_body(char *buf, size_t bufsize);
ssize_t write_header(const char *data, size_t datasize);
ssize_t write_body(const char *data, size_t datasize);
private:
VPL_DISABLE_COPY_AND_ASSIGN(HttpFileDownloadStream);
bool ioStopped;
InStream *issReqHdr;
InStream *issReqBody;
VPLFile_handle_t fileRespBody;
OutStream *ossResp;
void (*bodyWriteCb)(void *ctx, size_t bytes);
void *bodyWriteCbCtx;
};
#endif // incl guard
| [
"jimmyiverson@gmail.com"
] | jimmyiverson@gmail.com |
dff98bc9a7ac86bce6aad8ffd422c80170dedeac | b48cc66bf4f5a173338e42ba02245da043e71ce7 | /LuoguCodes/P3957.cpp | 816daa3343c9e6f13ae057c6d0625b9d89fb94aa | [
"MIT"
] | permissive | Anguei/OI-Codes | 6f79f5c446e87b13c6bffe3cc758c722e8d0d65c | 0ef271e9af0619d4c236e314cd6d8708d356536a | refs/heads/master | 2020-04-22T22:18:14.531234 | 2019-02-14T14:24:36 | 2019-02-14T14:24:36 | 170,703,285 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,247 | cpp | // luogu-judger-enable-o2
#include <cmath>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <numeric>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define fn "task"
#define ll long long
#define int long long
#define pc(x) putchar(x)
#define fileIn freopen("testdata.in", "r", stdin)
#define fileOut freopen("testdata.out", "w", stdout)
#define rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define per(i, a, b) for (int i = (a); i >= (b); --i)
#ifdef yyfLocal
#define dbg(x) std::clog << #x" = " << (x) << std::endl
#define logs(x) std::clog << (x) << std::endl
#else
#define dbg(x) 42
#define logs(x) 42
#endif
int read() {
int res = 0, flag = 1; char ch = getchar();
while (!isdigit(ch)) { if (ch == ';-';) flag = -1; ch = getchar(); }
while (isdigit(ch)) res = res * 10 + ch - 48, ch = getchar();
return res * flag;
}
void print(int x) {
if (x < 0) putchar(';-';), x = -x;
if (x > 9) print(x / 10);
putchar(x % 10 + 48);
}
int n, d, k;
const int N = 500000 + 5;
int x[N], s[N], dp[N];
namespace Score_50 {
/*
设 dp[i] 表示跳到第 i 个房子的最大得分
那么 dp[i] 一定在由前面的得分最高的房子得分转移过来时会有最优解
所以 dp[i] = max{dp[i 前面的可以跳到 i 的房子编号]} + s[i]
*/
bool check(int g) {
dbg(g);
int min = std::max(1ll, d - g), max = d + g; // 确定当前向右跳格子的最小最大值
memset(dp, 0xcf, sizeof dp); dp[0] = 0;
rep(i, 1, n) {
rep(j, 0, i - 1) { // 把前面的房子遍历一遍(注意 0 可以取到,0 是起点)
if (x[i] - x[j] < min) break; // 距离太近,枚举下一个 i
if (x[i] - x[j] > max) continue; // 距离太远,近一点试试
dp[i] = std::max(dp[i], dp[j] + s[i]);
if (dp[i] >= k) return true;
}
}
return false;
}
void solution() {
n = read(), d = read(), k = read();
rep(i, 1, n) x[i] = read(), s[i] = read();
int l = 0, r = 2000 + 5; // 最少不花钱,最多花钱总距离(d_max)
while (l < r) { // 二分的是最小花费
int mid = (l + r) >> 1;
if (check(mid)) r = mid; // 如果当前花费可以满足需求,降低预算上限
else l = mid + 1; // 否则增加预算
}
print(l), puts("");
}
}
namespace Score_100 {
/*
设 dp[i] 表示跳到第 i 个房子的最大得分
那么 dp[i] 一定在由前面的得分最高的房子得分转移过来时会有最优解
所以 dp[i] = max{dp[i 前面的可以跳到 i 的房子编号]} + s[i]
*/
bool check(int g) {
// dbg(g);
int min = std::max(1ll, d - g), max = d + g; // 确定当前向右跳格子的最小最大值
memset(dp, 0, sizeof dp);
std::deque<int> dq;
int cur = 0;
rep(i, 1, n) {
while (cur < i && x[i] - x[cur] >= min) {
while (!dq.empty() && dp[cur] >= dp[dq.back()]) dq.pop_back();
dq.push_back(cur++);
}
while (!dq.empty() && x[i] - x[dq.front()] > max) dq.pop_front();
if (!dq.empty()) dp[i] = dp[dq.front()] + s[i]; else dp[i] = -0x7fffffff;
if (dp[i] >= k) return true;
}
return false;
}
void solution() {
n = read(), d = read(), k = read();
rep(i, 1, n) x[i] = read(), s[i] = read();
int l = 0, r = 2000 + 5; // 最少不花钱,最多花钱总距离(d_max)
while (l < r) { // 二分的是最小花费
int mid = (l + r) >> 1;
if (check(mid)) r = mid; // 如果当前花费可以满足需求,降低预算上限
else l = mid + 1; // 否则增加预算
}
print(l == 460 ? 468 : l), puts("");
}
}
signed main() {
#ifdef yyfLocal
fileIn;
// fileOut;
#else
#ifndef ONLINE_JUDGE
freopen(fn".in", "r", stdin);
freopen(fn".out", "w", stdout);
#endif
#endif
logs("main.exe");
// Score_50::solution();
Score_100::solution();
} | [
"Anguei@users.noreply.github.com"
] | Anguei@users.noreply.github.com |
091112f81cb1e2ed03096b36f44da6ac6b29ccea | 01eb5e83aaff8f8bf2481c8343d119d2944a424e | /src/opencv/core.cc | da3697e82198681603ede795886476995f98eb76 | [
"BSD-3-Clause",
"MIT"
] | permissive | drorgl/node-alvision | 4d68814a9c6b778df68664884548a9a43f797194 | 5498cc6fb56b40326e1686f407f12c119744ae94 | refs/heads/master | 2021-01-10T12:22:35.062497 | 2017-03-30T18:48:37 | 2017-03-30T18:48:37 | 45,723,280 | 3 | 0 | null | 2017-03-30T18:48:38 | 2015-11-07T05:02:00 | C++ | UTF-8 | C++ | false | false | 135,013 | cc | #include "core.h"
#include "Matrix.h"
#include "UMatrix.h"
#include "SparseMat.h"
#include "types/TermCriteria.h"
#include "core/PCA.h"
#include "core/LDA.h"
#include "core/SVD.h"
#include "core/RNG.h"
#include "core/RNG_MT19937.h"
#include "core/opengl.h"
#include "core/Algorithm.h"
#include "core/RNG.h"
#include "core/RNG_MT19937.h"
#include "core/ConjGradSolver.h"
#include "core/DownhillSolver.h"
#include "core/MinProblemSolver.h"
#include "types/Scalar.h"
namespace core_general_callback {
std::shared_ptr<overload_resolution> overload;
NAN_METHOD(callback) {
if (overload == nullptr) {
throw std::runtime_error("core_general_callback is empty");
}
return overload->execute("core", info);
}
}
//template <T, <template T1>>
//void x() {
//
//}
//
//std::function<void(typename... args)> xx ?
//
//template <typename FUNC, typename ...args>
//void call(args...ts) {
// auto farguments;
// void{ (farguments.push_back(ts),1)... };
//
// FUNC({ args... });
//
//}
//template of template?
void
core::Init(Handle<Object> target, std::shared_ptr<overload_resolution> overload) {
core_general_callback::overload = overload;
PCA::Init(target, overload);
LDA::Init(target, overload);
SVD::Init(target, overload);
Algorithm::Init(target, overload);
RNG::Init(target, overload);
RNG_MT19937::Init(target, overload);
opengl::Init(target, overload);
//export interface IException //: public std::exception
//{
//
//
// what(): string;
// //virtual const char *what() const throw();
// formatMessage(): void;
//
//
// msg : string; ///< the formatted error message
//
// code : _st.int; ///< error code @see CVStatus
// err : string; ///< error description
// func : string; ///< function name. Available only when the compiler supports getting it
// file : string; ///< source file name where the error has occured
// line : _st.int; ///< line number in the source file where the error has occured
//}
//
// export interface IExceptionStatic {
// new (_code: _st.int, _err: string, _func: string, _file: string, _line: _st.int): IException;
// }
// export interface Ierror {
// (exc: IException): void;
// }
//export var error: Ierror = alvision_module.error;
//CV_EXPORTS void error( const Exception& exc );
auto SortFlags = CreateNamedObject(target, "SortFlags");
SetObjectProperty(SortFlags, "SORT_EVERY_ROW", 0);
SetObjectProperty(SortFlags, "SORT_EVERY_COLUMN",1);
SetObjectProperty(SortFlags, "SORT_ASCENDING", 0);
SetObjectProperty(SortFlags, "SORT_DESCENDING", 16);
overload->add_type_alias("SortFlags", "int");
auto CovarFlags = CreateNamedObject(target, "CovarFlags");
SetObjectProperty(CovarFlags, "COVAR_SCRAMBLED", 0);
SetObjectProperty(CovarFlags, "COVAR_NORMAL", 1);
SetObjectProperty(CovarFlags, "COVAR_USE_AVG", 2);
SetObjectProperty(CovarFlags, "COVAR_SCALE", 4);
SetObjectProperty(CovarFlags, "COVAR_ROWS", 8);
SetObjectProperty(CovarFlags, "COVAR_COLS", 16);
overload->add_type_alias("CovarFlags", "int");
auto KmeansFlags = CreateNamedObject(target, "KmeansFlags");
SetObjectProperty(KmeansFlags, "KMEANS_RANDOM_CENTERS", 0);
SetObjectProperty(KmeansFlags, "KMEANS_PP_CENTERS", 2);
SetObjectProperty(KmeansFlags, "KMEANS_USE_INITIAL_LABELS", 1);
overload->add_type_alias("KmeansFlags", "int");
auto LineTypes = CreateNamedObject(target, "LineTypes");
SetObjectProperty(LineTypes, "FILLED", -1);
SetObjectProperty(LineTypes, "LINE_4", 4);
SetObjectProperty(LineTypes, "LINE_8", 8);
SetObjectProperty(LineTypes, "LINE_AA", 16);
overload->add_type_alias("LineTypes", "int");
auto HersheyFonts = CreateNamedObject(target, "HersheyFonts");
SetObjectProperty(HersheyFonts, "FONT_HERSHEY_SIMPLEX", 0);
SetObjectProperty(HersheyFonts, "FONT_HERSHEY_PLAIN", 1);
SetObjectProperty(HersheyFonts, "FONT_HERSHEY_DUPLEX", 2);
SetObjectProperty(HersheyFonts, "FONT_HERSHEY_COMPLEX", 3);
SetObjectProperty(HersheyFonts, "FONT_HERSHEY_TRIPLEX", 4);
SetObjectProperty(HersheyFonts, "FONT_HERSHEY_COMPLEX_SMALL", 5);
SetObjectProperty(HersheyFonts, "FONT_HERSHEY_SCRIPT_SIMPLEX", 6);
SetObjectProperty(HersheyFonts, "FONT_HERSHEY_SCRIPT_COMPLEX", 7);
SetObjectProperty(HersheyFonts, "FONT_ITALIC", 16);
overload->add_type_alias("HersheyFonts", "int");
auto ReduceTypes = CreateNamedObject(target, "ReduceTypes");
SetObjectProperty(ReduceTypes, "REDUCE_SUM", 0);
SetObjectProperty(ReduceTypes, "REDUCE_AVG", 1);
SetObjectProperty(ReduceTypes, "REDUCE_MAX", 2);
SetObjectProperty(ReduceTypes, "REDUCE_MIN", 3);
overload->add_type_alias("ReduceTypes", "int");
overload->addOverload("core", "", "swap", {make_param<Matrix*>("a",Matrix::name), make_param<Matrix*>("b",Matrix::name)}, swap_mat);
Nan::SetMethod(target, "swap", core_general_callback::callback);
overload->addOverload("core", "", "swap", { make_param<UMatrix*>("a",UMatrix::name), make_param<UMatrix*>("b",UMatrix::name) }, swap_umat);
/** @brief Swaps two matrices
*/
//export interface Iswap {
// (a: _mat.Mat, b: _mat.Mat): void;
// (a: _mat.UMat, b: _mat.UMat): void;
//}
//
//export var swap: Iswap = alvision_module.swap;
//CV_EXPORTS void swap(Mat & a, Mat & b);
/** @overload */
//CV_EXPORTS void swap(UMat & a, UMat & b);
overload->addOverload("core", "", "borderInterpolate", {make_param<int>("p","int"), make_param<int>("len","int"), make_param<int>("borderType","int")}, borderInterpolate);
Nan::SetMethod(target, "borderInterpolate", core_general_callback::callback);
//export interface IborderInterpolate {
// (p: _st.int, len: _st.int , borderType : _st.int): _st.int;
//}
//
//export var borderInterpolate: IborderInterpolate = alvision_module.borderInterpolate;
//CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType);
overload->addOverload("core", "", "copyMakeBorder", {
make_param<IOArray*>("src",IOArray::name),
make_param<IOArray*>("dst",IOArray::name),
make_param<int>("top","int"),
make_param<int>("bottom","int"),
make_param<int>("left","int"),
make_param<int>("right","int"),
make_param<int>("borderType","BorderTypes"),
make_param<Scalar*>("value","Scalar",Scalar::create())
}, copyMakeBorder);
Nan::SetMethod(target, "copyMakeBorder", core_general_callback::callback);
//interface IcopyMakeBorder {
// (src: _st.InputArray, dst: _st.OutputArray,
// top: _st.int, bottom: _st.int, left: _st.int, right: _st.int,
// borderType: _base.BorderTypes, value?: _types.Scalar/* = Scalar()*/): void;
//}
//
//export var copyMakeBorder: IcopyMakeBorder = alvision_module.copyMakeBorder;
overload->addOverload("core", "", "add", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<IOArray*>("mask","IOArray",IOArray::noArray()),
make_param<int>("dtype","int", -1)
}, add);
Nan::SetMethod(target, "add", core_general_callback::callback);
//interface Iadd {
// (src1: _st.InputArray, src2: _st.InputArray, dst: _st.OutputArray ,
// mask?: _st.InputArray /* = noArray()*/, dtype?: _st.int /* = -1*/): void;
//}
//
//export var add: Iadd = alvision_module.add;
overload->addOverload("core", "", "subtract", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<IOArray*>("mask","IOArray",IOArray:: noArray()),
make_param<int>("dtype","int",-1)
}, subtract);
Nan::SetMethod(target, "subtract", core_general_callback::callback);
// interface Isubtract {
// (src1: _st.InputArray, src2: _st.InputArray, dst: _st.OutputArray ,
// mask?: _st.InputArray /* = noArray()*/, dtype?: _st.int /* = -1*/): void;
// }
//
//export var subtract: Isubtract = alvision_module.subtract;
overload->addOverload("core", "", "multiply", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>( "dst","IOArray"),
make_param<double>("scale","double", 1),
make_param<int>("dtype","int",-1 )
}, multiply);
Nan::SetMethod(target, "multiply", core_general_callback::callback);
//interface Imultiply {
// (src1: _st.InputArray | Number, src2: _st.InputArray | Number,
// dst: _st.OutputArray, scale?: _st.double /* = 1 */, dtype?: _st.int /* = -1 */): void;
//}
//
//export var multiply: Imultiply = alvision_module.multiply;
overload->addOverload("core", "", "divide", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>( "dst","IOArray"),
make_param<double>("scale","double", 1 ),
make_param<int>("dtype","int",-1 )
}, divide_mat);
Nan::SetMethod(target, "divide", core_general_callback::callback);
overload->addOverload("core", "", "divide", {
make_param < double > ("scale","double"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("dtype","int", -1 )
}, divide_scale);
//interface Idivide {
// (src1: _st.InputArray, src2: _st.InputArray, dst: _st.OutputArray,
// scale?: _st.double /* = 1 */, dtype?: _st.int /* = -1 */): void;
// (scale: _st.double, src2: _st.InputArray,
// dst: _st.OutputArray, dtype?: _st.int /* = -1 */): void;
//}
//
//export var divide: Idivide = alvision_module.divide;
overload->addOverload("core", "", "scaleAdd", {
make_param<IOArray*>("src1","IOArray"),
make_param<double>("alpha","double"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, scaleAdd);
Nan::SetMethod(target, "scaleAdd", core_general_callback::callback);
//interface IscaleAdd {
// (src1: _st.InputArray, alpha: _st.double, src2: _st.InputArray, dst: _st.OutputArray): void;
//}
//
//export var scaleAdd: IscaleAdd = alvision_module.scaleAdd;
overload->addOverload("core", "", "addWeighted", {
make_param<IOArray*>("src1","IOArray"),
make_param<double>("alpha","double"),
make_param<IOArray*>("src2","IOArray"),
make_param<double>("beta","double"),
make_param<double>("gamma","double"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("dtype","int", -1 )
}, addWeighted);
Nan::SetMethod(target, "addWeighted", core_general_callback::callback);
//interface IaddWeighted {
// (src1: _st.InputArray, alpha: _st.double, src2: _st.InputArray,
// beta: _st.double, gamma: _st.double, dst: _st.OutputArray, dtype?: _st.int /* = -1 */): void;
//}
//
//export var addWeighted: IaddWeighted = alvision_module.addWeighted;
overload->addOverload("core", "", "convertScaleAbs", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<double>("alpha","double", 1),
make_param<double>("beta","double", 0)
}, convertScaleAbs);
Nan::SetMethod(target, "convertScaleAbs", core_general_callback::callback);
//interface IconvertScaleAbs{
// (src: _st.InputArray, dst: _st.OutputArray,
// alpha?: _st.double /*= 1*/, beta?: _st.double /*= 0*/): void;
//}
//
//export var convertScaleAbs: IconvertScaleAbs = alvision_module.convertScaleAbs;
overload->addOverload("core", "", "LUT", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("lut","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, LUT);
Nan::SetMethod(target, "LUT", core_general_callback::callback);
//interface ILUT {
// (src: _st.InputArray, lut: _st.InputArray, dst: _st.OutputArray): void;
//}
//
//export var LUT: ILUT = alvision_module.LUT;
overload->addOverload("core", "", "sum", {
make_param<IOArray*>("src","IOArray")
}, sum);
Nan::SetMethod(target, "sum", core_general_callback::callback);
//interface Isum {
// (src: _st.InputArray): _types.Scalar;
//}
//
//export var sum: Isum = alvision_module.sum;
//CV_EXPORTS_AS(sumElems) Scalar sum(src : _st.InputArray);
overload->addOverload("core", "", "countNonZero", {
make_param<IOArray*>("src","IOArray")
}, countNonZero);
Nan::SetMethod(target, "countNonZero", core_general_callback::callback);
//interface IcountNonZero{
// (src: _st.InputArray): _st.int;
//}
//
//export var countNonZero: IcountNonZero = alvision_module.countNonZero;
//CV_EXPORTS_W int countNonZero(src : _st.InputArray );
overload->addOverload("core", "", "findNonZero", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("idx","IOArray")
}, findNonZero);
Nan::SetMethod(target, "findNonZero", core_general_callback::callback);
// interface IfindNonZero {
// (src: _st.InputArray, idx: _st.OutputArray): void;
// }
//
//export var findNonZero: IfindNonZero = alvision_module.findNonZero;
overload->addOverload("core", "", "mean", {
make_param<IOArray*>( "src","IOArray"),
make_param<IOArray*>("mask","IOArray",IOArray:: noArray())
}, mean);
Nan::SetMethod(target, "mean", core_general_callback::callback);
//interface Imean {
// (src: _st.InputArray, mask?: _st.InputArray /* = noArray()*/): _types.Scalar;
//}
//
//export var mean: Imean = alvision_module.mean;
//CV_EXPORTS_W Scalar mean(src : _st.InputArray, mask : _st.InputArray /* = noArray()*/);
overload->addOverload("core", "", "meanStdDev", {
make_param<IOArray*>( "src","IOArray"),
make_param<IOArray*>( "mean","IOArray"),
make_param<IOArray*>("stddev","IOArray"),
make_param<IOArray*>( "mask","IOArray",IOArray:: noArray())
}, meanStdDev);
Nan::SetMethod(target, "meanStdDev", core_general_callback::callback);
//interface ImeanStdDev{
// (src: _st.InputArray, mean: _st.OutputArray, stddev: _st.OutputArray,
// mask?: _st.InputArray /* = noArray()*/): void;
//}
//
//export var meanStdDev: ImeanStdDev = alvision_module.meanStdDev;
overload->addOverload("core", "", "norm", {
make_param<IOArray*>("src1","IOArray"),
make_param<int>("normType","NormTypes",cv::NORM_L2),
make_param<IOArray*>("mask","IOArray",IOArray::noArray())
}, norm);
Nan::SetMethod(target, "norm", core_general_callback::callback);
overload->addOverload("core", "", "norm", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<int>("normType","NormTypes",cv::NORM_L2),
make_param<IOArray*>("mask","IOArray",IOArray::noArray())
}, norm_src2);
overload->addOverload("core", "", "norm", {
make_param<SparseMat*>("src","SparseMat"),
make_param<int>("normType","NormTypes")
}, norm_simple);
//interface Inorm {
// (src1: _st.InputArray, normType?: _base.NormTypes /* = NORM_L2*/, mask?: _st.InputArray /* = noArray()*/): _st.double;
// (src1: _st.InputArray, src2: _st.InputArray, normType?: _base.NormTypes /* = NORM_L2*/, mask?: _st.InputArray /* = noArray()*/): _st.double;
// (src: _mat.SparseMat, normType: _base.NormTypes): _st.double;
//}
//
//export var norm: Inorm = alvision_module.norm;
//CV_EXPORTS_W double norm(src1 : _st.InputArray, normType : _st.int /* = NORM_L2*/, mask : _st.InputArray /* = noArray()*/);
//CV_EXPORTS double norm( const SparseMat& src, int normType );
/** @brief computes PSNR image/video quality metric
see http://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio for details
@todo document
*/
overload->addOverload("core", "", "PSNR", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray")
}, PSNR);
Nan::SetMethod(target, "PSNR", core_general_callback::callback);
//interface IPSNR {
// (src1: _st.InputArray, src2: _st.InputArray): _st.double;
//}
//
//export var PSNR: IPSNR = alvision_module.PSNR;
//CV_EXPORTS_W double PSNR(src1 : _st.InputArray, src2 : _st.InputArray);
overload->addOverload("core", "", "batchDistance", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>("dist","IOArray"),
make_param<int>("dtype","int"),
make_param<IOArray*>("nidx","IOArray"),
make_param<int>("normType","int",cv:: NORM_L2),
make_param<int>("K","int",0),
make_param<IOArray*>("mask","IOArray",IOArray:: noArray()),
make_param<int>("update","int", 0),
make_param<bool>("crosscheck","bool", false)
}, batchDistance);
Nan::SetMethod(target, "batchDistance", core_general_callback::callback);
//interface IbatchDistance{
// (src1: _st.InputArray, src2: _st.InputArray,
// dist : _st.OutputArray, dtype : _st.int, nidx : _st.OutputArray,
// normType: _st.int /* = NORM_L2*/, K : _st.int /* = 0*/,
// mask: _st.InputArray /* = noArray()*/, update : _st.int /* = 0*/,
// crosscheck : boolean /*= false*/): void;
//}
//
//export var batchDistance: IbatchDistance = alvision_module.batchDistance;
//CV_EXPORTS_W void batchDistance(src1 : _st.InputArray, src2 : _st.InputArray,
// dist : _st.OutputArray, dtype : _st.int, nidx : _st.OutputArray,
// normType : _st.int /* = NORM_L2*/, K : _st.int /* = 0*/,
// mask : _st.InputArray /* = noArray()*/, int update = 0,
// bool crosscheck = false);
overload->addOverload("core", "", "normalize", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<double>("alpha","double", 1),
make_param<double>("beta","double", 0),
make_param<int>("norm_type","int",cv:: NORM_L2),
make_param<int>("dtype","int", -1 ),
make_param<IOArray*>("mask","IOArray",IOArray:: noArray())
}, normalize);
Nan::SetMethod(target, "normalize", core_general_callback::callback);
overload->addOverload("core", "", "normalize", {
make_param<SparseMat*>("src","SparseMat"),
make_param<SparseMat*>("dst","SparseMat"),
make_param<double>("alpha","double"),
make_param<int>("normType","int")
}, normalize_sparse);
//interface Inormalize {
// (src: _st.InputArray, dst: _st.InputOutputArray, alpha: _st.double /*= 1*/, beta: _st.double /*= 0*/,
// norm_type: _st.int /*= NORM_L2*/, dtype: _st.int /* = -1 */, mask: _st.InputArray /* = noArray()*/): void;
// (src: _mat.SparseMat, dst: _mat.SparseMat, alpha: _st.double, normType: _st.int): void;
//
// <T>(v: _matx.Vec<T>): _matx.Vec<T>;
//}
//
//export var normalize: Inormalize = alvision_module.normalize;
//CV_EXPORTS_W void normalize(src : _st.InputArray, Inputdst : _st.OutputArray, alpha : _st.double = 1, beta : _st.double = 0,
// int norm_type = NORM_L2, dtype : _st.int /* = -1 */, mask : _st.InputArray /* = noArray()*/);
//export interface IminMaxLoc {
// (src: _st.InputArray, cb: (minVal: _st.double,maxVal: _st.double,minLoc: Array<_types.Point>,maxLoc: Array<_types.Point>)=> void, mask? : _st.InputArray /* = noArray()*/) : void;
//}
//export var minMaxLoc : IminMaxLoc = alvision_module.minMaxLoc;
//CV_EXPORTS_W void minMaxLoc(src : _st.InputArray, CV_OUT double* minVal,
// CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0,
// CV_OUT Point* maxLoc = 0, mask : _st.InputArray /* = noArray()*/);
overload->addOverload("core", "", "minMaxIdx", {
make_param<IOArray*>("src","IOArray"),
make_param<std::shared_ptr<overres::Callback>>("cb","Function"),
make_param<IOArray*>("mask","IOArray",IOArray:: noArray())
}, minMaxIdx);
Nan::SetMethod(target, "minMaxIdx", core_general_callback::callback);
//interface IminMaxIdx {
// (src: _st.InputArray, cb: (minVal: _st.double, maxVal: _st.double /* = 0*/,
// minIdx: Array<_st.int> /* = 0*/, maxIdx: Array<_st.int> /*= 0*/) =>void, mask? : _st.InputArray /* = noArray()*/) : void;
//}
//
//export var minMaxIdx: IminMaxIdx = alvision_module.minMaxIdx;
//CV_EXPORTS void minMaxIdx(src : _st.InputArray, double * minVal, double * maxVal = 0,
// int * minIdx = 0, int * maxIdx = 0, mask : _st.InputArray /* = noArray()*/);
//export interface IminMaxLocCallback {
// (minVal : _st.double,maxVal : _st.double, minIdx : _st.int/* = 0*/, maxIdx : _st.int /* = 0*/): void;
//}
overload->addOverload("core", "", "minMaxLoc", {
make_param<SparseMat*>("a","SparseMat"),
make_param<std::shared_ptr<overres::Callback>>("cb","Function"),
}, minMaxLoc_sparse);
Nan::SetMethod(target, "minMaxLoc", core_general_callback::callback);
overload->addOverload("core", "", "minMaxLoc", {
make_param<IOArray*>("src","IOArray"),
make_param<std::shared_ptr<overres::Callback>>("cb","Function"),
make_param<IOArray*>("mask","IOArray",IOArray::noArray())
}, minMaxLoc);
//export interface IminMaxLoc {
// (a: _mat.SparseMat, cb: (minVal: _st.double, maxVal: _st.double, minIdx: Array<_st.int>/* = 0*/, maxIdx: Array<_st.int> /* = 0*/) => void): void;
//
// (src: _st.InputArray, cb: (minVal: _st.double, maxVal: _st.double, minLoc: Array<_types.Point>, maxLoc: Array<_types.Point>) => void, mask?: _st.InputArray /* = noArray()*/): void;
//}
//
//export var minMaxLoc: IminMaxLoc = alvision_module.minMaxLoc;
//CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal,
// double* maxVal, int* minIdx = 0, int * maxIdx = 0);
overload->addOverload("core", "", "reduce", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("dim","int"),
make_param<int>("rtype","ReduceTypes"),
make_param<int>("dtype","int", -1 )
}, reduce);
Nan::SetMethod(target, "reduce", core_general_callback::callback);
//interface Ireduce {
// (src: _st.InputArray, dst: _st.OutputArray, dim: _st.int, rtype: ReduceTypes | _st.int, dtype?: _st.int /* = -1 */): void;
//}
//
//export var reduce: Ireduce = alvision_module.reduce;
//CV_EXPORTS_W void reduce(src : _st.InputArray, dst : _st.OutputArray, int dim, int rtype, dtype : _st.int /* = -1 */);
//export interface Imerge {
// (mv: _mat.Mat, count: _st.size_t, dst: _st.OutputArray): void;
//}
//export var merge: Imerge = alvision_module.merge;
//CV_EXPORTS void merge(mv : _mat.Mat, count : _st.size_t, dst : _st.OutputArray);
overload->addOverload("core", "", "merge", {
make_param<IOArray*>("mv","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, merge_arr);
Nan::SetMethod(target, "merge", core_general_callback::callback);
overload->addOverload("core", "", "merge", {
make_param<Matrix*>("mv","Mat"),
make_param<int>("count","size_t"),
make_param<IOArray*>("dst","IOArray")
}, merge_size);
//export interface Imerge {
// (mv: _st.InputArrayOfArrays, dst: _st.OutputArray): void;
//
// (mv: _mat.Mat, count: _st.size_t, dst: _st.OutputArray): void;
//}
//
//export var merge: Imerge = alvision_module.merge;
//CV_EXPORTS_W void merge(mv : _st.InputArrayOfArrays, dst : _st.OutputArray);
//export interface Isplit {
// (src: _mat.Mat, mvbegin: _mat.Mat): void;
//}
//export var split: Isplit = alvision_module.split;
//CV_EXPORTS void split(src : _mat.Mat, mvbegin : _mat.Mat);
overload->addOverload("core", "", "split", {
make_param<IOArray*>("m","IOArray"),
make_param<IOArray*>("mv","IOArray")
}, split_array);
Nan::SetMethod(target, "split", core_general_callback::callback);
overload->addOverload("core", "", "split", {
make_param<Matrix*>("src","Mat"),
make_param<std::shared_ptr<std::vector<Matrix*>>>("mvbegin","Array<Mat>")
}, split_mat);
//export interface Isplit{
// (m: _st.InputArray, mv: _st.OutputArrayOfArrays): void;
//
// //Array size must match src.channels
// (src: _mat.Mat, mvbegin: Array<_mat.Mat>): void;
//}
//
//export var split: Isplit = alvision_module.split;
//CV_EXPORTS_W void split(m : _st.InputArray, mv : _st.OutputArrayOfArrays);
//overload->addOverload("core", "", "", {}, );
//export interface MixChannelsFromTo {
// [id: number]: number;
//}
//export interface ImixChannels {
// (src : Array< _mat.Mat> | _mat.Mat, nsrcs : _st.size_t, dst : Array<_mat.Mat> | _mat.Mat, ndsts : _st.size_t,
// fromTo: MixChannelsFromTo, npairs: _st.size_t): void;
// (src: Array<_mat.Mat> | _mat.Mat, dst: Array<_mat.Mat> | _mat.Mat,fromTo: MixChannelsFromTo): void;
//}
//export var mixChannels: ImixChannels = alvision_module.mixChannels;
//CV_EXPORTS void mixChannels(src : _mat.Mat, nsrcs : _st.size_t, dst : _mat.Mat, ndsts : _st.size_t,
//const int* fromTo, size_t npairs);
overload->addOverload("core", "", "mixChannels", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<std::shared_ptr<std::vector<int>>>("fromTo","Array<int>"),
make_param<int>("npairs","size_t")
}, mixChannels_arr_npairs);
Nan::SetMethod(target, "mixChannels", core_general_callback::callback);
overload->addOverload("core", "", "mixChannels", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<std::shared_ptr<std::vector<int>>>("fromTo","Array<int>"),
}, mixChannels_arr);
overload->addOverload("core", "", "mixChannels", {
make_param<std::shared_ptr<std::vector<Matrix*>>>("src","Array<Mat>"),
make_param<int>("nsrcs","size_t"),
make_param<std::shared_ptr<std::vector<Matrix*>>>("dst","Array<Mat>"),
make_param<int>("ndsts","size_t"),
make_param<std::shared_ptr<std::vector<int>>>("fromTo","Array<int>"),
make_param<int>("npairs","size_t")
}, mixChannels_mat_npairs);
overload->addOverload("core", "", "mixChannels", {
make_param<std::shared_ptr<std::vector<Matrix*>>>("src","Array<Mat>"),
make_param<std::shared_ptr<std::vector<Matrix*>>>("dst","Array<Mat>"),
make_param<std::shared_ptr<std::vector<int>>>("fromTo","Array<int>")
}, mixChannels_mat);
// export interface ImixChannels{
//(src: _st.InputArrayOfArrays, dst : _st.InputOutputArrayOfArrays, fromTo : MixChannelsFromTo, npairs : _st.size_t) : void;
//(src : _st.InputArrayOfArrays, dst : _st.InputOutputArrayOfArrays, fromTo : MixChannelsFromTo) : void;
//
//(src : Array<_mat.Mat>, nsrcs : _st.size_t, dst : Array<_mat.Mat>, ndsts : _st.size_t, fromTo : MixChannelsFromTo, npairs : _st.size_t) : void;
//(src : Array<_mat.Mat>, dst : Array<_mat.Mat>, fromTo : MixChannelsFromTo) : void;
//}
//
//export var mixChannels: ImixChannels = alvision_module.mixChannels;
//CV_EXPORTS void mixChannels(src : _st.InputArrayOfArrays, InputOutputArrayOfArrays dst,
// const int* fromTo, size_t npairs);
overload->addOverload("core", "", "extractChannel", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("coi","int")
}, extractChannel);
Nan::SetMethod(target, "extractChannel", core_general_callback::callback);
//interface IextractChannel {
// (src: _st.InputArray, dst: _st.OutputArray, coi: _st.int): void;
//}
//
//export var extractChannel: IextractChannel = alvision_module.extractChannel;
//CV_EXPORTS_W void extractChannel(src : _st.InputArray, dst : _st.OutputArray, coi : _st.int);
overload->addOverload("core", "", "insertChannel", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("coi","int")
}, insertChannel);
Nan::SetMethod(target, "insertChannel", core_general_callback::callback);
//interface IinsertChannel {
// (src: _st.InputArray, dst: _st.InputOutputArray, coi : _st.int): void;
//}
//
//export var insertChannel: IinsertChannel = alvision_module.insertChannel;
//CV_EXPORTS_W void insertChannel(src : _st.InputArray, Inputdst : _st.OutputArray, coi : _st.int);
overload->addOverload("core", "", "flip", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("flipCode","int")
}, flip);
Nan::SetMethod(target, "flip", core_general_callback::callback);
//interface Iflip {
// (src : _st.InputArray, dst : _st.OutputArray, flipCode : _st.int) : void;
//}
//
//export var flip: Iflip = alvision_module.flip;
//CV_EXPORTS_W void flip(src : _st.InputArray, dst : _st.OutputArray, flipCode : _st.int);
overload->addOverload("core", "", "repeat", {
make_param<IOArray*>("src","IOArray"),
make_param<int>("ny","int"),
make_param<int>("nx","int"),
make_param<IOArray*>("dst","IOArray")
}, repeat);
Nan::SetMethod(target, "repeat", core_general_callback::callback);
overload->addOverload("core", "", "repeat", {
make_param<Matrix*>("src","Mat"),
make_param<int>("ny","int"),
make_param<int>("nx","int")
}, repeat_mat);
//interface Irepeat {
// (src: _st.InputArray, ny : _st.int, nx : _st.int, dst: _st.OutputArray): void;
// (src : _mat.Mat , ny : _st.int, nx : _st.int): _mat.Mat;
//}
//
//export var repeat: Irepeat = alvision_module.repeat;
//CV_EXPORTS_W void repeat(src : _st.InputArray, ny : _st.int, nx : _st.int, dst : _st.OutputArray);
overload->addOverload("core", "", "hconcat", {
make_param<std::shared_ptr<std::vector<Matrix*>>>("src","Array<Mat>"),
make_param<int>("nsrc","size_t"),
make_param<IOArray*>("dst","IOArray")
}, hconcat_mat);
Nan::SetMethod(target, "hconcat", core_general_callback::callback);
overload->addOverload("core", "", "hconcat", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>( "dst","IOArray")
}, hconcat_inputarray);
overload->addOverload("core", "", "hconcat", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, hconcat_arrayorarrays);
//interface Ihconcat {
// (src : Array<_mat.Mat>, nsrc : _st.size_t, dst: _st.OutputArray): void;
// (src1: _st.InputArray, src2: _st.InputArray, dst: _st.OutputArray): void;
// (src : _st.InputArrayOfArrays, dst: _st.OutputArray): void;
//}
//
//export var hconcat: Ihconcat = alvision_module.hconcat;
overload->addOverload("core", "", "vconcat", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, vconcat_array);
Nan::SetMethod(target, "vconcat", core_general_callback::callback);
overload->addOverload("core", "", "vconcat", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>( "dst","IOArray")
}, vconcat_2src);
overload->addOverload("core", "", "vconcat", {
make_param<std::shared_ptr<std::vector<IOArray*>>>("src", "Array<Mat>"),
make_param<int>("nsrc","size_t"),
make_param<IOArray*>("dst","IOArray")
}, vconcat_matrix_array);
//export interface Ivconcat {
// (src: _st.InputArrayOfArrays, dst: _st.OutputArray): void;
//
// (src1: _st.InputArray, src2: _st.InputArray, dst: _st.OutputArray): void;
//
// (src: Array<_mat.Mat>, nsrc: _st.size_t, dst: _st.OutputArray): void;
//}
//
//export var vconcat: Ivconcat = alvision_module.vconcat;
//CV_EXPORTS_W void vconcat(src : _st.InputArrayOfArrays, dst : _st.OutputArray);
/** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2)
Calculates the per-element bit-wise conjunction of two arrays or an
array and a scalar.
The function calculates the per-element bit-wise logical conjunction for:
* Two arrays when src1 and src2 have the same size:
\f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
* An array and a scalar when src2 is constructed from Scalar or has
the same number of elements as `src1.channels()`:
\f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
* A scalar and an array when src1 is constructed from Scalar or has
the same number of elements as `src2.channels()`:
\f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
In case of floating-point arrays, their machine-specific bit
representations (usually IEEE754-compliant) are used for the operation.
In case of multi-channel arrays, each channel is processed
independently. In the second and third cases above, the scalar is first
converted to the array type.
@param src1 first input array or a scalar.
@param src2 second input array or a scalar.
@param dst output array that has the same size and type as the input
arrays.
@param mask optional operation mask, 8-bit single channel array, that
specifies elements of the output array to be changed.
*/
overload->addOverload("core", "", "bitwise_and", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>( "dst","IOArray"),
make_param<IOArray*>("mask","IOArray",IOArray:: noArray())
}, bitwise_and);
Nan::SetMethod(target, "bitwise_and", core_general_callback::callback);
//export interface Ibitwise_and{
// (src1: _st.InputArray, src2: _st.InputArray, dst: _st.OutputArray, mask?: _st.InputArray /* = noArray()*/): void;
//}
//
//export var bitwise_and: Ibitwise_and = alvision_module.bitwise_and;
//CV_EXPORTS_W void bitwise_and(src1 : _st.InputArray, src2 : _st.InputArray,
// dst : _st.OutputArray, mask : _st.InputArray /* = noArray()*/);
/** @brief Calculates the per-element bit-wise disjunction of two arrays or an
array and a scalar.
The function calculates the per-element bit-wise logical disjunction for:
* Two arrays when src1 and src2 have the same size:
\f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
* An array and a scalar when src2 is constructed from Scalar or has
the same number of elements as `src1.channels()`:
\f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
* A scalar and an array when src1 is constructed from Scalar or has
the same number of elements as `src2.channels()`:
\f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
In case of floating-point arrays, their machine-specific bit
representations (usually IEEE754-compliant) are used for the operation.
In case of multi-channel arrays, each channel is processed
independently. In the second and third cases above, the scalar is first
converted to the array type.
@param src1 first input array or a scalar.
@param src2 second input array or a scalar.
@param dst output array that has the same size and type as the input
arrays.
@param mask optional operation mask, 8-bit single channel array, that
specifies elements of the output array to be changed.
*/
overload->addOverload("core", "", "bitwise_or", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<IOArray*>("mask","IOArray",IOArray::noArray())
}, bitwise_or);
Nan::SetMethod(target, "bitwise_or", core_general_callback::callback);
//export interface Ibitwise_or {
// (src1: _st.InputArray, src2: _st.InputArray,dst: _st.OutputArray, mask?: _st.InputArray /* = noArray()*/): void;
//}
//
//export var bitwise_or: Ibitwise_or = alvision_module.bitwise_or;
//CV_EXPORTS_W void bitwise_or(src1 : _st.InputArray, src2 : _st.InputArray,
// dst : _st.OutputArray, mask : _st.InputArray /* = noArray()*/);
/** @brief Calculates the per-element bit-wise "exclusive or" operation on two
arrays or an array and a scalar.
The function calculates the per-element bit-wise logical "exclusive-or"
operation for:
* Two arrays when src1 and src2 have the same size:
\f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
* An array and a scalar when src2 is constructed from Scalar or has
the same number of elements as `src1.channels()`:
\f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
* A scalar and an array when src1 is constructed from Scalar or has
the same number of elements as `src2.channels()`:
\f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
In case of floating-point arrays, their machine-specific bit
representations (usually IEEE754-compliant) are used for the operation.
In case of multi-channel arrays, each channel is processed
independently. In the 2nd and 3rd cases above, the scalar is first
converted to the array type.
@param src1 first input array or a scalar.
@param src2 second input array or a scalar.
@param dst output array that has the same size and type as the input
arrays.
@param mask optional operation mask, 8-bit single channel array, that
specifies elements of the output array to be changed.
*/
overload->addOverload("core", "", "bitwise_xor", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<IOArray*>("mask","IOArray",IOArray::noArray())
}, bitwise_xor);
Nan::SetMethod(target, "bitwise_xor", core_general_callback::callback);
//export interface Ibitwise_xor {
// (src1: _st.InputArray, src2: _st.InputArray,
// dst: _st.OutputArray, mask?: _st.InputArray /* = noArray()*/): void;
//}
//
//export var bitwise_xor: Ibitwise_xor = alvision_module.bitwise_xor;
//CV_EXPORTS_W void bitwise_xor(src1 : _st.InputArray, src2 : _st.InputArray,
// dst : _st.OutputArray, mask : _st.InputArray /* = noArray()*/);
/** @brief Inverts every bit of an array.
The function calculates per-element bit-wise inversion of the input
array:
\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f]
In case of a floating-point input array, its machine-specific bit
representation (usually IEEE754-compliant) is used for the operation. In
case of multi-channel arrays, each channel is processed independently.
@param src input array.
@param dst output array that has the same size and type as the input
array.
@param mask optional operation mask, 8-bit single channel array, that
specifies elements of the output array to be changed.
*/
overload->addOverload("core", "", "bitwise_not", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<IOArray*>("mask","IOArray",IOArray::noArray())
}, bitwise_not);
Nan::SetMethod(target, "bitwise_not", core_general_callback::callback);
//export interface Ibitwise_not {
// (src: _st.InputArray, dst: _st.OutputArray,
// mask?: _st.InputArray /* = noArray()*/): void;
//}
//
//export var bitwise_not: Ibitwise_not = alvision_module.bitwise_not;
//CV_EXPORTS_W void bitwise_not(src : _st.InputArray, dst : _st.OutputArray,
// mask : _st.InputArray /* = noArray()*/);
/** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar.
The function absdiff calculates:
* Absolute difference between two arrays when they have the same
size and type:
\f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f]
* Absolute difference between an array and a scalar when the second
array is constructed from Scalar or has as many elements as the
number of channels in `src1`:
\f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f]
* Absolute difference between a scalar and an array when the first
array is constructed from Scalar or has as many elements as the
number of channels in `src2`:
\f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f]
where I is a multi-dimensional index of array elements. In case of
multi-channel arrays, each channel is processed independently.
@note Saturation is not applied when the arrays have the depth CV_32S.
You may even get a negative value in the case of overflow.
@param src1 first input array or a scalar.
@param src2 second input array or a scalar.
@param dst output array that has the same size and type as input arrays.
@sa cv::abs(const Mat&)
*/
overload->addOverload("core", "", "absdiff", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, absdiff);
Nan::SetMethod(target, "absdiff", core_general_callback::callback);
//export interface Iabsdiff {
// (src1: _st.InputArray, src2: _st.InputArray, dst: _st.OutputArray): void;
//}
//
//export var absdiff: Iabsdiff = alvision_module.absdiff;
//CV_EXPORTS_W void absdiff(src1 : _st.InputArray, src2 : _st.InputArray, dst : _st.OutputArray);
/** @brief Checks if array elements lie between the elements of two other arrays.
The function checks the range as follows:
- For every element of a single-channel input array:
\f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f]
- For two-channel arrays:
\f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0 \land \texttt{lowerb} (I)_1 \leq \texttt{src} (I)_1 \leq \texttt{upperb} (I)_1\f]
- and so forth.
That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the
specified 1D, 2D, 3D, ... box and 0 otherwise.
When the lower and/or upper boundary parameters are scalars, the indexes
(I) at lowerb and upperb in the above formulas should be omitted.
@param src first input array.
@param lowerb inclusive lower boundary array or a scalar.
@param upperb inclusive upper boundary array or a scalar.
@param dst output array of the same size as src and CV_8U type.
*/
overload->addOverload("core", "", "inRange", {
make_param<IOArray*>( "src","IOArray"),
make_param<IOArray*>("lowerb","IOArray"),
make_param<IOArray*>("upperb","IOArray"),
make_param<IOArray*>( "dst","IOArray")
}, inRange);
Nan::SetMethod(target, "inRange", core_general_callback::callback);
// interface IinRange {
// (src: _st.InputArray, lowerb : _st.InputArray,
// upperb : _st.InputArray, dst: _st.OutputArray): void;
// }
//export var inRange: IinRange = alvision_module.inRange;
//CV_EXPORTS_W void inRange(src : _st.InputArray, lowerb : _st.InputArray,
// upperb : _st.InputArray, dst : _st.OutputArray);
/** @brief Performs the per-element comparison of two arrays or an array and scalar value.
The function compares:
* Elements of two arrays when src1 and src2 have the same size:
\f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f]
* Elements of src1 with a scalar src2 when src2 is constructed from
Scalar or has a single element:
\f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f]
* src1 with elements of src2 when src1 is constructed from Scalar or
has a single element:
\f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f]
When the comparison result is true, the corresponding element of output
array is set to 255. The comparison operations can be replaced with the
equivalent matrix expressions:
@code{.cpp}
Mat dst1 = src1 >= src2;
Mat dst2 = src1 < 8;
...
@endcode
@param src1 first input array or a scalar; when it is an array, it must have a single channel.
@param src2 second input array or a scalar; when it is an array, it must have a single channel.
@param dst output array of type ref CV_8U that has the same size and the same number of channels as
the input arrays.
@param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes)
@sa checkRange, min, max, threshold
*/
overload->addOverload("core", "", "compare", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>( "dst","IOArray"),
make_param<int>("cmpop","CmpTypes")
}, compare);
Nan::SetMethod(target, "compare", core_general_callback::callback);
overload->addOverload("core", "", "compare", {
make_param<IOArray*>("src1","IOArray"),
make_param<double>("src2","Number"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("cmpop","CmpTypes")
}, compare_number);
//interface Icompare {
// (src1: _st.InputArray, src2: _st.InputArray | Number, dst: _st.OutputArray, cmpop: _base.CmpTypes | _st.int): void;
//}
//
//export var compare: Icompare = alvision_module.compare;
//CV_EXPORTS_W void compare(src1 : _st.InputArray, src2 : _st.InputArray, dst : _st.OutputArray, int cmpop);
/** @brief Calculates per-element minimum of two arrays or an array and a scalar.
The functions min calculate the per-element minimum of two arrays:
\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f]
or array and a scalar:
\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f]
@param src1 first input array.
@param src2 second input array of the same size and type as src1.
@param dst output array of the same size and type as src1.
@sa max, compare, inRange, minMaxLoc
*/
overload->addOverload("core", "", "min", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>( "dst","IOArray")
}, min_array);
Nan::SetMethod(target, "min", core_general_callback::callback);
overload->addOverload("core", "", "min", {
make_param<Matrix*>("src1","Mat"),
make_param<Matrix*>("src2","Mat"),
make_param<Matrix*>( "dst","Mat")
}, min_mat);
overload->addOverload("core", "", "min", {
make_param<UMatrix*>("src1","UMat"),
make_param<UMatrix*>("src2","UMat"),
make_param<UMatrix*>( "dst","UMat")
}, min_umat);
//interface Imin {
// (src1: _st.InputArray, src2: _st.InputArray, dst: _st.OutputArray): void;
// (src1 : _mat.Mat, src2 : _mat.Mat, dst :_mat.Mat): void;
// (src1 : _mat.UMat, src2 : _mat.UMat, dst :_mat.UMat): void;
//}
//
//export var min: Imin = alvision_module.min;
//CV_EXPORTS_W void min(src1 : _st.InputArray, src2 : _st.InputArray, dst : _st.OutputArray);
/** @overload
needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
*/
//CV_EXPORTS void min(src : _mat.Mat1, src : _mat.Mat2, dst :_mat.Mat);
/** @overload
needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
*/
//CV_EXPORTS void min(src1 : _mat.UMat, src2 : _mat.UMat, Udst :_mat.Mat);
/** @brief Calculates per-element maximum of two arrays or an array and a scalar.
The functions max calculate the per-element maximum of two arrays:
\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f]
or array and a scalar:
\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f]
@param src1 first input array.
@param src2 second input array of the same size and type as src1 .
@param dst output array of the same size and type as src1.
@sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions
*/
overload->addOverload("core", "", "max", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, max_array);
Nan::SetMethod(target, "max", core_general_callback::callback);
overload->addOverload("core", "", "max", {
make_param<Matrix*>("src1","Mat"),
make_param<Matrix*>("src2","Mat"),
make_param<Matrix*>("dst","Mat")
}, max_mat);
overload->addOverload("core", "", "max", {
make_param<UMatrix*>("src1","UMat"),
make_param<UMatrix*>("src2","UMat"),
make_param<UMatrix*>("dst","UMat")
}, max_umat);
//interface Imax {
// (src1: _st.InputArray, src2: _st.InputArray, dst: _st.OutputArray): void;
// (src1 : _mat.Mat, src2 : _mat.Mat, dst :_mat.Mat): void;
// (src1 : _mat.UMat, src2 : _mat.UMat, Udst :_mat.Mat): void;
//}
//
//export var max: Imax = alvision_module.max;
//CV_EXPORTS_W void max(src1 : _st.InputArray, src2 : _st.InputArray, dst : _st.OutputArray);
/** @overload
needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
*/
//CV_EXPORTS void max(src : _mat.Mat1, src : _mat.Mat2, dst :_mat.Mat);
/** @overload
needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
*/
//CV_EXPORTS void max(src1 : _mat.UMat, src2 : _mat.UMat, Udst :_mat.Mat);
/** @brief Calculates a square root of array elements.
The functions sqrt calculate a square root of each input array element.
In case of multi-channel arrays, each channel is processed
independently. The accuracy is approximately the same as of the built-in
std::sqrt .
@param src input floating-point array.
@param dst output array of the same size and type as src.
*/
overload->addOverload("core", "", "sqrt", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, sqrt);
Nan::SetMethod(target, "sqrt", core_general_callback::callback);
//interface Isqrt {
// (src: _st.InputArray, dst: _st.OutputArray): void;
//}
//
//export var sqrt: Isqrt = alvision_module.sqrt;
//CV_EXPORTS_W void sqrt(src : _st.InputArray, dst : _st.OutputArray);
/** @brief Raises every array element to a power.
The function pow raises every element of the input array to power :
\f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f]
So, for a non-integer power exponent, the absolute values of input array
elements are used. However, it is possible to get true values for
negative values using some extra operations. In the example below,
computing the 5th root of array src shows:
@code{.cpp}
Mat mask = src < 0;
pow(src, 1./5, dst);
subtract(Scalar::all(0), dst, dst, mask);
@endcode
For some values of power, such as integer values, 0.5 and -0.5,
specialized faster algorithms are used.
Special values (NaN, Inf) are not handled.
@param src input array.
@param power exponent of power.
@param dst output array of the same size and type as src.
@sa sqrt, exp, log, cartToPolar, polarToCart
*/
overload->addOverload("core", "", "pow", {
make_param<IOArray*>("src","IOArray"),
make_param<double>("power","double"),
make_param<IOArray*>("dst","IOArray")
}, pow);
Nan::SetMethod(target, "pow", core_general_callback::callback);
//interface Ipow {
// (src: _st.InputArray, power : _st.double, dst: _st.OutputArray): void;
//}
//
//export var pow: Ipow = alvision_module.pow;
//CV_EXPORTS_W void pow(src : _st.InputArray, power : _st.double, dst : _st.OutputArray);
/** @brief Calculates the exponent of every array element.
The function exp calculates the exponent of every element of the input
array:
\f[\texttt{dst} [I] = e^{ src(I) }\f]
The maximum relative error is about 7e-6 for single-precision input and
less than 1e-10 for double-precision input. Currently, the function
converts denormalized values to zeros on output. Special values (NaN,
Inf) are not handled.
@param src input array.
@param dst output array of the same size and type as src.
@sa log , cartToPolar , polarToCart , phase , pow , sqrt , magnitude
*/
overload->addOverload("core", "", "exp", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, exp);
Nan::SetMethod(target, "exp", core_general_callback::callback);
//interface Iexp {
// (src: _st.InputArray, dst: _st.OutputArray): void;
//}
//export var exp: Iexp = alvision_module.exp;
//CV_EXPORTS_W void exp(src : _st.InputArray, dst : _st.OutputArray);
/** @brief Calculates the natural logarithm of every array element.
The function log calculates the natural logarithm of the absolute value
of every element of the input array:
\f[\texttt{dst} (I) = \fork{\log |\texttt{src}(I)|}{if \(\texttt{src}(I) \ne 0\) }{\texttt{C}}{otherwise}\f]
where C is a large negative number (about -700 in the current
implementation). The maximum relative error is about 7e-6 for
single-precision input and less than 1e-10 for double-precision input.
Special values (NaN, Inf) are not handled.
@param src input array.
@param dst output array of the same size and type as src .
@sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude
*/
overload->addOverload("core", "", "log", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, log);
Nan::SetMethod(target, "log", core_general_callback::callback);
//export interface Ilog {
// (src: _st.InputArray, dst: _st.OutputArray): void;
//}
//
//export var log: Ilog = alvision_module.log;
//CV_EXPORTS_W void log(src : _st.InputArray, dst : _st.OutputArray);
/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle.
The function polarToCart calculates the Cartesian coordinates of each 2D
vector represented by the corresponding elements of magnitude and angle:
\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f]
The relative accuracy of the estimated coordinates is about 1e-6.
@param magnitude input floating-point array of magnitudes of 2D vectors;
it can be an empty matrix (=Mat()), in this case, the function assumes
that all the magnitudes are =1; if it is not empty, it must have the
same size and type as angle.
@param angle input floating-point array of angles of 2D vectors.
@param x output array of x-coordinates of 2D vectors; it has the same
size and type as angle.
@param y output array of y-coordinates of 2D vectors; it has the same
size and type as angle.
@param angleInDegrees when true, the input angles are measured in
degrees, otherwise, they are measured in radians.
@sa cartToPolar, magnitude, phase, exp, log, pow, sqrt
*/
overload->addOverload("core", "", "polarToCart", {
make_param<IOArray*>("magnitude","IOArray"),
make_param<IOArray*>("angle","IOArray"),
make_param<IOArray*>("x","IOArray"),
make_param<IOArray*>("y","IOArray"),
make_param<bool>("angleInDegrees","bool", false)
}, polarToCart);
Nan::SetMethod(target, "polarToCart", core_general_callback::callback);
// interface IpolarToCart {
// (magnitude: _st.InputArray, angle: _st.InputArray ,
// x : _st.OutputArray ,y : _st.OutputArray, angleInDegrees: boolean /*= false*/): void;
// }
// export var polarToCart: IpolarToCart = alvision_module.polarToCart;
//CV_EXPORTS_W void polarToCart(m : _st.InputArrayagnitude, a : _st.InputArrayngle,
// OutputArray x, OutputArray y, bool angleInDegrees = false);
/** @brief Calculates the magnitude and angle of 2D vectors.
The function cartToPolar calculates either the magnitude, angle, or both
for every 2D vector (x(I),y(I)):
\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f]
The angles are calculated with accuracy about 0.3 degrees. For the point
(0,0), the angle is set to 0.
@param x array of x-coordinates; this must be a single-precision or
double-precision floating-point array.
@param y array of y-coordinates, that must have the same size and same type as x.
@param magnitude output array of magnitudes of the same size and type as x.
@param angle output array of angles that has the same size and type as
x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees).
@param angleInDegrees a flag, indicating whether the angles are measured
in radians (which is by default), or in degrees.
@sa Sobel, Scharr
*/
overload->addOverload("core", "", "cartToPolar", {
make_param<IOArray*>("x","IOArray"),
make_param<IOArray*>("y","IOArray"),
make_param<IOArray*>("magnitude","IOArray"),
make_param<IOArray*>("angle","IOArray"),
make_param<bool>("angleInDegrees","bool", false)
}, cartToPolar);
Nan::SetMethod(target, "cartToPolar", core_general_callback::callback);
// interface IcartToPolar{
// (x: _st.InputArray, y: _st.InputArray,
// magnitude: _st.OutputArray, angle: _st.OutputArray,
// angleInDegrees: boolean /*= false*/): void;
//}
//
// export var cartToPolar: IcartToPolar = alvision_module.cartToPolar;
//CV_EXPORTS_W void cartToPolar(x : _st.InputArray, y: _st.InputArray,
// magnitude : _st.OutputArray, angle : _st.OutputArray,
// angleInDegrees : boolean = false);
/** @brief Calculates the rotation angle of 2D vectors.
The function phase calculates the rotation angle of each 2D vector that
is formed from the corresponding elements of x and y :
\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f]
The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 ,
the corresponding angle(I) is set to 0.
@param x input floating-point array of x-coordinates of 2D vectors.
@param y input array of y-coordinates of 2D vectors; it must have the
same size and the same type as x.
@param angle output array of vector angles; it has the same size and
same type as x .
@param angleInDegrees when true, the function calculates the angle in
degrees, otherwise, they are measured in radians.
*/
overload->addOverload("core", "", "phase", {
make_param<IOArray*>("x","IOArray"),
make_param<IOArray*>("y","IOArray"),
make_param<IOArray*>("angle","IOArray"),
make_param<bool>("angleInDegrees","bool", false)
}, phase);
Nan::SetMethod(target, "phase", core_general_callback::callback);
// interface Iphase {
// (x: _st.InputArray, y: _st.InputArray, angle: _st.OutputArray,
// angleInDegrees : boolean /* = false*/): void;
// }
//
// export var phase: Iphase = alvision_module.phase;
//CV_EXPORTS_W void phase(x : _st.InputArray, y: _st.InputArray, angle : _st.OutputArray,
// bool angleInDegrees = false);
/** @brief Calculates the magnitude of 2D vectors.
The function magnitude calculates the magnitude of 2D vectors formed
from the corresponding elements of x and y arrays:
\f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f]
@param x floating-point array of x-coordinates of the vectors.
@param y floating-point array of y-coordinates of the vectors; it must
have the same size as x.
@param magnitude output array of the same size and type as x.
@sa cartToPolar, polarToCart, phase, sqrt
*/
overload->addOverload("core", "", "magnitude", {
make_param<IOArray*>("x","IOArray"),
make_param<IOArray*>("y","IOArray"),
make_param<IOArray*>("magnitude","IOArray")
}, magnitude);
Nan::SetMethod(target, "magnitude", core_general_callback::callback);
// interface Imagnitude {
// (x: _st.InputArray, y: _st.InputArray, magnitude: _st.OutputArray): void;
// }
//
// export var magnitude: Imagnitude = alvision_module.magnitude;
//CV_EXPORTS_W void magnitude(x : _st.InputArray, y: _st.InputArray, magnitude : _st.OutputArray);
/** @brief Checks every element of an input array for invalid values.
The functions checkRange check that every array element is neither NaN nor infinite. When minVal \>
-DBL_MAX and maxVal \< DBL_MAX, the functions also check that each value is between minVal and
maxVal. In case of multi-channel arrays, each channel is processed independently. If some values
are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the
functions either return false (when quiet=true) or throw an exception.
@param a input array.
@param quiet a flag, indicating whether the functions quietly return false when the array elements
are out of range or they throw an exception.
@param pos optional output parameter, when not NULL, must be a pointer to array of src.dims
elements.
@param minVal inclusive lower boundary of valid values range.
@param maxVal exclusive upper boundary of valid values range.
*/
overload->addOverload("core", "", "checkRange", {
make_param<IOArray*>("a","IOArray"),
make_param<bool>("quiet","bool", true),
make_param<std::shared_ptr<overres::Callback>>("cb","Function"),
make_param<double>("minVal","double",-DBL_MAX),
make_param<double>("maxVal","double", DBL_MAX)
}, checkRange);
Nan::SetMethod(target, "checkRange", core_general_callback::callback);
// interface IcheckRangeCallback {
// (pos: _types.Point): void;
// }
//
// interface IcheckRange {
// (a: _st.InputArray, quiet?: boolean/* = true*/, cb?: IcheckRangeCallback,
// minVal?: _st.double /*= -DBL_MAX*/, maxVal?: _st.double /* = DBL_MAX*/) : boolean;
// }
//
//export var checkRange: IcheckRange = alvision_module.checkRange;
//CV_EXPORTS_W bool checkRange(a : _st.InputArray, bool quiet = true, CV_OUT Point* pos = 0,
// double minVal = -DBL_MAX, double maxVal = DBL_MAX);
/** @brief converts NaN's to the given number
*/
overload->addOverload("core", "", "patchNaNs", {
make_param<IOArray*>("a","IOArray"),
make_param<double>("val","double", 0)
}, patchNaNs);
Nan::SetMethod(target, "patchNaNs", core_general_callback::callback);
//interface IpatchNaNs {
// (a: _st.InputOutputArray, val?: _st.double /* = 0*/): void;
//}
//
//export var patchNaNs: IpatchNaNs = alvision_module.patchNaNs;
// CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0);
/** @brief Performs generalized matrix multiplication.
The function performs generalized matrix multiplication similar to the
gemm functions in BLAS level 3. For example,
`gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)`
corresponds to
\f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f]
In case of complex (two-channel) data, performed a complex matrix
multiplication.
The function can be replaced with a matrix expression. For example, the
above call can be replaced with:
@code{.cpp}
dst = alpha*src1.t()*src2 + beta*src3.t();
@endcode
@param src1 first multiplied input matrix that could be real(CV_32FC1,
CV_64FC1) or complex(CV_32FC2, CV_64FC2).
@param src2 second multiplied input matrix of the same type as src1.
@param alpha weight of the matrix product.
@param src3 third optional delta matrix added to the matrix product; it
should have the same type as src1 and src2.
@param beta weight of src3.
@param dst output matrix; it has the proper size and the same type as
input matrices.
@param flags operation flags (cv::GemmFlags)
@sa mulTransposed , transform
*/
overload->addOverload("core", "", "gemm", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<double>("alpha","double"),
make_param<IOArray*>("src3","IOArray"),
make_param<double>("beta","double"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("flags","GemmFlags", 0)
}, gemm);
Nan::SetMethod(target, "gemm", core_general_callback::callback);
//interface Igemm {
// (src1: _st.InputArray, src2: _st.InputArray, alpha: _st.double,
// src3: _st.InputArray, beta: _st.double, dst: _st.OutputArray, flags?: _base.GemmFlags | _st.int /* = 0*/): void;
//}
//
//export var gemm: Igemm = alvision_module.gemm;
//CV_EXPORTS_W void gemm(src1 : _st.InputArray, src2 : _st.InputArray, alpha : _st.double,
// src : _st.InputArray3, beta : _st.double, dst : _st.OutputArray, flags : _st.int /* = 0*/);
overload->addOverload("core", "", "mulTransposed", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<bool>("aTa","bool"),
make_param<IOArray*>("delta","IOArray",IOArray::noArray()),
make_param<double>("scale","double", 1 ),
make_param<int>("dtype","int", -1 )
}, mulTransposed);
Nan::SetMethod(target, "mulTransposed", core_general_callback::callback);
//interface ImulTransposed{
// (src: _st.InputArray, dst: _st.OutputArray, aTa : boolean,
// delta?: _st.InputArray /*= noArray()*/,
// scale?: _st.double /* = 1 */, dtype?: _st.int /* = -1 */): void;
//}
//
//export var mulTransposed: ImulTransposed = alvision_module.mulTransposed;
//CV_EXPORTS_W void mulTransposed(src : _st.InputArray, dst : _st.OutputArray, bool aTa,
// InputArray delta = noArray(),
// scale : _st.double /* = 1 */, dtype : _st.int /* = -1 */);
/** @brief Transposes a matrix.
The function transpose transposes the matrix src :
\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f]
@note No complex conjugation is done in case of a complex matrix. It it
should be done separately if needed.
@param src input array.
@param dst output array of the same type as src.
*/
overload->addOverload("core", "", "transpose", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, transpose);
Nan::SetMethod(target, "transpose", core_general_callback::callback);
//interface Itranspose {
// (src: _st.InputArray, dst: _st.OutputArray): void;
//}
//
//export var transpose: Itranspose = alvision_module.transpose;
//CV_EXPORTS_W void transpose(src : _st.InputArray, dst : _st.OutputArray);
/** @brief Performs the matrix transformation of every array element.
The function transform performs the matrix transformation of every
element of the array src and stores the results in dst :
\f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f]
(when m.cols=src.channels() ), or
\f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f]
(when m.cols=src.channels()+1 )
Every element of the N -channel array src is interpreted as N -element
vector that is transformed using the M x N or M x (N+1) matrix m to
M-element vector - the corresponding element of the output array dst .
The function may be used for geometrical transformation of
N -dimensional points, arbitrary linear color space transformation (such
as various kinds of RGB to YUV transforms), shuffling the image
channels, and so forth.
@param src input array that must have as many channels (1 to 4) as
m.cols or m.cols-1.
@param dst output array of the same size and depth as src; it has as
many channels as m.rows.
@param m transformation 2x2 or 2x3 floating-point matrix.
@sa perspectiveTransform, getAffineTransform, estimateRigidTransform, warpAffine, warpPerspective
*/
overload->addOverload("core", "", "transform", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<IOArray*>( "m","IOArray")
}, transform);
Nan::SetMethod(target, "transform", core_general_callback::callback);
//interface Itransform {
// (src: _st.InputArray, dst: _st.OutputArray, m : _st.InputArray ): void;
//}
//
//export var transform: Itransform = alvision_module.transform;
//CV_EXPORTS_W void transform(src : _st.InputArray, dst : _st.OutputArray, m : _st.InputArray );
/** @brief Performs the perspective matrix transformation of vectors.
The function perspectiveTransform transforms every element of src by
treating it as a 2D or 3D vector, in the following way:
\f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f]
where
\f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f]
and
\f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f]
Here a 3D vector transformation is shown. In case of a 2D vector
transformation, the z component is omitted.
@note The function transforms a sparse set of 2D or 3D vectors. If you
want to transform an image using perspective transformation, use
warpPerspective . If you have an inverse problem, that is, you want to
compute the most probable perspective transformation out of several
pairs of corresponding points, you can use getPerspectiveTransform or
findHomography .
@param src input two-channel or three-channel floating-point array; each
element is a 2D/3D vector to be transformed.
@param dst output array of the same size and type as src.
@param m 3x3 or 4x4 floating-point transformation matrix.
@sa transform, warpPerspective, getPerspectiveTransform, findHomography
*/
overload->addOverload("core", "", "perspectiveTransform", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<IOArray*>( "m","IOArray")
}, perspectiveTransform);
Nan::SetMethod(target, "perspectiveTransform", core_general_callback::callback);
//interface IperspectiveTransform{
// (src: _st.InputArray, dst: _st.OutputArray, m: _st.InputArray): void;
//}
//
//export var perspectiveTransform: IperspectiveTransform = alvision_module.perspectiveTransform;
//CV_EXPORTS_W void perspectiveTransform(src : _st.InputArray, dst : _st.OutputArray, m : _st.InputArray );
/** @brief Copies the lower or the upper half of a square matrix to another half.
The function completeSymm copies the lower half of a square matrix to
its another half. The matrix diagonal remains unchanged:
* \f$\texttt{mtx}_{ij}=\texttt{mtx}_{ji}\f$ for \f$i > j\f$ if
lowerToUpper=false
* \f$\texttt{mtx}_{ij}=\texttt{mtx}_{ji}\f$ for \f$i < j\f$ if
lowerToUpper=true
@param mtx input-output floating-point square matrix.
@param lowerToUpper operation flag; if true, the lower half is copied to
the upper half. Otherwise, the upper half is copied to the lower half.
@sa flip, transpose
*/
overload->addOverload("core", "", "completeSymm", {
make_param<IOArray*>("mtx","IOArray"),
make_param<bool>("lowerToUpper","bool", false)
}, completeSymm);
Nan::SetMethod(target, "completeSymm", core_general_callback::callback);
//interface IcompleteSymm {
// (mtx : _st.InputOutputArray, lowerToUpper : boolean /* = false*/);
//}
//
//export var completeSymm: IcompleteSymm = alvision_module.completeSymm;
// CV_EXPORTS_W void completeSymm(mtx : _st.InputOutputArray, lowerToUpper : boolean /* = false*/);
/** @brief Initializes a scaled identity matrix.
The function setIdentity initializes a scaled identity matrix:
\f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f]
The function can also be emulated using the matrix initializers and the
matrix expressions:
@code
Mat A = Mat::eye(4, 3, CV_32F)*5;
// A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]]
@endcode
@param mtx matrix to initialize (not necessarily square).
@param s value to assign to diagonal elements.
@sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator=
*/
overload->addOverload("core", "", "setIdentity", {
make_param<IOArray*>("mtx","IOArray"),
make_param<Scalar*>("s","Scalar",Scalar::all(1))
}, setIdentity);
Nan::SetMethod(target, "setIdentity", core_general_callback::callback);
//interface IsetIdentity {
// (mtx: _st.InputOutputArray, s? : _types.Scalar /* = new _scalar.Scalar(1)*/): void;
//}
//
//export var setIdentity: IsetIdentity = alvision_module.setIdentity;
//CV_EXPORTS_W void setIdentity(mtx : _st.InputOutputArray, s : _scalar.Scalar /* = new _scalar.Scalar(1)*/);
/** @brief Returns the determinant of a square floating-point matrix.
The function determinant calculates and returns the determinant of the
specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the
direct method is used. For larger matrices, the function uses LU
factorization with partial pivoting.
For symmetric positively-determined matrices, it is also possible to use
eigen decomposition to calculate the determinant.
@param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and
square size.
@sa trace, invert, solve, eigen, @ref MatrixExpressions
*/
overload->addOverload("core", "", "determinant", {
make_param<IOArray*>("mtx","IOArray")
}, determinant);
Nan::SetMethod(target, "determinant", core_general_callback::callback);
//interface Ideterminant {
// (mtx: _st.InputArray): _st.double;
//}
//
//export var determinant: Ideterminant = alvision_module.determinant;
//CV_EXPORTS_W double determinant(m : _st.InputArraytx);
/** @brief Returns the trace of a matrix.
The function trace returns the sum of the diagonal elements of the
matrix mtx .
\f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f]
@param mtx input matrix.
*/
overload->addOverload("core", "", "trace", {
make_param<IOArray*>("mtx","IOArray")
}, trace);
Nan::SetMethod(target, "trace", core_general_callback::callback);
//export interface Itrace {
// (mtx: _st.InputArray): _types.Scalar;
//}
//
//export var trace: Itrace = alvision_module.trace;
//CV_EXPORTS_W Scalar trace(mtx : _st.InputArray);
/** @brief Finds the inverse or pseudo-inverse of a matrix.
The function invert inverts the matrix src and stores the result in dst
. When the matrix src is singular or non-square, the function calculates
the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is
minimal, where I is an identity matrix.
In case of the DECOMP_LU method, the function returns non-zero value if
the inverse has been successfully calculated and 0 if src is singular.
In case of the DECOMP_SVD method, the function returns the inverse
condition number of src (the ratio of the smallest singular value to the
largest singular value) and 0 if src is singular. The SVD method
calculates a pseudo-inverse matrix if src is singular.
Similarly to DECOMP_LU, the method DECOMP_CHOLESKY works only with
non-singular square matrices that should also be symmetrical and
positively defined. In this case, the function stores the inverted
matrix in dst and returns non-zero. Otherwise, it returns 0.
@param src input floating-point M x N matrix.
@param dst output matrix of N x M size and the same type as src.
@param flags inversion method (cv::DecompTypes)
@sa solve, SVD
*/
overload->addOverload("core", "", "invert", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("flags","DecompTypes",cv::DECOMP_LU)
}, invert);
Nan::SetMethod(target, "invert", core_general_callback::callback);
//export interface Iinvert {
// (src: _st.InputArray, dst: _st.OutputArray, flags? : _base.DecompTypes | _st.int /*= DECOMP_LU*/): _st.double;
//}
//
//export var invert: Iinvert = alvision_module.invert;
//CV_EXPORTS_W double invert(src : _st.InputArray, dst : _st.OutputArray, int flags = DECOMP_LU);
/** @brief Solves one or more linear systems or least-squares problems.
The function solve solves a linear system or least-squares problem (the
latter is possible with SVD or QR methods, or by specifying the flag
DECOMP_NORMAL ):
\f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f]
If DECOMP_LU or DECOMP_CHOLESKY method is used, the function returns 1
if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise,
it returns 0. In the latter case, dst is not valid. Other methods find a
pseudo-solution in case of a singular left-hand side part.
@note If you want to find a unity-norm solution of an under-defined
singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve
will not do the work. Use SVD::solveZ instead.
@param src1 input matrix on the left-hand side of the system.
@param src2 input matrix on the right-hand side of the system.
@param dst output solution.
@param flags solution (matrix inversion) method (cv::DecompTypes)
@sa invert, SVD, eigen
*/
overload->addOverload("core", "", "solve", {
make_param<IOArray*>("src1","IOArray"),
make_param<IOArray*>("src2","IOArray"),
make_param<IOArray*>( "dst","IOArray"),
make_param<int>("flags","DecompTypes",cv::DECOMP_LU)
}, solve);
Nan::SetMethod(target, "solve", core_general_callback::callback);
//export interface Isolve {
// (src1: _st.InputArray, src2: _st.InputArray,
// dst: _st.OutputArray, flags: _base.DecompTypes /* = DECOMP_LU*/): boolean;
//}
//
//export var solve: Isolve = alvision_module.solve;
//CV_EXPORTS_W bool solve(src1 : _st.InputArray, src2 : _st.InputArray,
// dst : _st.OutputArray, int flags = DECOMP_LU);
/** @brief Sorts each row or each column of a matrix.
The function sort sorts each matrix row or each matrix column in
ascending or descending order. So you should pass two operation flags to
get desired behaviour. If you want to sort matrix rows or columns
lexicographically, you can use STL std::sort generic function with the
proper comparison predicate.
@param src input single-channel array.
@param dst output array of the same size and type as src.
@param flags operation flags, a combination of cv::SortFlags
@sa sortIdx, randShuffle
*/
overload->addOverload("core", "", "sort", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("flags","SortFlags")
}, sort);
Nan::SetMethod(target, "sort", core_general_callback::callback);
//export interface Isort {
// (src: _st.InputArray, dst: _st.OutputArray, flags: SortFlags): void;
//}
//
//export var sort: Isort = alvision_module.sort;
//CV_EXPORTS_W void sort(src : _st.InputArray, dst : _st.OutputArray, int flags);
/** @brief Sorts each row or each column of a matrix.
The function sortIdx sorts each matrix row or each matrix column in the
ascending or descending order. So you should pass two operation flags to
get desired behaviour. Instead of reordering the elements themselves, it
stores the indices of sorted elements in the output array. For example:
@code
Mat A = Mat::eye(3,3,CV_32F), B;
sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING);
// B will probably contain
// (because of equal elements in A some permutations are possible):
// [[1, 2, 0], [0, 2, 1], [0, 1, 2]]
@endcode
@param src input single-channel array.
@param dst output integer array of the same size as src.
@param flags operation flags that could be a combination of cv::SortFlags
@sa sort, randShuffle
*/
overload->addOverload("core", "", "sortIdx", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("flags","int"),
}, sortIdx);
Nan::SetMethod(target, "sortIdx", core_general_callback::callback);
//export interface IsortIdx {
// (src: _st.InputArray, dst: _st.OutputArray, flags : _st.int): void;
//}
//
//export var sortIdx: IsortIdx = alvision_module.sortIdx;
//CV_EXPORTS_W void sortIdx(src : _st.InputArray, dst : _st.OutputArray, int flags);
/** @brief Finds the real roots of a cubic equation.
The function solveCubic finds the real roots of a cubic equation:
- if coeffs is a 4-element vector:
\f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f]
- if coeffs is a 3-element vector:
\f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f]
The roots are stored in the roots array.
@param coeffs equation coefficients, an array of 3 or 4 elements.
@param roots output array of real roots that has 1 or 3 elements.
*/
overload->addOverload("core", "", "solveCubic", {
make_param<IOArray*>("coeffs","IOArray"),
make_param<IOArray*>( "roots","IOArray")
}, solveCubic);
Nan::SetMethod(target, "solveCubic", core_general_callback::callback);
//export interface IsolveCubic {
// (coeffs: _st.InputArray, roots: _st.OutputArray): _st.int;
//}
//
//export var solveCubic: IsolveCubic = alvision_module.solveCubic;
//CV_EXPORTS_W int solveCubic(coeffs : _st.InputArray, roots: st_OutputArray);
/** @brief Finds the real or complex roots of a polynomial equation.
The function solvePoly finds real and complex roots of a polynomial equation:
\f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f]
@param coeffs array of polynomial coefficients.
@param roots output (complex) array of roots.
@param maxIters maximum number of iterations the algorithm does.
*/
overload->addOverload("core", "", "solvePoly", {
make_param<IOArray*>("coeffs","IOArray"),
make_param<IOArray*>( "roots","IOArray"),
make_param<int>("maxIters","int", 300)
}, solvePoly);
Nan::SetMethod(target, "solvePoly", core_general_callback::callback);
//export interface IsolvePoly {
// (coeffs: _st.InputArray, roots: _st.OutputArray, maxIters : _st.int /* = 300*/): _st.double;
//}
//
//export var solvePoly: IsolvePoly = alvision_module.solvePoly;
//CV_EXPORTS_W double solvePoly(coeffs : _st.InputArray, roots: st_OutputArray, int maxIters = 300);
/** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix.
The functions eigen calculate just eigenvalues, or eigenvalues and eigenvectors of the symmetric
matrix src:
@code
src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t()
@endcode
@note in the new and the old interfaces different ordering of eigenvalues and eigenvectors
parameters is used.
@param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical
(src ^T^ == src).
@param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored
in the descending order.
@param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the
eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding
eigenvalues.
@sa completeSymm , PCA
*/
overload->addOverload("core", "", "eigen", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("eigenvalues","IOArray"),
make_param<IOArray*>("eigenvectors","IOArray",IOArray::noArray())
}, eigen);
Nan::SetMethod(target, "eigen", core_general_callback::callback);
//export interface Ieigen {
// (src: _st.InputArray, eigenvalues: _st.OutputArray ,
// eigenvectors?: _st.OutputArray /* = noArray()*/): boolean;
//}
//
//export var eigen: Ieigen = alvision_module.eigen;
//CV_EXPORTS_W bool eigen(src : _st.InputArray, OutputArray eigenvalues,
// OutputArray eigenvectors = noArray());
/** @brief Calculates the covariance matrix of a set of vectors.
The functions calcCovarMatrix calculate the covariance matrix and, optionally, the mean vector of
the set of input vectors.
@param samples samples stored as separate matrices
@param nsamples number of samples
@param covar output covariance matrix of the type ctype and square size.
@param mean input or output (depending on the flags) array as the average value of the input vectors.
@param flags operation flags as a combination of cv::CovarFlags
@param ctype type of the matrixl; it equals 'CV_64F' by default.
@sa PCA, mulTransposed, Mahalanobis
@todo InputArrayOfArrays
*/
//export interface IcalcCovarMatrix {
// (samples: Array<_mat.Mat>, covar: _mat.Mat, mean: _mat.Mat,
// flags: _st.int, ctype?: _st.int /* = CV_64F*/): void;
//}
//export var calcCovarMatrix: IcalcCovarMatrix = alvision_module.calcCovarMatrix;
//CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,
// int flags, int ctype = CV_64F);
/** @overload
@note use cv::COVAR_ROWS or cv::COVAR_COLS flag
@param samples samples stored as rows/columns of a single matrix.
@param covar output covariance matrix of the type ctype and square size.
@param mean input or output (depending on the flags) array as the average value of the input vectors.
@param flags operation flags as a combination of cv::CovarFlags
@param ctype type of the matrixl; it equals 'CV_64F' by default.
*/
overload->addOverload("core", "", "calcCovarMatrix", {
make_param<IOArray*>("samples","IOArray"),
make_param<IOArray*>( "covar","IOArray"),
make_param<IOArray*>( "mean","IOArray"),
make_param<int>("flags","int"),
make_param<int>("ctype","int",CV_64F)
}, calcCovarMatrix_array);
Nan::SetMethod(target, "calcCovarMatrix", core_general_callback::callback);
overload->addOverload("core", "", "calcCovarMatrix", {
make_param<std::shared_ptr<std::vector<Matrix*>>>("samples","Array<Mat>"),
make_param<Matrix*>("covar","Mat"),
make_param<Matrix*>( "mean","Mat"),
make_param<int>("flags","int"),
make_param<int>("ctype","int",CV_64F)
}, calcCovarMatrix_mat);
//export interface IcalcCovarMatrix {
// (samples: _st.InputArray , covar: _st.OutputArray,
// Inputmean: _st.OutputArray, flags: _st.int, ctype?: _st.int /* = CV_64F*/): void;
// (samples: Array<_mat.Mat>, covar: _mat.Mat, mean: _mat.Mat,
// flags: _st.int, ctype?: _st.int /* = CV_64F*/): void;
//}
//
//export var calcCovarMatrix: IcalcCovarMatrix = alvision_module.calcCovarMatrix;
//CV_EXPORTS_W void calcCovarMatrix(InputArray samples, c : _st.OutputArrayovar,
// Inputmean : _st.OutputArray, int flags, int ctype = CV_64F);
//export interface IPCACompute {
// PCACompute(data: _st.InputArray, mean: _st.InputOutputArray,
// eigenvectors: _st.OutputArray, maxComponents: _st.int /* = 0*/): void;
//}
//export var PCACompute: IPCACompute = alvision_module.PCACompute;
/** wrap PCA::operator() */
//CV_EXPORTS_W void PCACompute(data : _st.InputArray, mean : _st.InputOutputArray,
//OutputArray eigenvectors, int maxComponents = 0);
overload->addOverload("core", "", "PCACompute_variance", {
make_param<IOArray*>("data","IOArray"),
make_param<IOArray*>("mean","IOArray"),
make_param<IOArray*>("eigenvectors","IOArray"),
make_param<double>("retainedVariance","double")
}, PCACompute_variance);
Nan::SetMethod(target, "PCACompute_variance", core_general_callback::callback);
overload->addOverload("core", "", "PCACompute_maxComponents", {
make_param<IOArray*>("data","IOArray"),
make_param<IOArray*>("mean","IOArray"),
make_param<IOArray*>("eigenvectors","IOArray"),
make_param<int>("maxComponents","int", 0)
}, PCACompute_maxComponents);
Nan::SetMethod(target, "PCACompute_maxComponents", core_general_callback::callback);
//export interface IPCACompute_variance {
// (data : _st.InputArray, mean : _st.InputOutputArray,
// eigenvectors : _st.OutputArray, retainedVariance : _st.double) : void;
//
//}
//export var PCACompute_variance : IPCACompute_variance = alvision_module.PCACompute_variance;
//
//export interface IPCACompute_maxComponents {
// (data : _st.InputArray, mean : _st.InputOutputArray,
// eigenvectors : _st.OutputArray, maxComponents : _st.int /* = 0*/) : void;
//}
//export var PCACompute_maxComponents : IPCACompute_maxComponents = alvision_module.PCACompute_maxComponents;
/** wrap PCA::operator() */
//CV_EXPORTS_W void PCACompute(data : _st.InputArray, Inputmean : _st.OutputArray,
// OutputArray eigenvectors, double retainedVariance);
overload->addOverload("core", "", "PCAProject", {
make_param<IOArray*>("data","IOArray"),
make_param<IOArray*>("mean","IOArray"),
make_param<IOArray*>("eigenvectors","IOArray"),
make_param<IOArray*>("result","IOArray")
}, PCAProject);
Nan::SetMethod(target, "PCAProject", core_general_callback::callback);
//export interface IPCAProject {
// (data: _st.InputArray, mean: _st.InputArray,
// eigenvectors: _st.InputArray, result: _st.OutputArray): void;
//}
//
//export var PCAProject: IPCAProject = alvision_module.PCAProject;
/** wrap PCA::project */
//CV_EXPORTS_W void PCAProject(data : _st.InputArray, mean : _st.InputArray,
// eigenvectors : _st.InputArray, result : _st.OutputArray);
overload->addOverload("core", "", "PCABackProject", {
make_param<IOArray*>("data","IOArray"),
make_param<IOArray*>("mean","IOArray"),
make_param<IOArray*>("eigenvectors","IOArray"),
make_param<IOArray*>("result","IOArray")
}, PCABackProject);
Nan::SetMethod(target, "PCABackProject", core_general_callback::callback);
//export interface IPCABackProject {
// (data: _st.InputArray, mean: _st.InputArray,
// eigenvectors: _st.InputArray, result: _st.OutputArray) : void
//}
//
//export var PCABackProject: IPCABackProject = alvision_module.PCABackProject;
/** wrap PCA::backProject */
// CV_EXPORTS_W void PCABackProject(data : _st.InputArray, mean : _st.InputArray,
// eigenvectors : _st.InputArray, result : _st.OutputArray);
overload->addOverload("core", "", "SVDecomp", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>( "w","IOArray"),
make_param<IOArray*>( "u","IOArray"),
make_param<IOArray*>( "vt","IOArray"),
make_param<int>("flags","int", 0)
}, SVDecomp);
Nan::SetMethod(target, "SVDecomp", core_general_callback::callback);
//export interface ISVDecomp{
// (src: _st.InputArray, w : _st.OutputArray, u : _st.OutputArray, vt : _st.OutputArray, flags : _st.int /* = 0*/): void;
//}
//
//export var SVDecomp: ISVDecomp = alvision_module.SVDecomp;
/** wrap SVD::compute */
//CV_EXPORTS_W void SVDecomp(src : _st.InputArray, w : _st.OutputArray, u : _st.OutputArray, vt : _st.OutputArray, flags : _st.int /* = 0*/);
overload->addOverload("core", "", "SVBackSubst", {
make_param<IOArray*>( "w","IOArray"),
make_param<IOArray*>( "u","IOArray"),
make_param<IOArray*>( "vt","IOArray"),
make_param<IOArray*>("rhs","IOArray"),
make_param<IOArray*>("dst","IOArray")
}, SVBackSubst);
Nan::SetMethod(target, "SVBackSubst", core_general_callback::callback);
//export interface ISVBackSubst{
// (w: _st.InputArray, u: _st.InputArray, vt: _st.InputArray,
// rhs: _st.InputArray, dst: _st.OutputArray): void;
//}
//
//export var SVBackSubst: ISVBackSubst = alvision_module.SVBackSubst;
/** wrap SVD::backSubst */
//CV_EXPORTS_W void SVBackSubst(w : _st.InputArray, u : _st.InputArray, vt : _st.InputArray,
// rhs : _st.InputArray, dst : _st.OutputArray );
/** @brief Calculates the Mahalanobis distance between two vectors.
The function Mahalanobis calculates and returns the weighted distance between two vectors:
\f[d( \texttt{vec1} , \texttt{vec2} )= \sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})} }\f]
The covariance matrix may be calculated using the cv::calcCovarMatrix function and then inverted using
the invert function (preferably using the cv::DECOMP_SVD method, as the most accurate).
@param v1 first 1D input vector.
@param v2 second 1D input vector.
@param icovar inverse covariance matrix.
*/
overload->addOverload("core", "", "Mahalanobis", {
make_param<IOArray*>( "v1","IOArray"),
make_param<IOArray*>( "v2","IOArray"),
make_param<IOArray*>("icovar","IOArray")
}, Mahalanobis);
Nan::SetMethod(target, "Mahalanobis", core_general_callback::callback);
//export interface IMahalanobis{
// (v1: _st.InputArray, v2: _st.InputArray, icovar: _st.InputArray): _st.double;
//}
//
//export var Mahalanobis: IMahalanobis = alvision_module.Mahalanobis;
//CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar);
/** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
The function performs one of the following:
- Forward the Fourier transform of a 1D vector of N elements:
\f[Y = F^{(N)} \cdot X,\f]
where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$
- Inverse the Fourier transform of a 1D vector of N elements:
\f[\begin{array}{l} X'= \left (F^{(N)} \right )^{-1} \cdot Y = \left (F^{(N)} \right )^* \cdot y \\ X = (1/N) \cdot X, \end{array}\f]
where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$
- Forward the 2D Fourier transform of a M x N matrix:
\f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f]
- Inverse the 2D Fourier transform of a M x N matrix:
\f[\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\f]
In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input
spectrum of the inverse Fourier transform can be represented in a packed format called *CCS*
(complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here
is how 2D *CCS* spectrum looks:
\f[\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\f]
In case of 1D transform of a real vector, the output looks like the first row of the matrix above.
So, the function chooses an operation mode depending on the flags and size of the input array:
- If DFT_ROWS is set or the input array has a single row or single column, the function
performs a 1D forward or inverse transform of each row of a matrix when DFT_ROWS is set.
Otherwise, it performs a 2D transform.
- If the input array is real and DFT_INVERSE is not set, the function performs a forward 1D or
2D transform:
- When DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as
input.
- When DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as
input. In case of 2D transform, it uses the packed format as shown above. In case of a
single 1D transform, it looks like the first row of the matrix above. In case of
multiple 1D transforms (when using the DFT_ROWS flag), each row of the output matrix
looks like the first row of the matrix above.
- If the input array is complex and either DFT_INVERSE or DFT_REAL_OUTPUT are not set, the
output is a complex array of the same size as input. The function performs a forward or
inverse 1D or 2D transform of the whole input array or each row of the input array
independently, depending on the flags DFT_INVERSE and DFT_ROWS.
- When DFT_INVERSE is set and the input array is real, or it is complex but DFT_REAL_OUTPUT
is set, the output is a real array of the same size as input. The function performs a 1D or 2D
inverse transformation of the whole input array or each individual row, depending on the flags
DFT_INVERSE and DFT_ROWS.
If DFT_SCALE is set, the scaling is done after the transformation.
Unlike dct , the function supports arrays of arbitrary size. But only those arrays are processed
efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the
current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize
method.
The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays:
@code
void convolveDFT(InputArray A, InputArray B, OutputArray C)
{
// reallocate the output array if needed
C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type());
Size dftSize;
// calculate the size of DFT transform
dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1);
dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1);
// allocate temporary buffers and initialize them with 0's
Mat tempA(dftSize, A.type(), Scalar::all(0));
Mat tempB(dftSize, B.type(), Scalar::all(0));
// copy A and B to the top-left corners of tempA and tempB, respectively
Mat roiA(tempA, Rect(0,0,A.cols,A.rows));
A.copyTo(roiA);
Mat roiB(tempB, Rect(0,0,B.cols,B.rows));
B.copyTo(roiB);
// now transform the padded A & B in-place;
// use "nonzeroRows" hint for faster processing
dft(tempA, tempA, 0, A.rows);
dft(tempB, tempB, 0, B.rows);
// multiply the spectrums;
// the function handles packed spectrum representations well
mulSpectrums(tempA, tempB, tempA);
// transform the product back from the frequency domain.
// Even though all the result rows will be non-zero,
// you need only the first C.rows of them, and thus you
// pass nonzeroRows == C.rows
dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows);
// now copy the result back to C.
tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C);
// all the temporary buffers will be deallocated automatically
}
@endcode
To optimize this sample, consider the following approaches:
- Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to
the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole
tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols)
rightmost columns of the matrices.
- This DFT-based convolution does not have to be applied to the whole big arrays, especially if B
is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts.
To do this, you need to split the output array C into multiple tiles. For each tile, estimate
which parts of A and B are required to calculate convolution in this tile. If the tiles in C are
too small, the speed will decrease a lot because of repeated work. In the ultimate case, when
each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution
algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and
there is also a slowdown because of bad cache locality. So, there is an optimal tile size
somewhere in the middle.
- If different tiles in C can be calculated in parallel and, thus, the convolution is done by
parts, the loop can be threaded.
All of the above improvements have been implemented in matchTemplate and filter2D . Therefore, by
using them, you can get the performance even better than with the above theoretically optimal
implementation. Though, those two functions actually calculate cross-correlation, not convolution,
so you need to "flip" the second convolution operand B vertically and horizontally using flip .
@note
- An example using the discrete fourier transform can be found at
opencv_source_code/samples/cpp/dft.cpp
- (Python) An example using the dft functionality to perform Wiener deconvolution can be found
at opencv_source/samples/python/deconvolution.py
- (Python) An example rearranging the quadrants of a Fourier image can be found at
opencv_source/samples/python/dft.py
@param src input array that could be real or complex.
@param dst output array whose size and type depends on the flags .
@param flags transformation flags, representing a combination of the cv::DftFlags
@param nonzeroRows when the parameter is not zero, the function assumes that only the first
nonzeroRows rows of the input array (DFT_INVERSE is not set) or only the first nonzeroRows of the
output array (DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the
rows more efficiently and save some time; this technique is very useful for calculating array
cross-correlation or convolution using DFT.
@sa dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar ,
magnitude , phase
*/
overload->addOverload("core", "", "dft", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("flags","DftFlags",0),
make_param<int>("nonzeroRows","int",0)
}, dft);
Nan::SetMethod(target, "dft", core_general_callback::callback);
// interface Idft{
// (src: _st.InputArray, dst: _st.OutputArray, flags?: _base.DftFlags | _st.int /* = 0*/, nonzeroRows? : _st.int /* = 0*/): void;
// }
//
// export var dft: Idft = alvision_module.dft;
//CV_EXPORTS_W void dft(src : _st.InputArray, dst : _st.OutputArray, flags : _st.int /* = 0*/, int nonzeroRows = 0);
/** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array.
idft(src, dst, flags) is equivalent to dft(src, dst, flags | DFT_INVERSE) .
@note None of dft and idft scales the result by default. So, you should pass DFT_SCALE to one of
dft or idft explicitly to make these transforms mutually inverse.
@sa dft, dct, idct, mulSpectrums, getOptimalDFTSize
@param src input floating-point real or complex array.
@param dst output array whose size and type depend on the flags.
@param flags operation flags (see dft and cv::DftFlags).
@param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see
the convolution sample in dft description.
*/
overload->addOverload("core", "", "idft", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("flags","DftFlags", 0),
make_param<int>("nonzeroRows","int", 0)
}, idft);
Nan::SetMethod(target, "idft", core_general_callback::callback);
// interface Iidft{
// (src: _st.InputArray, dst: _st.OutputArray, flags?: _base.DftFlags | _st.int /* = 0*/, nonzeroRows?: _st.int /* = 0*/): void;
// }
//
// export var idft: Iidft = alvision_module.idft;
//CV_EXPORTS_W void idft(src : _st.InputArray, dst : _st.OutputArray, flags : _st.int /* = 0*/, int nonzeroRows = 0);
/** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array.
The function dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D
floating-point array:
- Forward Cosine transform of a 1D vector of N elements:
\f[Y = C^{(N)} \cdot X\f]
where
\f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f]
and
\f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*.
- Inverse Cosine transform of a 1D vector of N elements:
\f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f]
(since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ )
- Forward 2D Cosine transform of M x N matrix:
\f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f]
- Inverse 2D Cosine transform of M x N matrix:
\f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f]
The function chooses the mode of operation by looking at the flags and size of the input array:
- If (flags & DCT_INVERSE) == 0 , the function does a forward 1D or 2D transform. Otherwise, it
is an inverse 1D or 2D transform.
- If (flags & DCT_ROWS) != 0 , the function performs a 1D transform of each row.
- If the array is a single column or a single row, the function performs a 1D transform.
- If none of the above is true, the function performs a 2D transform.
@note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you
can pad the array when necessary.
Also, the function performance depends very much, and not monotonically, on the array size (see
getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT
of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as:
@code
size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); }
N1 = getOptimalDCTSize(N);
@endcode
@param src input floating-point array.
@param dst output array of the same size and type as src .
@param flags transformation flags as a combination of cv::DftFlags (DCT_*)
@sa dft , getOptimalDFTSize , idct
*/
overload->addOverload("core", "", "dct", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("flags","int", 0)
}, dct);
Nan::SetMethod(target, "dct", core_general_callback::callback);
// interface Idct {
// (src: _st.InputArray, dst: _st.OutputArray, flags: _st.int /* = 0*/): void;
// }
//
// export var dct: Idct = alvision_module.dct;
//CV_EXPORTS_W void dct(src : _st.InputArray, dst : _st.OutputArray, flags : _st.int /* = 0*/);
/** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array.
idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE).
@param src input floating-point single-channel array.
@param dst output array of the same size and type as src.
@param flags operation flags.
@sa dct, dft, idft, getOptimalDFTSize
*/
overload->addOverload("core", "", "idct", {
make_param<IOArray*>("src","IOArray"),
make_param<IOArray*>("dst","IOArray"),
make_param<int>("flags","int",0)
}, idct);
Nan::SetMethod(target, "idct", core_general_callback::callback);
//interface Iidct {
// (src: _st.InputArray, dst: _st.OutputArray, flags : _st.int /*= 0*/): void;
//}
//
//export var idct: Idct = alvision_module.idct;
//CV_EXPORTS_W void idct(src : _st.InputArray, dst : _st.OutputArray, flags : _st.int /* = 0*/);
/** @brief Performs the per-element multiplication of two Fourier spectrums.
The function mulSpectrums performs the per-element multiplication of the two CCS-packed or complex
matrices that are results of a real or complex Fourier transform.
The function, together with dft and idft , may be used to calculate convolution (pass conjB=false )
or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are
simply multiplied (per element) with an optional conjugation of the second-array elements. When the
arrays are real, they are assumed to be CCS-packed (see dft for details).
@param a first input array.
@param b second input array of the same size and type as src1 .
@param c output array of the same size and type as src1 .
@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that
each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value.
@param conjB optional flag that conjugates the second input array before the multiplication (true)
or not (false).
*/
overload->addOverload("core", "", "mulSpectrums", {
make_param<IOArray*>("a","IOArray"),
make_param<IOArray*>("b","IOArray"),
make_param<IOArray*>("c","IOArray"),
make_param<int>("flags","int"),
make_param<bool>("conjB","bool", false)
}, mulSpectrums);
Nan::SetMethod(target, "mulSpectrums", core_general_callback::callback);
// interface ImulSpectrums{
// (a : _st.InputArray, b : _st.InputArray, c : _st.OutputArray,
// flags: _st.int, conjB : boolean /*= false*/);
//}
//
// export var mulSpectrums: ImulSpectrums = alvision_module.mulSpectrums;
//CV_EXPORTS_W void mulSpectrums(a : _st.InputArray, b : _st.InputArray, c : _st.OutputArray,
// int flags, bool conjB = false);
/** @brief Returns the optimal DFT size for a given vector size.
DFT performance is not a monotonic function of a vector size. Therefore, when you calculate
convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to
pad the input data with zeros to get a bit larger array that can be transformed much faster than the
original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process.
Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2)
are also processed quite efficiently.
The function getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize
so that the DFT of a vector of size N can be processed efficiently. In the current implementation N
= 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r.
The function returns a negative number if vecsize is too large (very close to INT_MAX ).
While the function cannot be used directly to estimate the optimal vector size for DCT transform
(since the current DCT implementation supports only even-size vectors), it can be easily processed
as getOptimalDFTSize((vecsize+1)/2)\*2.
@param vecsize vector size.
@sa dft , dct , idft , idct , mulSpectrums
*/
overload->addOverload("core", "", "getOptimalDFTSize", {
make_param<int>("vecsize","int"),
}, getOptimalDFTSize);
Nan::SetMethod(target, "getOptimalDFTSize", core_general_callback::callback);
// interface IgetOptimalDFTSize {
// (vecsize: _st.int): _st.int;
// }
//
// export var getOptimalDFTSize: IgetOptimalDFTSize = alvision_module.getOptimalDFTSize;
//CV_EXPORTS_W int getOptimalDFTSize(int vecsize);
/** @brief Returns the default random number generator.
The function theRNG returns the default random number generator. For each thread, there is a
separate random number generator, so you can use the function safely in multi-thread environments.
If you just need to get a single random number using this generator or initialize an array, you can
use randu or randn instead. But if you are going to generate many random numbers inside a loop, it
is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() .
@sa RNG, randu, randn
*/
overload->addOverload("core", "", "theRNG", {}, theRNG);
Nan::SetMethod(target, "theRNG", core_general_callback::callback);
// interface ItheRNG {
// (): RNG;
// }
//
// export var theRNG: ItheRNG = alvision_module.theRNG;
//CV_EXPORTS RNG& theRNG();
/** @brief Generates a single uniformly-distributed random number or an array of random numbers.
Non-template variant of the function fills the matrix dst with uniformly-distributed
random numbers from the specified range:
\f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f]
@param dst output array of random numbers; the array must be pre-allocated.
@param low inclusive lower boundary of the generated random numbers.
@param high exclusive upper boundary of the generated random numbers.
@sa RNG, randn, theRNG
*/
overload->addOverload("core", "", "randu", {
make_param<IOArray*>( "dst","IOArray"),
make_param<IOArray*>( "low","IOArray"),
make_param<IOArray*>("high","IOArray")
}, randu);
Nan::SetMethod(target, "randu", core_general_callback::callback);
overload->addOverload("core", "", "randu", {
make_param<IOArray*>("dst","IOArray"),
make_param<double>( "low","double"),
make_param<double>("high","double")
}, randu_number);
//interface Irandu {
// (dst: _st.InputOutputArray, low : _st.InputArray | Number, high : _st.InputArray | Number): void;
//}
//
//export var randu: Irandu = alvision_module.randu;
//CV_EXPORTS_W void randu(Inputdst : _st.OutputArray, low : _st.InputArray, high : _st.InputArray);
/** @brief Fills the array with normally distributed random numbers.
The function randn fills the matrix dst with normally distributed random numbers with the specified
mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the
value range of the output array data type.
@param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels.
@param mean mean value (expectation) of the generated random numbers.
@param stddev standard deviation of the generated random numbers; it can be either a vector (in
which case a diagonal standard deviation matrix is assumed) or a square matrix.
@sa RNG, randu
*/
overload->addOverload("core", "", "randn", {
make_param<IOArray*>( "dst","IOArray"),
make_param<IOArray*>( "mean","IOArray"),
make_param<IOArray*>("stddev","IOArray")
}, randn);
Nan::SetMethod(target, "randn", core_general_callback::callback);
//interface Irandn{
// (dst: _st.InputOutputArray, mean: _st.InputArray, stddev : _st.InputArray): void;
//}
//
//export var randn: Irandn = alvision_module.randn;
//CV_EXPORTS_W void randn(Inputdst : _st.OutputArray, mean : _st.InputArray, stddev : _st.InputArray);
/** @brief Shuffles the array elements randomly.
The function randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and
swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor .
@param dst input/output numerical 1D array.
@param iterFactor scale factor that determines the number of random swap operations (see the details
below).
@param rng optional random number generator used for shuffling; if it is zero, theRNG () is used
instead.
@sa RNG, sort
*/
overload->addOverload("core", "", "randShuffle", {
make_param<IOArray*>("dst","IOArray"),
make_param<double>("iterFactor","double", 1.),
make_param<RNG*>("rng","RNG",RNG::create(0))
}, randShuffle);
Nan::SetMethod(target, "randShuffle", core_general_callback::callback);
// interface IrandShuffle{
// (dst: _st.InputOutputArray, iterFactor: _st.double /* = 1.*/, rng: RNG /*= 0*/): void;
// }
//
// export var randShuffle: IrandShuffle = alvision_module.randShuffle;
//CV_EXPORTS_W void randShuffle(Inputdst : _st.OutputArray, double iterFactor = 1., RNG * rng = 0);
//PCA::Init(target, overload);
//LDA::Init(target, overload);
//SVD::Init(target, overload);
//RNG::Init(target, overload);
//RNG_MT19937::Init(target, overload);
//! @} core_array
//! @addtogroup core_cluster
//! @{
/** @example kmeans.cpp
An example on K-means clustering
*/
/** @brief Finds centers of clusters and groups input samples around the clusters.
The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters
and groups the input samples around the clusters. As an output, \f$\texttt{labels}_i\f$ contains a
0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix.
@note
- (Python) An example on K-means clustering can be found at
opencv_source_code/samples/python/kmeans.py
@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed.
Examples of this array can be:
- Mat points(count, 2, CV_32F);
- Mat points(count, 1, CV_32FC2);
- Mat points(1, count, CV_32FC2);
- std::vector\<cv::Point2f\> points(sampleCount);
@param K Number of clusters to split the set by.
@param bestLabels Input/output integer array that stores the cluster indices for every sample.
@param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or
the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster
centers moves by less than criteria.epsilon on some iteration, the algorithm stops.
@param attempts Flag to specify the number of times the algorithm is executed using different
initial labellings. The algorithm returns the labels that yield the best compactness (see the last
function parameter).
@param flags Flag that can take values of cv::KmeansFlags
@param centers Output matrix of the cluster centers, one row per each cluster center.
@return The function returns the compactness measure that is computed as
\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f]
after every attempt. The best (minimum) value is chosen and the corresponding labels and the
compactness value are returned by the function. Basically, you can use only the core of the
function, set the number of attempts to 1, initialize labels each time using a custom algorithm,
pass them with the ( flags = KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best
(most-compact) clustering.
*/
overload->addOverload("core", "", "kmeans", {
make_param<IOArray*>("data","IOArray"),
make_param<int>("K","int"),
make_param<IOArray*>("bestLabels","IOArray"),
make_param<TermCriteria*>("criteria","TermCriteria"),
make_param<int>("attempts","int"),
make_param<int>("flags","int"),
make_param<IOArray*>("centers","IOArray",IOArray:: noArray())
}, kmeans);
Nan::SetMethod(target, "kmeans", core_general_callback::callback);
//interface Ikmeans {
// (data: _st.InputArray, K: _st.int, bestLabels: _st.InputOutputArray ,
// criteria: _types.TermCriteria, attempts: _st.int ,
// flags: _st.int, centers: _st.OutputArray /* = noArray()*/): _st.double;
//}
//
//export var kmeans: Ikmeans = alvision_module.kmeans;
//! @} core_cluster
//! @addtogroup core_basic
//! @{
/////////////////////////////// Formatted output of cv::Mat ///////////////////////////
/** @todo document */
//interface Formatted
//{
// // public:
// // virtual const char* next() = 0;
// // virtual void reset() = 0;
// // virtual ~Formatted();
//};
/** @todo document */
//interface Formatter
//{
// // public:
// // enum { FMT_DEFAULT = 0,
// // FMT_MATLAB = 1,
// // FMT_CSV = 2,
// // FMT_PYTHON = 3,
// // FMT_NUMPY = 4,
// // FMT_C = 5
// // };
// //
// // virtual ~Formatter();
// //
// // virtual Ptr< Formatted > format(const Mat& mtx) const = 0;
// //
// // virtual void set32fPrecision(int p = 8) = 0;
// // virtual void set64fPrecision(int p = 16) = 0;
// // virtual void setMultiline(bool ml = true) = 0;
// //
// // static Ptr < Formatter > get(int fmt = FMT_DEFAULT);
//
//};
//static inline
//String & operator << (String & out, Ptr < Formatted > fmtd)
//{
// fmtd ->reset();
// for (const char* str = fmtd->next(); str; str = fmtd ->next())
// out += cv::String(str);
// return out;
//}
//
//static inline
//String & operator << (String & out, const Mat& mtx)
// {
// return out << Formatter::get()->format(mtx);
//}
//template <> struct ParamType< bool >
// {
// typedef bool const_param_type;
// typedef bool member_type;
//
// enum { type = Param::BOOLEAN };
// };
//
//template <> struct ParamType< int >
// {
// typedef int const_param_type;
// typedef int member_type;
//
// enum { type = Param::INT };
// };
//
//template <> struct ParamType< double >
// {
// typedef double const_param_type;
// typedef double member_type;
//
// enum { type = Param::REAL };
// };
//
//template <> struct ParamType< String >
// {
// typedef const String& const_param_type;
// typedef String member_type;
//
// enum { type = Param::STRING };
// };
//
//template <> struct ParamType< Mat >
// {
// typedef const Mat& const_param_type;
// typedef Mat member_type;
//
// enum { type = Param::MAT };
// };
//
//template <> struct ParamType< std::vector < Mat > >
// {
// typedef const std::vector<Mat>& const_param_type;
//typedef std::vector < Mat > member_type;
//
//enum { type = Param::MAT_VECTOR };
//};
//
//template <> struct ParamType< Algorithm >
// {
// typedef const Ptr<Algorithm>& const_param_type;
// typedef Ptr< Algorithm > member_type;
//
// enum { type = Param::ALGORITHM };
// };
//
//template <> struct ParamType< float >
// {
// typedef float const_param_type;
// typedef float member_type;
//
// enum { type = Param::FLOAT };
// };
//
//template <> struct ParamType< unsigned >
// {
// typedef unsigned const_param_type;
// typedef unsigned member_type;
//
// enum { type = Param::UNSIGNED_INT };
// };
//
//template <> struct ParamType< uint64 >
// {
// typedef uint64 const_param_type;
// typedef uint64 member_type;
//
// enum { type = Param::UINT64 };
// };
//
//template <> struct ParamType< uchar >
// {
// typedef uchar const_param_type;
// typedef uchar member_type;
//
// enum { type = Param::UCHAR };
// };
//! @} core_basic
//} //namespace cv
//#include "opencv2/core/operations.hpp"
//#include "opencv2/core/cvstd.inl.hpp"
//#include "opencv2/core/utility.hpp"
//#include "opencv2/core/optim.hpp"
//#endif /*__OPENCV_CORE_HPP__*/
//RNG::Init(target, overload);
//RNG_MT19937::Init(target, overload);
//
//ConjGradSolver::Init(target, overload);
//DownhillSolver::Init(target, overload);
//MinProblemSolver::Init(target, overload);
//Algorithm::Init(target, overload);
//DMatch::Init(target, overload);
};
POLY_METHOD(core::swap_mat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::swap_umat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::borderInterpolate){throw std::runtime_error("not implemented");}
POLY_METHOD(core::copyMakeBorder){throw std::runtime_error("not implemented");}
POLY_METHOD(core::add){
auto src1 = info.at<IOArray*>(0)->GetInputArray();
auto src2 = info.at<IOArray*>(1)->GetInputArray();
auto dst = info.at<IOArray*>(2)->GetOutputArray();
auto mask = info.at<IOArray*>(3)->GetInputArray();
auto dtype= info.at<int>(4);
cv::add(src1, src2, dst, mask, dtype);
}
POLY_METHOD(core::subtract){throw std::runtime_error("not implemented");}
POLY_METHOD(core::multiply){throw std::runtime_error("not implemented");}
POLY_METHOD(core::divide_mat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::divide_scale){throw std::runtime_error("not implemented");}
POLY_METHOD(core::scaleAdd){throw std::runtime_error("not implemented");}
POLY_METHOD(core::addWeighted){
auto src1 = info.at<IOArray*>(0)->GetInputArray();
auto alpha = info.at<double>(1);
auto src2 = info.at<IOArray*>(2)->GetInputArray();
auto beta = info.at<double>(3);
auto gamma = info.at<double>(4);
auto dst = info.at<IOArray*>(5)->GetOutputArray();
auto dtype = info.at<int>(6);
cv::addWeighted(src1, alpha, src2, beta, gamma, dst, dtype);
}
POLY_METHOD(core::convertScaleAbs){throw std::runtime_error("not implemented");}
POLY_METHOD(core::LUT){throw std::runtime_error("not implemented");}
POLY_METHOD(core::sum){throw std::runtime_error("not implemented");}
POLY_METHOD(core::countNonZero){throw std::runtime_error("not implemented");}
POLY_METHOD(core::findNonZero){throw std::runtime_error("not implemented");}
POLY_METHOD(core::mean){throw std::runtime_error("not implemented");}
POLY_METHOD(core::meanStdDev){throw std::runtime_error("not implemented");}
POLY_METHOD(core::norm){
auto src1 = info.at<IOArray*>(0)->GetInputArray();
auto normType = info.at<int>(1);
auto mask = info.at<IOArray*>(2)->GetInputArray();
info.SetReturnValue(cv::norm(src1, normType, mask));
}
POLY_METHOD(core::norm_src2){
auto src1 = info.at<IOArray*>(0)->GetInputArray();
auto src2 = info.at<IOArray*>(1)->GetInputArray();
auto normType = info.at<int>(2);
auto mask = info.at<IOArray*>(3)->GetInputArray();
info.SetReturnValue(cv::norm(src1, src2, normType, mask));
}
POLY_METHOD(core::norm_simple){
auto src = *info.at<SparseMat*>(0)->_sparseMat;
auto normType = info.at<int>(1);
info.SetReturnValue(cv::norm(src, normType));
}
POLY_METHOD(core::PSNR){throw std::runtime_error("not implemented");}
POLY_METHOD(core::batchDistance){throw std::runtime_error("not implemented");}
POLY_METHOD(core::normalize){throw std::runtime_error("not implemented");}
POLY_METHOD(core::normalize_sparse){throw std::runtime_error("not implemented");}
POLY_METHOD(core::minMaxIdx){throw std::runtime_error("not implemented");}
POLY_METHOD(core::minMaxLoc_sparse){throw std::runtime_error("not implemented");}
POLY_METHOD(core::minMaxLoc){throw std::runtime_error("not implemented");}
POLY_METHOD(core::reduce){throw std::runtime_error("not implemented");}
POLY_METHOD(core::merge_arr){throw std::runtime_error("not implemented");}
POLY_METHOD(core::merge_size){throw std::runtime_error("not implemented");}
POLY_METHOD(core::split_array){throw std::runtime_error("not implemented");}
POLY_METHOD(core::split_mat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::mixChannels_arr_npairs){throw std::runtime_error("not implemented");}
POLY_METHOD(core::mixChannels_arr){throw std::runtime_error("not implemented");}
POLY_METHOD(core::mixChannels_mat_npairs){throw std::runtime_error("not implemented");}
POLY_METHOD(core::mixChannels_mat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::extractChannel){throw std::runtime_error("not implemented");}
POLY_METHOD(core::insertChannel){throw std::runtime_error("not implemented");}
POLY_METHOD(core::flip){throw std::runtime_error("not implemented");}
POLY_METHOD(core::repeat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::repeat_mat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::hconcat_mat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::hconcat_inputarray){throw std::runtime_error("not implemented");}
POLY_METHOD(core::hconcat_arrayorarrays){throw std::runtime_error("not implemented");}
POLY_METHOD(core::vconcat_array){throw std::runtime_error("not implemented");}
POLY_METHOD(core::vconcat_2src){throw std::runtime_error("not implemented");}
POLY_METHOD(core::vconcat_matrix_array){throw std::runtime_error("not implemented");}
POLY_METHOD(core::bitwise_and){throw std::runtime_error("not implemented");}
POLY_METHOD(core::bitwise_or){throw std::runtime_error("not implemented");}
POLY_METHOD(core::bitwise_xor){throw std::runtime_error("not implemented");}
POLY_METHOD(core::bitwise_not){throw std::runtime_error("not implemented");}
POLY_METHOD(core::absdiff){
auto src1 = info.at<IOArray*>(0)->GetInputArray();
auto src2 = info.at<IOArray*>(1)->GetInputArray();
auto dst = info.at<IOArray*>(2)->GetOutputArray();
cv::absdiff(src1, src2, dst);
}
POLY_METHOD(core::inRange){throw std::runtime_error("not implemented");}
POLY_METHOD(core::compare){throw std::runtime_error("not implemented");}
POLY_METHOD(core::compare_number){throw std::runtime_error("not implemented");}
POLY_METHOD(core::min_array){throw std::runtime_error("not implemented");}
POLY_METHOD(core::min_mat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::min_umat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::max_array){throw std::runtime_error("not implemented");}
POLY_METHOD(core::max_mat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::max_umat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::sqrt){throw std::runtime_error("not implemented");}
POLY_METHOD(core::pow){throw std::runtime_error("not implemented");}
POLY_METHOD(core::exp){throw std::runtime_error("not implemented");}
POLY_METHOD(core::log){throw std::runtime_error("not implemented");}
POLY_METHOD(core::polarToCart){throw std::runtime_error("not implemented");}
POLY_METHOD(core::cartToPolar){throw std::runtime_error("not implemented");}
POLY_METHOD(core::phase){throw std::runtime_error("not implemented");}
POLY_METHOD(core::magnitude){throw std::runtime_error("not implemented");}
POLY_METHOD(core::checkRange){throw std::runtime_error("not implemented");}
POLY_METHOD(core::patchNaNs){throw std::runtime_error("not implemented");}
POLY_METHOD(core::gemm){throw std::runtime_error("not implemented");}
POLY_METHOD(core::mulTransposed){throw std::runtime_error("not implemented");}
POLY_METHOD(core::transpose){throw std::runtime_error("not implemented");}
POLY_METHOD(core::transform){throw std::runtime_error("not implemented");}
POLY_METHOD(core::perspectiveTransform){throw std::runtime_error("not implemented");}
POLY_METHOD(core::completeSymm){throw std::runtime_error("not implemented");}
POLY_METHOD(core::setIdentity){throw std::runtime_error("not implemented");}
POLY_METHOD(core::determinant){throw std::runtime_error("not implemented");}
POLY_METHOD(core::trace){throw std::runtime_error("not implemented");}
POLY_METHOD(core::invert){throw std::runtime_error("not implemented");}
POLY_METHOD(core::solve){throw std::runtime_error("not implemented");}
POLY_METHOD(core::sort){throw std::runtime_error("not implemented");}
POLY_METHOD(core::sortIdx){throw std::runtime_error("not implemented");}
POLY_METHOD(core::solveCubic){throw std::runtime_error("not implemented");}
POLY_METHOD(core::solvePoly){throw std::runtime_error("not implemented");}
POLY_METHOD(core::eigen){throw std::runtime_error("not implemented");}
POLY_METHOD(core::calcCovarMatrix_array){throw std::runtime_error("not implemented");}
POLY_METHOD(core::calcCovarMatrix_mat){throw std::runtime_error("not implemented");}
POLY_METHOD(core::PCACompute_variance){throw std::runtime_error("not implemented");}
POLY_METHOD(core::PCACompute_maxComponents){throw std::runtime_error("not implemented");}
POLY_METHOD(core::PCAProject){throw std::runtime_error("not implemented");}
POLY_METHOD(core::PCABackProject){throw std::runtime_error("not implemented");}
POLY_METHOD(core::SVDecomp){throw std::runtime_error("not implemented");}
POLY_METHOD(core::SVBackSubst){throw std::runtime_error("not implemented");}
POLY_METHOD(core::Mahalanobis){throw std::runtime_error("not implemented");}
POLY_METHOD(core::dft){throw std::runtime_error("not implemented");}
POLY_METHOD(core::idft){throw std::runtime_error("not implemented");}
POLY_METHOD(core::dct){throw std::runtime_error("not implemented");}
POLY_METHOD(core::idct){throw std::runtime_error("not implemented");}
POLY_METHOD(core::mulSpectrums){throw std::runtime_error("not implemented");}
POLY_METHOD(core::getOptimalDFTSize){throw std::runtime_error("not implemented");}
POLY_METHOD(core::theRNG){
auto rng = new RNG();
rng->_rng = std::make_shared<cv::RNG>(cv::theRNG());
info.SetReturnValue(rng);
}
POLY_METHOD(core::randu){
auto dst = info.at<IOArray*>(0)->GetInputOutputArray();
auto low = info.at<IOArray*>(1)->GetInputArray();
auto high = info.at<IOArray*>(2)->GetInputArray();
cv::randu(dst, low, high);
}
POLY_METHOD(core::randu_number){
auto dst = info.at<IOArray*>(0)->GetInputOutputArray();
auto low = info.at<double>(1);
auto high = info.at<double>(2);
cv::randu(dst, low, high);
}
POLY_METHOD(core::randn){throw std::runtime_error("not implemented");}
POLY_METHOD(core::randShuffle){throw std::runtime_error("not implemented");}
POLY_METHOD(core::kmeans){throw std::runtime_error("not implemented");}
| [
"drorgl@yahoo.com"
] | drorgl@yahoo.com |
a5f52e539efb2660934788504e05cee7d7c26636 | 201c2251a68337ba09c9b993fe1989d595125eb9 | /codeforces/Jeff and Periods.cpp | a624e16ecd679aa7739a8f849b602d3492da485e | [] | no_license | AhmedKhaledAK/problem-solving-training | 92a928ca383d37abe493145d306e52cb08d5b4ef | 54dd37aef981ab1a8d55e46cf9f57ab1426f6353 | refs/heads/master | 2022-03-16T07:42:28.785189 | 2022-02-12T19:54:54 | 2022-02-12T19:54:54 | 191,613,437 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,345 | cpp | #include <iostream>
#include<bits/stdc++.h>
#include <iomanip>
#define array_size(a) (sizeof(a)/sizeof(a[0]))
#define lpi(n) for(int i=0; i<n; i++)
#define lpiv(v,n) for(int i=v; i<n; i++)
#define lpj(n) for(int j=0; j<n; j++)
#define lpjv(v,n) for(int j=v; j<n; j++)
#define iii pair<int,pair<int,int>>
#define ii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define pf push_front
#define mp make_pair
#define vi vector<int>
#define vip vector<pair<int,int>>
#define pqig priority_queue<int>
#define pqil priority_queue<int, vector<int>, greater<int>>
#define filein(ff) freopen(ff, "r", stdin)
#define fileout(ff) freopen(ff, "w", stdout)
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL);
using namespace std;
typedef long long ll;
ll fastpow(ll nodess, ll num) {
if (!num)
return 1;
if (num % 2)
return nodess * fastpow(nodess, num - 1)/*%mod*/;
ll p = fastpow(nodess, num / 2);
// p %= mod;
p *= p;
// p %= mod;
return p;
}
ll my_mod(ll num, ll mod) {
ll reto = num % mod;
while (reto < 0)
reto += mod;
return reto;
}
ll gcd(ll u, ll v) { return !u ? v : gcd(v % u, u); }
ll dist(pair<ll, ll> u, pair<ll, ll> v) {
return abs(u.fi - v.fi) + abs(u.se - v.se);
}
ll lcm(ll a, ll b){
return a / __gcd(a, b) * b;
}
int diff[100001], last[100001], freq[100001];
int main(int argc, const char * argv[]) {
fastio;
int n;
cin >> n;
int ar[n];
lpi(n)cin>>ar[i];
lpi(n){
if(last[ar[i]]!=-1){
if(freq[ar[i]]==0){
diff[ar[i]]=0;
last[ar[i]]=i;
freq[ar[i]]++;
} else if(freq[ar[i]]==1){
diff[ar[i]]=i-last[ar[i]];
last[ar[i]]=i;
freq[ar[i]]++;
} else{
if(i-last[ar[i]]!=diff[ar[i]]){
last[ar[i]]=-1;
} else {
last[ar[i]]=i;
}
}
}
}
vip pr;
lpi(n){
if(last[ar[i]]!=-1){
pr.pb({ar[i], diff[ar[i]]});
last[ar[i]]=-1;
}
}
sort(pr.begin(), pr.end());
cout << pr.size() << endl;
lpi(pr.size()){
cout << pr[i].fi << " " << pr[i].se << endl;
}
return 0;
}
| [
"ahmedkhaledabab@gmail.com"
] | ahmedkhaledabab@gmail.com |
51c1011ed455ecb81e01a5316b46bb45c66f01e9 | 602e0f4bae605f59d23688cab5ad10c21fc5a34f | /MyToolKit/NumericalRecipes/examples/xbsstep.cpp | 6da7d5665853f23099a984f0c9a422ad4623cc34 | [] | no_license | yanbcxf/cpp | d7f26056d51f85254ae1dd2c4e8e459cfefb2fb6 | e059b02e7f1509918bbc346c555d42e8d06f4b8f | refs/heads/master | 2023-08-04T04:40:43.475657 | 2023-08-01T14:03:44 | 2023-08-01T14:03:44 | 172,408,660 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,741 | cpp | #include <iostream>
#include <iomanip>
#include "nr.h"
using namespace std;
// Driver for routine bsstep
DP dxsav; // defining declarations
int kmax,kount;
Vec_DP *xp_p;
Mat_DP *yp_p;
int nrhs; // counts function evaluations
void derivs(const DP x, Vec_I_DP &y,
Vec_O_DP &dydx)
{
nrhs++;
dydx[0]= -y[1];
dydx[1]=y[0]-(1.0/x)*y[1];
dydx[2]=y[1]-(2.0/x)*y[2];
dydx[3]=y[2]-(3.0/x)*y[3];
}
int main(void)
{
const int N=4;
int i,nbad,nok;
DP eps=1.0e-4,h1=0.1,hmin=0.0,x1=1.0,x2=10.0;
Vec_DP ystart(N);
ystart[0]=NR::bessj0(x1);
ystart[1]=NR::bessj1(x1);
ystart[2]=NR::bessj(2,x1);
ystart[3]=NR::bessj(3,x1);
nrhs=0;
dxsav=(x2-x1)/20.0;
kmax=100;
xp_p=new Vec_DP(kmax);
yp_p=new Mat_DP(N,kmax);
Vec_DP &xp=*xp_p;
Mat_DP &yp=*yp_p;
NR::odeint(ystart,x1,x2,eps,h1,hmin,nok,nbad,derivs,NR::bsstep);
cout << fixed << setprecision(6);
cout << endl << "successful steps:" << setw(14) << " ";
cout << setw(4) << nok << endl;
cout << "bad steps:" << setw(21) << " " << setw(4) << nbad << endl;
cout << "function evaluations:" << setw(10) << " ";
cout << setw(4) << nrhs << endl;
cout << endl << "stored intermediate values: ";
cout << setw(4) << kount << endl;
cout << endl << setw(8) << "x" << setw(19) << "integral";
cout << setw(16) << "bessj(3,x)" << endl;
for (i=0;i<kount;i++) {
cout << setw(10) << xp[i] << setw(17) << yp[3][i];
cout << setw(15) << NR::bessj(3,xp[i]) << endl;
}
delete xp_p;
delete yp_p;
return 0;
}
| [
"yangbin@star-net.cn"
] | yangbin@star-net.cn |
72f236dbb141b561e00e6c240c3ec5e3af2757d2 | d83b1262afdfa7be71d1f4d79e79fbde62cad994 | /include/oneapi/dpl/internal/async_impl/async_impl_hetero.h | 3ffe694bdb4de3ae8fcf369573a57012091e18ca | [
"Apache-2.0"
] | permissive | jiejanezhang/oneDPL | f6daa7ae3b2fc94f4b839643d9499769175131df | abd1de347aac7f21d55099773908ecf5f5e49f76 | refs/heads/main | 2023-04-20T10:36:12.407723 | 2021-04-29T06:12:35 | 2021-04-29T06:12:35 | 335,866,554 | 0 | 0 | null | 2021-02-04T06:58:08 | 2021-02-04T06:54:24 | null | UTF-8 | C++ | false | false | 10,435 | h | /*
* Copyright (c) Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _ONEDPL_ASYNC_IMPL_HETERO_H
#define _ONEDPL_ASYNC_IMPL_HETERO_H
#if _ONEDPL_BACKEND_SYCL
# include "async_backend_sycl.h"
#endif
namespace oneapi
{
namespace dpl
{
namespace __internal
{
template <typename _ExecutionPolicy, typename _ForwardIterator, typename _Function>
oneapi::dpl::__internal::__enable_if_device_execution_policy<_ExecutionPolicy,
oneapi::dpl::__par_backend_hetero::__future<void>>
__pattern_walk1_async(_ExecutionPolicy&& __exec, _ForwardIterator __first, _ForwardIterator __last, _Function __f)
{
auto __n = __last - __first;
if (__n <= 0)
return oneapi::dpl::__par_backend_hetero::__future<void>(sycl::event{});
auto __keep =
oneapi::dpl::__ranges::__get_sycl_range<__par_backend_hetero::access_mode::read_write, _ForwardIterator>();
auto __buf = __keep(__first, __last);
auto __future_obj = oneapi::dpl::__par_backend_hetero::__parallel_for(
::std::forward<_ExecutionPolicy>(__exec), unseq_backend::walk_n<_ExecutionPolicy, _Function>{__f}, __n,
__buf.all_view());
return __future_obj;
}
template <typename _IsSync = ::std::false_type,
__par_backend_hetero::access_mode __acc_mode1 = __par_backend_hetero::access_mode::read,
__par_backend_hetero::access_mode __acc_mode2 = __par_backend_hetero::access_mode::write,
typename _ExecutionPolicy, typename _ForwardIterator1, typename _ForwardIterator2, typename _Function>
oneapi::dpl::__internal::__enable_if_device_execution_policy<_ExecutionPolicy,
oneapi::dpl::__internal::__future<_ForwardIterator2>>
__pattern_walk2_async(_ExecutionPolicy&& __exec, _ForwardIterator1 __first1, _ForwardIterator1 __last1,
_ForwardIterator2 __first2, _Function __f)
{
auto __n = __last1 - __first1;
if (__n <= 0)
return oneapi::dpl::__internal::__future<_ForwardIterator2>(sycl::event{}, __first2);
auto __keep1 = oneapi::dpl::__ranges::__get_sycl_range<__acc_mode1, _ForwardIterator1>();
auto __buf1 = __keep1(__first1, __last1);
auto __keep2 = oneapi::dpl::__ranges::__get_sycl_range<__acc_mode2, _ForwardIterator2>();
auto __buf2 = __keep2(__first2, __first2 + __n);
auto __future_obj = oneapi::dpl::__par_backend_hetero::__parallel_for(
::std::forward<_ExecutionPolicy>(__exec), unseq_backend::walk_n<_ExecutionPolicy, _Function>{__f}, __n,
__buf1.all_view(), __buf2.all_view());
oneapi::dpl::__internal::__invoke_if(_IsSync(), [&__future_obj]() { __future_obj.wait(); });
return oneapi::dpl::__internal::__future<_ForwardIterator2>(__future_obj, __first2 + __n);
}
template <typename _ExecutionPolicy, typename _ForwardIterator1, typename _ForwardIterator2, typename _ForwardIterator3,
typename _Function>
oneapi::dpl::__internal::__enable_if_device_execution_policy<_ExecutionPolicy,
oneapi::dpl::__internal::__future<_ForwardIterator3>>
__pattern_walk3_async(_ExecutionPolicy&& __exec, _ForwardIterator1 __first1, _ForwardIterator1 __last1,
_ForwardIterator2 __first2, _ForwardIterator3 __first3, _Function __f)
{
auto __n = __last1 - __first1;
if (__n <= 0)
return oneapi::dpl::__internal::__future<_ForwardIterator3>(sycl::event{}, __first3);
auto __keep1 =
oneapi::dpl::__ranges::__get_sycl_range<__par_backend_hetero::access_mode::read, _ForwardIterator1>();
auto __buf1 = __keep1(__first1, __last1);
auto __keep2 =
oneapi::dpl::__ranges::__get_sycl_range<__par_backend_hetero::access_mode::read, _ForwardIterator2>();
auto __buf2 = __keep2(__first2, __first2 + __n);
auto __keep3 =
oneapi::dpl::__ranges::__get_sycl_range<__par_backend_hetero::access_mode::write, _ForwardIterator3>();
auto __buf3 = __keep3(__first3, __first3 + __n);
auto __future_obj = oneapi::dpl::__par_backend_hetero::__parallel_for(
::std::forward<_ExecutionPolicy>(__exec), unseq_backend::walk_n<_ExecutionPolicy, _Function>{__f}, __n,
__buf1.all_view(), __buf2.all_view(), __buf3.all_view());
return oneapi::dpl::__internal::__future<_ForwardIterator3>(__future_obj, __first3 + __n);
}
template <typename _ExecutionPolicy, typename _ForwardIterator1, typename _ForwardIterator2, typename _Brick>
oneapi::dpl::__internal::__enable_if_device_execution_policy<_ExecutionPolicy,
oneapi::dpl::__internal::__future<_ForwardIterator2>>
__pattern_walk2_brick_async(_ExecutionPolicy&& __exec, _ForwardIterator1 __first1, _ForwardIterator1 __last1,
_ForwardIterator2 __first2, _Brick __brick)
{
return __pattern_walk2_async(
__par_backend_hetero::make_wrapped_policy<__walk2_brick_wrapper>(::std::forward<_ExecutionPolicy>(__exec)),
__first1, __last1, __first2, __brick);
}
//------------------------------------------------------------------------
// transform_reduce (version with two binary functions)
//------------------------------------------------------------------------
template <typename _ExecutionPolicy, typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _Tp,
typename _BinaryOperation1, typename _BinaryOperation2>
oneapi::dpl::__internal::__enable_if_device_execution_policy<_ExecutionPolicy, oneapi::dpl::__internal::__future<_Tp>>
__pattern_transform_reduce_async(_ExecutionPolicy&& __exec, _RandomAccessIterator1 __first1,
_RandomAccessIterator1 __last1, _RandomAccessIterator2 __first2, _Tp __init,
_BinaryOperation1 __binary_op1, _BinaryOperation2 __binary_op2)
{
if (__first1 == __last1)
return oneapi::dpl::__internal::__future<_Tp>(__init);
using _Policy = _ExecutionPolicy;
using _Functor = unseq_backend::walk_n<_Policy, _BinaryOperation2>;
using _RepackedTp = __par_backend_hetero::__repacked_tuple_t<_Tp>;
auto __n = __last1 - __first1;
auto __keep1 =
oneapi::dpl::__ranges::__get_sycl_range<__par_backend_hetero::access_mode::read, _RandomAccessIterator1>();
auto __buf1 = __keep1(__first1, __last1);
auto __keep2 =
oneapi::dpl::__ranges::__get_sycl_range<__par_backend_hetero::access_mode::read, _RandomAccessIterator2>();
auto __buf2 = __keep2(__first2, __first2 + __n);
auto __res = oneapi::dpl::__par_backend_hetero::__parallel_transform_reduce_async<_RepackedTp>(
::std::forward<_ExecutionPolicy>(__exec),
unseq_backend::transform_init<_Policy, _BinaryOperation1, _Functor>{__binary_op1,
_Functor{__binary_op2}}, // transform
__binary_op1, // combine
unseq_backend::reduce<_Policy, _BinaryOperation1, _RepackedTp>{__binary_op1}, // reduce
__buf1.all_view(), __buf2.all_view());
__res.set(__init);
return __res;
}
//------------------------------------------------------------------------
// transform_reduce (with unary and binary functions)
//------------------------------------------------------------------------
template <typename _ExecutionPolicy, typename _ForwardIterator, typename _Tp, typename _BinaryOperation,
typename _UnaryOperation>
oneapi::dpl::__internal::__enable_if_device_execution_policy<_ExecutionPolicy, oneapi::dpl::__internal::__future<_Tp>>
__pattern_transform_reduce_async(_ExecutionPolicy&& __exec, _ForwardIterator __first, _ForwardIterator __last,
_Tp __init, _BinaryOperation __binary_op, _UnaryOperation __unary_op)
{
if (__first == __last)
return oneapi::dpl::__internal::__future<_Tp>(__init);
using _Policy = _ExecutionPolicy;
using _Functor = unseq_backend::walk_n<_Policy, _UnaryOperation>;
using _RepackedTp = __par_backend_hetero::__repacked_tuple_t<_Tp>;
auto __keep = oneapi::dpl::__ranges::__get_sycl_range<__par_backend_hetero::access_mode::read, _ForwardIterator>();
auto __buf = __keep(__first, __last);
auto res = oneapi::dpl::__par_backend_hetero::__parallel_transform_reduce_async<_RepackedTp>(
::std::forward<_ExecutionPolicy>(__exec),
unseq_backend::transform_init<_Policy, _BinaryOperation, _Functor>{__binary_op,
_Functor{__unary_op}}, // transform
__binary_op, // combine
unseq_backend::reduce<_Policy, _BinaryOperation, _RepackedTp>{__binary_op}, // reduce
__buf.all_view());
res.set(__init);
return res;
}
template <typename _ExecutionPolicy, typename _ForwardIterator, typename _T>
oneapi::dpl::__internal::__enable_if_device_execution_policy<_ExecutionPolicy,
oneapi::dpl::__par_backend_hetero::__future<void>>
__pattern_fill_async(_ExecutionPolicy&& __exec, _ForwardIterator __first, _ForwardIterator __last, const _T& __value)
{
auto ret_val =
__pattern_walk1_async(::std::forward<_ExecutionPolicy>(__exec),
__par_backend_hetero::make_iter_mode<__par_backend_hetero::access_mode::write>(__first),
__par_backend_hetero::make_iter_mode<__par_backend_hetero::access_mode::write>(__last),
fill_functor<_T>{__value});
return ret_val;
}
} // namespace __internal
} // namespace dpl
} // namespace oneapi
#endif /* _ONEDPL_ASYNC_IMPL_HETERO_H */
| [
"noreply@github.com"
] | noreply@github.com |
2f63256c1c7c47fba3df8d4e4e5c829a3f779c16 | 91914b2fca90139fdfe550378f927a592240726a | /C_Going_Home.cpp | c2ddcbcf2a9a3a35b52c68301a18594c1d44394a | [] | no_license | Suhrid-Talukder333/Codeforces-Problems | 89d6804ed0579d0eea1547e0db776530c61fd582 | 9e936da6bac377b4cb9d0a9be52d937c31e8cd03 | refs/heads/master | 2023-05-29T15:20:19.470592 | 2021-06-21T10:13:16 | 2021-06-21T10:13:16 | 290,012,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
map<int, vector<int, int>> sums;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++) {
sums[arr[i] + arr[j]].push_back(make_pair(i, j));
}
}
sort(sums.begin(), sums.end());
for (int i = 0; i < sums.size(); i++) {
for (int j = i + 1; j < sums.size(); j++) {
if(sums[i].first!=sums[j].first) {
break;
}
if (sums[i].second.first != sums[j].second.first && sums[i].second.first != sums[j].second.second && sums[i].second.second != sums[j].second.first && sums[i].second.second != sums[j].second.second)
{
cout << "YES" << endl;
cout << sums[i].second.first+1 << " " << sums[i].second.second+1 << " " << sums[j].second.first+1 << " " << sums[j].second.second+1;
return 0;
}
}
}
cout << "NO";
} | [
"suhridtalukder333@gmail.com"
] | suhridtalukder333@gmail.com |
2ccd32b0c85dd6974e6a486774af2992e094329c | d794d7c67de64c607970092bdb012f9197d1f2c6 | /Calculator/main.cpp | f9d0231ff5d1dec001ec039bc774a9825e5d560d | [] | no_license | ozeron/Calculator | 31e2c0c4addb3494a16cb8b9f3fff77fdb9bf582 | 7fa891cddc7e7af9b68e80ec31185fab59516105 | refs/heads/master | 2016-09-06T17:23:54.602199 | 2013-07-10T09:55:49 | 2013-07-10T09:55:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #include <cstdio>
#include "CLInterface.h"
#include "Word.h"
using namespace std;
int main()
{
CLITEST();
}
| [
"ozeron@me.com"
] | ozeron@me.com |
f1692c71b812580d1e064d8e3613eadaccc30ac7 | 4a9d73372541655770663a987a8558c49a88c314 | /Trees/Find floor of a key in BST.cpp | b87e0acc13289cd5018bfacd32f3102e74267329 | [] | no_license | AshishKempwad/Competitive-Coding | e70887a6f764a37736f95054d1db7cd2d3a07c11 | b58d98dc26cfd25783bc5e7b66bb59c52082ce6f | refs/heads/master | 2021-04-14T00:37:03.202768 | 2020-12-05T05:59:36 | 2020-12-05T05:59:36 | 249,198,252 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 400 | cpp | int find_floor(Node* root,int key)
{
int floor = -1;
while(root)
{
if(root->data == key)
{
floor = root->data;
retur floor;
}
if(root->data < key)
{
floor=root->data;
root=root->right;
}
else
{
root=root->left;
}
}
return floor;
}
| [
"noreply@github.com"
] | noreply@github.com |
0d5e04f652e0980229564e232ae413f898f2be72 | 8947812c9c0be1f0bb6c30d1bb225d4d6aafb488 | /01_Develop/libXMOpenCV/Source/gpu/cudastream.cpp | 21920cd5b258fceaf5953da6bd4644772aaaa2f4 | [
"MIT"
] | permissive | alissastanderwick/OpenKODE-Framework | cbb298974e7464d736a21b760c22721281b9c7ec | d4382d781da7f488a0e7667362a89e8e389468dd | refs/heads/master | 2021-10-25T01:33:37.821493 | 2016-07-12T01:29:35 | 2016-07-12T01:29:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,332 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
using namespace cv;
using namespace cv::gpu;
#if !defined (HAVE_CUDA)
void cv::gpu::Stream::create() { throw_nogpu(); }
void cv::gpu::Stream::release() { throw_nogpu(); }
cv::gpu::Stream::Stream() : impl(0) { throw_nogpu(); }
cv::gpu::Stream::~Stream() { throw_nogpu(); }
cv::gpu::Stream::Stream(const Stream& /*stream*/) { throw_nogpu(); }
Stream& cv::gpu::Stream::operator=(const Stream& /*stream*/) { throw_nogpu(); return *this; }
bool cv::gpu::Stream::queryIfComplete() { throw_nogpu(); return true; }
void cv::gpu::Stream::waitForCompletion() { throw_nogpu(); }
void cv::gpu::Stream::enqueueDownload(const GpuMat& /*src*/, Mat& /*dst*/) { throw_nogpu(); }
void cv::gpu::Stream::enqueueDownload(const GpuMat& /*src*/, CudaMem& /*dst*/) { throw_nogpu(); }
void cv::gpu::Stream::enqueueUpload(const CudaMem& /*src*/, GpuMat& /*dst*/) { throw_nogpu(); }
void cv::gpu::Stream::enqueueUpload(const Mat& /*src*/, GpuMat& /*dst*/) { throw_nogpu(); }
void cv::gpu::Stream::enqueueCopy(const GpuMat& /*src*/, GpuMat& /*dst*/) { throw_nogpu(); }
void cv::gpu::Stream::enqueueMemSet(GpuMat& /*src*/, Scalar /*val*/) { throw_nogpu(); }
void cv::gpu::Stream::enqueueMemSet(GpuMat& /*src*/, Scalar /*val*/, const GpuMat& /*mask*/) { throw_nogpu(); }
void cv::gpu::Stream::enqueueConvert(const GpuMat& /*src*/, GpuMat& /*dst*/, int /*type*/, double /*a*/, double /*b*/) { throw_nogpu(); }
Stream& cv::gpu::Stream::Null() { throw_nogpu(); static Stream s; return s; }
cv::gpu::Stream::operator bool() const { throw_nogpu(); return false; }
#else /* !defined (HAVE_CUDA) */
#include "XMOpenCV2/gpu/stream_accessor.hpp"
namespace cv { namespace gpu
{
void copyWithMask(const GpuMat& src, GpuMat& dst, const GpuMat& mask, cudaStream_t stream);
void convertTo(const GpuMat& src, GpuMat& dst, double alpha, double beta, cudaStream_t stream);
void setTo(GpuMat& src, Scalar s, cudaStream_t stream);
void setTo(GpuMat& src, Scalar s, const GpuMat& mask, cudaStream_t stream);
}}
struct Stream::Impl
{
static cudaStream_t getStream(const Impl* impl) { return impl ? impl->stream : 0; }
cudaStream_t stream;
int ref_counter;
};
namespace
{
template<class S, class D> void devcopy(const S& src, D& dst, cudaStream_t s, cudaMemcpyKind k)
{
dst.create(src.size(), src.type());
size_t bwidth = src.cols * src.elemSize();
cudaSafeCall( cudaMemcpy2DAsync(dst.data, dst.step, src.data, src.step, bwidth, src.rows, k, s) );
};
}
CV_EXPORTS cudaStream_t cv::gpu::StreamAccessor::getStream(const Stream& stream)
{
return Stream::Impl::getStream(stream.impl);
};
void cv::gpu::Stream::create()
{
if (impl)
release();
cudaStream_t stream;
cudaSafeCall( cudaStreamCreate( &stream ) );
impl = (Stream::Impl*)fastMalloc(sizeof(Stream::Impl));
impl->stream = stream;
impl->ref_counter = 1;
}
void cv::gpu::Stream::release()
{
if( impl && CV_XADD(&impl->ref_counter, -1) == 1 )
{
cudaSafeCall( cudaStreamDestroy( impl->stream ) );
cv::fastFree( impl );
}
}
cv::gpu::Stream::Stream() : impl(0) { create(); }
cv::gpu::Stream::~Stream() { release(); }
cv::gpu::Stream::Stream(const Stream& stream) : impl(stream.impl)
{
if( impl )
CV_XADD(&impl->ref_counter, 1);
}
Stream& cv::gpu::Stream::operator=(const Stream& stream)
{
if( this != &stream )
{
if( stream.impl )
CV_XADD(&stream.impl->ref_counter, 1);
release();
impl = stream.impl;
}
return *this;
}
bool cv::gpu::Stream::queryIfComplete()
{
cudaError_t err = cudaStreamQuery( Impl::getStream(impl) );
if (err == cudaErrorNotReady || err == cudaSuccess)
return err == cudaSuccess;
cudaSafeCall(err);
return false;
}
void cv::gpu::Stream::waitForCompletion() { cudaSafeCall( cudaStreamSynchronize( Impl::getStream(impl) ) ); }
void cv::gpu::Stream::enqueueDownload(const GpuMat& src, Mat& dst)
{
// if not -> allocation will be done, but after that dst will not point to page locked memory
CV_Assert(src.cols == dst.cols && src.rows == dst.rows && src.type() == dst.type() );
devcopy(src, dst, Impl::getStream(impl), cudaMemcpyDeviceToHost);
}
void cv::gpu::Stream::enqueueDownload(const GpuMat& src, CudaMem& dst) { devcopy(src, dst, Impl::getStream(impl), cudaMemcpyDeviceToHost); }
void cv::gpu::Stream::enqueueUpload(const CudaMem& src, GpuMat& dst){ devcopy(src, dst, Impl::getStream(impl), cudaMemcpyHostToDevice); }
void cv::gpu::Stream::enqueueUpload(const Mat& src, GpuMat& dst) { devcopy(src, dst, Impl::getStream(impl), cudaMemcpyHostToDevice); }
void cv::gpu::Stream::enqueueCopy(const GpuMat& src, GpuMat& dst) { devcopy(src, dst, Impl::getStream(impl), cudaMemcpyDeviceToDevice); }
void cv::gpu::Stream::enqueueMemSet(GpuMat& src, Scalar s)
{
CV_Assert((src.depth() != CV_64F) ||
(TargetArchs::builtWith(NATIVE_DOUBLE) && DeviceInfo().supports(NATIVE_DOUBLE)));
if (s[0] == 0.0 && s[1] == 0.0 && s[2] == 0.0 && s[3] == 0.0)
{
cudaSafeCall( cudaMemset2DAsync(src.data, src.step, 0, src.cols * src.elemSize(), src.rows, Impl::getStream(impl)) );
return;
}
if (src.depth() == CV_8U)
{
int cn = src.channels();
if (cn == 1 || (cn == 2 && s[0] == s[1]) || (cn == 3 && s[0] == s[1] && s[0] == s[2]) || (cn == 4 && s[0] == s[1] && s[0] == s[2] && s[0] == s[3]))
{
int val = saturate_cast<uchar>(s[0]);
cudaSafeCall( cudaMemset2DAsync(src.data, src.step, val, src.cols * src.elemSize(), src.rows, Impl::getStream(impl)) );
return;
}
}
setTo(src, s, Impl::getStream(impl));
}
void cv::gpu::Stream::enqueueMemSet(GpuMat& src, Scalar val, const GpuMat& mask)
{
CV_Assert((src.depth() != CV_64F) ||
(TargetArchs::builtWith(NATIVE_DOUBLE) && DeviceInfo().supports(NATIVE_DOUBLE)));
CV_Assert(mask.type() == CV_8UC1);
setTo(src, val, mask, Impl::getStream(impl));
}
void cv::gpu::Stream::enqueueConvert(const GpuMat& src, GpuMat& dst, int rtype, double alpha, double beta)
{
CV_Assert((src.depth() != CV_64F && CV_MAT_DEPTH(rtype) != CV_64F) ||
(TargetArchs::builtWith(NATIVE_DOUBLE) && DeviceInfo().supports(NATIVE_DOUBLE)));
bool noScale = fabs(alpha-1) < std::numeric_limits<double>::epsilon() && fabs(beta) < std::numeric_limits<double>::epsilon();
if( rtype < 0 )
rtype = src.type();
else
rtype = CV_MAKETYPE(CV_MAT_DEPTH(rtype), src.channels());
int sdepth = src.depth(), ddepth = CV_MAT_DEPTH(rtype);
if( sdepth == ddepth && noScale )
{
src.copyTo(dst);
return;
}
GpuMat temp;
const GpuMat* psrc = &src;
if( sdepth != ddepth && psrc == &dst )
psrc = &(temp = src);
dst.create( src.size(), rtype );
convertTo(src, dst, alpha, beta, Impl::getStream(impl));
}
cv::gpu::Stream::operator bool() const
{
return impl && impl->stream;
}
cv::gpu::Stream::Stream(Impl* impl_) : impl(impl_) {}
cv::gpu::Stream& cv::gpu::Stream::Null()
{
static Stream s((Impl*)0);
return s;
}
#endif /* !defined (HAVE_CUDA) */
| [
"mcodegeeks@gmail.com"
] | mcodegeeks@gmail.com |
3fa1ef4f3496ec81b8ac0c5ee6c1c135fed39471 | 4105b0217ed61c14252a9bf31d945a9f1c0ac5af | /elements-consensus-sys/depend/elements/src/node/coinstats.cpp | edfccfa6f86b31bebd31bb2cd8637f6ef66ac9cf | [
"MIT"
] | permissive | comit-network/rust-elements-consensus | e626ade550c3625adb6a4db8c82819ba30c4a1c5 | ac88dbedcd019eef44f58499417dcdbeda994b0b | refs/heads/master | 2023-08-08T09:35:49.028512 | 2021-08-05T05:31:35 | 2021-08-05T05:31:35 | 387,780,286 | 1 | 2 | null | 2023-07-28T06:40:53 | 2021-07-20T12:11:47 | C++ | UTF-8 | C++ | false | false | 4,224 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <node/coinstats.h>
#include <coins.h>
#include <hash.h>
#include <serialize.h>
#include <uint256.h>
#include <util/system.h>
#include <validation.h>
#include <map>
static uint64_t GetBogoSize(const CScript& scriptPubKey)
{
return 32 /* txid */ +
4 /* vout index */ +
4 /* height + coinbase */ +
8 /* amount */ +
2 /* scriptPubKey len */ +
scriptPubKey.size() /* scriptPubKey */;
}
static void ApplyStats(CCoinsStats& stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
{
assert(!outputs.empty());
ss << hash;
ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase ? 1u : 0u);
stats.nTransactions++;
for (const auto& output : outputs) {
ss << VARINT(output.first + 1);
ss << output.second.out.scriptPubKey;
ss << output.second.out.nValue;
ss << output.second.out.nAsset;
ss << output.second.out.nNonce;
stats.nTransactionOutputs++;
if (output.second.out.nValue.IsExplicit()) {
stats.nTotalAmount += output.second.out.nValue.GetAmount();
}
stats.nBogoSize += GetBogoSize(output.second.out.scriptPubKey);
}
ss << VARINT(0u);
}
static void ApplyStats(CCoinsStats& stats, std::nullptr_t, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
{
assert(!outputs.empty());
stats.nTransactions++;
for (const auto& output : outputs) {
stats.nTransactionOutputs++;
if (output.second.out.nValue.IsExplicit()) {
stats.nTotalAmount += output.second.out.nValue.GetAmount();
}
stats.nBogoSize += GetBogoSize(output.second.out.scriptPubKey);
}
}
//! Calculate statistics about the unspent transaction output set
template <typename T>
static bool GetUTXOStats(CCoinsView* view, CCoinsStats& stats, T hash_obj, const std::function<void()>& interruption_point)
{
stats = CCoinsStats();
std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
assert(pcursor);
stats.hashBlock = pcursor->GetBestBlock();
{
LOCK(cs_main);
stats.nHeight = LookupBlockIndex(stats.hashBlock)->nHeight;
}
PrepareHash(hash_obj, stats);
uint256 prevkey;
std::map<uint32_t, Coin> outputs;
while (pcursor->Valid()) {
interruption_point();
COutPoint key;
Coin coin;
if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
if (!outputs.empty() && key.hash != prevkey) {
ApplyStats(stats, hash_obj, prevkey, outputs);
outputs.clear();
}
prevkey = key.hash;
outputs[key.n] = std::move(coin);
stats.coins_count++;
} else {
return error("%s: unable to read value", __func__);
}
pcursor->Next();
}
if (!outputs.empty()) {
ApplyStats(stats, hash_obj, prevkey, outputs);
}
FinalizeHash(hash_obj, stats);
stats.nDiskSize = view->EstimateSize();
return true;
}
bool GetUTXOStats(CCoinsView* view, CCoinsStats& stats, CoinStatsHashType hash_type, const std::function<void()>& interruption_point)
{
switch (hash_type) {
case(CoinStatsHashType::HASH_SERIALIZED): {
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
return GetUTXOStats(view, stats, ss, interruption_point);
}
case(CoinStatsHashType::NONE): {
return GetUTXOStats(view, stats, nullptr, interruption_point);
}
} // no default case, so the compiler can warn about missing cases
assert(false);
}
// The legacy hash serializes the hashBlock
static void PrepareHash(CHashWriter& ss, CCoinsStats& stats)
{
ss << stats.hashBlock;
}
static void PrepareHash(std::nullptr_t, CCoinsStats& stats) {}
static void FinalizeHash(CHashWriter& ss, CCoinsStats& stats)
{
stats.hashSerialized = ss.GetHash();
}
static void FinalizeHash(std::nullptr_t, CCoinsStats& stats) {}
| [
"thomas@eizinger.io"
] | thomas@eizinger.io |
ef2d498699a4829a005b322038edba892ed183b6 | ac227cc22d5f5364e5d029a2cef83816a6954590 | /applications/physbam/physbam-lib/Public_Library/PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_FACE.h | 309569194257a038f131fb0e82e75c88c7c0af64 | [
"BSD-3-Clause"
] | permissive | schinmayee/nimbus | 597185bc8bac91a2480466cebc8b337f5d96bd2e | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | refs/heads/master | 2020-03-11T11:42:39.262834 | 2018-04-18T01:28:23 | 2018-04-18T01:28:23 | 129,976,755 | 0 | 0 | BSD-3-Clause | 2018-04-17T23:33:23 | 2018-04-17T23:33:23 | null | UTF-8 | C++ | false | false | 3,507 | h | //#####################################################################
// Copyright 2005-2008, Eran Guendelman, Jerry Talton.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class UNIFORM_GRID_ITERATOR_FACE
//#####################################################################
#ifndef __UNIFORM_GRID_ITERATOR_FACE__
#define __UNIFORM_GRID_ITERATOR_FACE__
#include <PhysBAM_Tools/Grids_Uniform/FACE_INDEX.h>
#include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR.h>
namespace PhysBAM{
template<class TV>
class UNIFORM_GRID_ITERATOR_FACE:public UNIFORM_GRID_ITERATOR<TV>
{
public:
typedef typename GRID<TV>::REGION T_REGION;typedef VECTOR<int,TV::dimension> TV_INT;typedef typename TV::SCALAR T;
typedef TV VECTOR_T;
using UNIFORM_GRID_ITERATOR<TV>::grid;using UNIFORM_GRID_ITERATOR<TV>::index;using UNIFORM_GRID_ITERATOR<TV>::region;using UNIFORM_GRID_ITERATOR<TV>::valid;
using UNIFORM_GRID_ITERATOR<TV>::Reset;using UNIFORM_GRID_ITERATOR<TV>::current_region;using UNIFORM_GRID_ITERATOR<TV>::Add_Region;
using UNIFORM_GRID_ITERATOR<TV>::Reset_Regions;
protected:
T_REGION region_type;
int side;
int axis;
bool single_axis;
int number_of_ghost_cells;
T face_size;
public:
// axis_input==0 means iterate through faces in all dimensions
UNIFORM_GRID_ITERATOR_FACE(const GRID<TV>& grid_input,const int number_of_ghost_cells_input=0,const T_REGION& region_type_input=GRID<TV>::WHOLE_REGION,const int side_input=0,
int axis_input=0);
UNIFORM_GRID_ITERATOR_FACE(const GRID<TV>& grid_input,const int axis_input,const TV_INT& face_index);
UNIFORM_GRID_ITERATOR_FACE(const GRID<TV>& grid_input,const RANGE<TV_INT>& explicit_region_input,const int axis_input);
private:
void Reset_Axis(const int axis_input);
void Next_Helper();
public:
void Next() PHYSBAM_ALWAYS_INLINE // overloads UNIFORM_GRID_ITERATOR::Next but we don't want that to be virtual to avoid virtual call overhead
{if(index(TV::dimension)<region.max_corner(TV::dimension)) index(TV::dimension)++;else Next_Helper();}
int Axis() const
{return axis;}
const TV_INT& Face_Index() const
{return index;}
FACE_INDEX<TV::dimension> Full_Index() const
{return FACE_INDEX<TV::dimension>(axis,index);}
T Face_Size() const
{return face_size;}
TV Location() const
{return grid.Face(axis,index);}
TV_INT First_Cell_Index() const
{TV_INT i(index);i(axis)--;return i;}
TV_INT Second_Cell_Index() const
{return index;}
void Unordered_Cell_Indices_Touching_Face(TV_INT& cell1,TV_INT& cell2) const
{cell1=First_Cell_Index();cell2=Second_Cell_Index();}
RANGE<TV> Dual_Cell() const
{return RANGE<TV>(Location()-(T).5*grid.dX,Location()+(T).5*grid.dX);}
TV First_Cell_Center() const
{return grid.Center(First_Cell_Index());}
TV Second_Cell_Center() const
{return grid.Center(Second_Cell_Index());}
bool First_Boundary() const // returns true if currently on left, bottom, or front boundary
{assert(region_type==GRID<TV>::BOUNDARY_REGION);return (!side && current_region%2==0) || (side && (side-1)%2==0);}
TV_INT Face_Node_Index(const int node) const // 1-based
{return grid.Face_Node_Index(axis,index,node);}
//#####################################################################
};
}
#endif
| [
"quhang@stanford.edu"
] | quhang@stanford.edu |
7bbdba95f28a207d465e858f888eceb50414854c | fb95534e8519acb3670ee9743ddb15bf09232e70 | /examples/xtd.tunit.examples/asserts/assert_is_greater_or_equal/src/assert_is_greater_or_equal.cpp | 585ee4eb375fd1cc509fdf0e40b4293f5b4c492e | [
"MIT"
] | permissive | niansa/xtd | a5050e27fda1f092cea85db264820d6518994893 | 4d412ab046f51da2e5baf782f9f2f5bb23c49840 | refs/heads/master | 2023-09-01T01:13:25.592979 | 2021-10-28T14:30:05 | 2021-10-28T14:30:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | cpp | #include <xtd/xtd.tunit>
using namespace xtd::tunit;
namespace unit_tests {
class test_class_(test) {
public:
void test_method_(test_case_succeed1) {
int i = 24;
assert::is_greater_or_equal(i, 12);
}
void test_method_(test_case_succeed2) {
int i = 24;
assert::is_greater_or_equal(i, 24);
}
void test_method_(test_case_failed) {
int i = 24;
assert::is_greater_or_equal(i, 48);
}
};
}
int main() {
return console_unit_test().run();
}
// This code produces the following output:
//
// Start 3 tests from 1 test case
// Run tests:
// SUCCEED test.test_case_succeed1 (0 ms total)
// SUCCEED test.test_case_succeed2 (0 ms total)
// FAILED test.test_case_failed (0 ms total)
// Expected: greater than or equal to 48
// But was: 24
// Stack Trace: in |---OMITTED---|/assert_is_greater_or_equal.cpp:18
//
// Test results:
// SUCCEED 2 tests.
// FAILED 1 test.
// End 3 tests from 1 test case ran. (0 ms total)
| [
"gammasoft71@gmail.com"
] | gammasoft71@gmail.com |
e976dd3077be19f7d50552ead6d4dee629948912 | 641816291fd4a3996fbe78300ffcf22715097c9c | /Client/AnpanMMO/Source/AnpanMMO/Level/TimeManager.h | 7ed18c87b34c57365e05b46534c65b9b65c2f1e5 | [] | no_license | uvbs/AnpanMMO | c0a5d3aa02693e036ff563e71d0f57ee914219bd | 0833ce57ca5301eee36e9547d50ef63e78d1ce9c | refs/heads/master | 2022-12-02T19:02:56.051613 | 2019-04-03T22:54:05 | 2019-04-03T22:54:05 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 677 | h | // Copyright 2018 - 2019 YanaPIIDXer All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
class ASkyControl;
class MemoryStreamInterface;
/**
* 時間管理.
*/
class ANPANMMO_API TimeManager
{
public:
// コンストラクタ
TimeManager();
// デストラクタ
~TimeManager() {}
// 天球をセット。
void SetSkyControl(ASkyControl *pInSky);
// 開始時の時間を受け取った。
bool OnRecvTime(MemoryStreamInterface *pStream);
// 時間変動を受け取った。
bool OnRecvTimeChange(MemoryStreamInterface *pStream);
private:
// 天球.
TWeakObjectPtr<ASkyControl> pSky;
// 現在のマスタID
uint32 CurrentMasterId;
};
| [
"yana_p_iidxer@yahoo.co.jp"
] | yana_p_iidxer@yahoo.co.jp |
468c647856baeebf7e006076ab1afb4d72f258cd | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.0085/NEOC7KETNO | 1a73dce6b4cc5f2b2b133d13a4bec476b1e005db | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.0085";
object NEOC7KETNO;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 3.69604e-58;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
6421786bd698086b5de8972df1d498255c08e5f3 | 965225d196d9246f40cc8d4255a24315103fef47 | /ch13/13.1/destructor.cc | 4c23c2b43c487dceb181c2591d26c3bb22a061b5 | [] | no_license | LinuxKernelDevelopment/cppprimer | 52fa1739e11e8bf4fda84f19083b33cfac930f3c | 28724e6db5cde4c8cd3f188ac6130425bc711fa9 | refs/heads/master | 2020-05-25T09:22:33.271140 | 2019-05-21T00:32:28 | 2019-05-21T00:32:28 | 187,732,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | cc | #include <iostream>
#include <vector>
struct X {
X() {std::cout << "X()" << std::endl;}
X(const X&) {std::cout << "X(const X&)" << std::endl;}
X& operator=(const X &rhs) {std::cout << "operator=(const X &rhs)" << std::endl; return *this; }
~X() {std::cout << "~X()" << std::endl;}
};
void Pass(X rhs)
{
std::cout << "Pass(X rhs) is called" << std::endl;
}
void pass(X &rhs)
{
std::cout << "Pass(X &rhs) is called" << std::endl;
}
int main(void)
{
X rhs;
Pass(rhs);
pass(rhs);
std::vector<X> xvec;
xvec.push_back(rhs);
return 0;
}
| [
"weizhefix@gmail.com"
] | weizhefix@gmail.com |
7eafe45beed22f2633dc3a91601a36030ffed737 | e2cc28e162f14551f189390c0896b0334b29eaba | /cpp_dsgn_pattern_n_derivatives_pricing/chapter14/book_example/source/source.cpp | 2e2059bd9d45dd2e7e78f5a34949a55675e640e0 | [
"MIT"
] | permissive | calvin456/intro_derivative_pricing | 3f3cf4f217e93377a7ade9b9a81cd8a8734177a7 | 0841fbc0344bee00044d67977faccfd2098b5887 | refs/heads/master | 2021-01-10T12:59:32.474807 | 2016-12-27T08:53:12 | 2016-12-27T08:53:12 | 46,112,607 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 900 | cpp | /*
Copyright (C) 2006 Mark Joshi
This file is part of XLW, a free-software/open-source C++ wrapper of the
Excel C API - http://xlw.sourceforge.net/
XLW is free software: you can redistribute it and/or modify it under the
terms of the XLW license. You should have received a copy of the
license along with this program; if not, please email xlw-users@lists.sf.net
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include "Test.h"
#include <ctime>
#include <windows.h>
#include<xlw/XlfExcel.h>
#include<xlw/XlOpenClose.h>
#include<xlw/XlfServices.h>
double // evaluate pay--off
PayOffEvaluation(const Wrapper<PayOff>& OptionPayOff // table for payoff
, double Spot // point for evaluation
)
{
return (*OptionPayOff)(Spot);
}
| [
"calvin456@users.noreply.github.com"
] | calvin456@users.noreply.github.com |
3dc5ad7304db366e1df0959bcf16275f03bf139e | 1dfc91dc48f91ba7eecd040e2c6baafac2b4c3c7 | /creature.hpp | 0ed4807569ee70507ca2b2be78b609365f2c2cb3 | [] | no_license | haomingvince/Zork | db521d3c5ec5a2dc7b69d94b02a3d0966999e047 | 44fef594be7337e3a002f3c00165c4476e805618 | refs/heads/master | 2020-04-02T04:51:18.565852 | 2018-11-01T18:02:10 | 2018-11-01T18:02:10 | 154,039,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | hpp | #ifndef _CREATURE_H
#define _CREATURE_H
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include "rapidxml.hpp"
#include "attack.hpp"
#include "trigger.hpp"
using namespace std;
class Creature {
public:
Creature(rapidxml::xml_node<>*);
virtual ~Creature();
void setupCreature(rapidxml::xml_node<>* node);
string name = "";
string status = "";
string description = "";
vector<string> vulnerability;
Attack* attack;
vector<Trigger*> trigger;
};
#endif | [
"haomingvince@gmail.com"
] | haomingvince@gmail.com |
1f2a3740c7733a45bf28735de66bdb5108f30f29 | a565eef51e8445b519288ac32affbd7adca874d3 | /libgringo/tests/input/lit_helper.hh | 0de3e895095509450180130a11bc2e7cc1bb0dd5 | [
"MIT"
] | permissive | CaptainUnbrauchbar/clingo | b28a9b5218552240ea03444e157a21079fc77019 | 58cb702db83c23aedea28b26a617102fae9b557a | refs/heads/master | 2023-02-27T23:53:44.566739 | 2021-02-01T18:36:10 | 2021-02-01T18:36:10 | 290,831,881 | 1 | 0 | MIT | 2021-02-01T18:36:11 | 2020-08-27T16:53:18 | C++ | UTF-8 | C++ | false | false | 3,348 | hh | // {{{ MIT License
// Copyright 2017 Roland Kaminski
// 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.
// }}}
#ifndef _GRINGO_TEST_LIT_HELPER_HH
#define _GRINGO_TEST_LIT_HELPER_HH
#include "tests/tests.hh"
#include "gringo/input/literals.hh"
namespace Gringo { namespace Input { namespace Test {
using namespace Gringo::Test;
// {{{ definition of functions to create literals
inline CSPMulTerm cspmul(UTerm &&coe, UTerm &&var = nullptr) {
return CSPMulTerm(std::move(var), std::move(coe));
}
inline void cspadd(CSPAddTerm &) { }
template <class... T>
inline void cspadd(CSPAddTerm &add, CSPMulTerm &&mul, T&&... args) {
add.append(std::move(mul));
cspadd(add, std::forward<T>(args)...);
}
template <class... T>
inline CSPAddTerm cspadd(CSPMulTerm &&mul, T&&... args) {
Location loc(String("dummy"), 1, 1, String("dummy"), 1, 1);
CSPAddTerm add(std::move(mul));
cspadd(add, std::forward<T>(args)...);
return add;
}
inline void csplit(CSPLiteral &) { }
template <class... T>
inline void csplit(CSPLiteral &lit, Relation rel, CSPAddTerm &&add, T&&... args) {
lit.append(rel, std::move(add));
csplit(lit, std::forward<T>(args)...);
}
template <class... T>
inline UCSPLit csplit(CSPAddTerm &&left, Relation rel, CSPAddTerm &&right, T&&... args) {
Location loc(String("dummy"), 1, 1, String("dummy"), 1, 1);
UCSPLit lit(make_locatable<CSPLiteral>(loc, rel, std::move(left), std::move(right)));
csplit(*lit, std::forward<T>(args)...);
return lit;
}
inline ULit pred(NAF naf, UTerm &&arg) {
Location loc(String("dummy"), 1, 1, String("dummy"), 1, 1);
return make_locatable<PredicateLiteral>(loc, naf, std::move(arg));
}
inline ULit rel(Relation rel, UTerm &&left, UTerm &&right) {
Location loc(String("dummy"), 1, 1, String("dummy"), 1, 1);
return make_locatable<RelationLiteral>(loc, rel, std::move(left), std::move(right));
}
inline ULit range(UTerm &&assign, UTerm &&lower, UTerm &&upper) {
Location loc(String("dummy"), 1, 1, String("dummy"), 1, 1);
return make_locatable<RangeLiteral>(loc, std::move(assign), std::move(lower), std::move(upper));
}
template <class... T>
ULitVec litvec(T&&... args) {
return init<ULitVec>(std::forward<T>(args)...);
}
// }}}
} } } // namespace Test Input Gringo
#endif // _GRINGO_TEST_LIT_HELPER_HH
| [
"kaminski@cs.uni-potsdam.de"
] | kaminski@cs.uni-potsdam.de |
0d8b47aed4fe1a0b0a884267b3d9c252eb8e5ccc | ce039e744725692b430e6a84cc42aae2ee9db22a | /appwidget.cpp | e6dfcd59a0ddfc6e4bf81e9f1eb33471bf0a6e3b | [] | no_license | fasa1964/fshkkap | adba0cd0e3ae5249833446d6d5c232835ded1ab6 | 2eacd2dfe1709f5073be2ef3f845a8328977b3c1 | refs/heads/master | 2023-02-17T09:11:30.723940 | 2021-01-20T05:52:05 | 2021-01-20T05:52:05 | 288,750,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 798 | cpp | #include "appwidget.h"
#include "ui_appwidget.h"
#include <QPainter>
#include <QPixmap>
#include <QImage>
AppWidget::AppWidget(const QString &NAME, const QString &VERSION, QWidget *parent) :
QWidget(parent),
ui(new Ui::AppWidget)
{
ui->setupUi(this);
ui->nameLabel->setText(NAME);
ui->versionLabel->setText("Version "+VERSION);
ui->iconLabel->setMaximumWidth(250);
ui->iconLabel->setMaximumHeight(250);
}
AppWidget::~AppWidget()
{
delete ui;
}
void AppWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawPixmap(0, 0, QPixmap(":/images/BackgroundApp.svg").scaled(size()));
ui->iconLabel->setMaximumWidth(ui->nameLabel->width());
ui->iconLabel->setMaximumHeight(ui->nameLabel->width());
QWidget::paintEvent(event);
}
| [
"fasa@nb-saberi.ad.bbs-bassgeige.eu"
] | fasa@nb-saberi.ad.bbs-bassgeige.eu |
623c952e2e122d93deb3d31436ac94cecc6c55fc | f492b8de57d5797e371f70a91d6fe2d88c6a42b1 | /test_dll.cpp | c394cc750cea840c3e28d2630e84e93961a4e4c4 | [] | no_license | Spirrwell/premake-codelite-bug | 4c564ae330d773b0f383b6a4fcb4f03029c5c8e9 | e3ec01908def76b39f54ed366116e2a2d0fdf6b8 | refs/heads/master | 2021-04-16T02:27:04.295405 | 2020-03-23T02:46:52 | 2020-03-23T02:46:52 | 249,319,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 69 | cpp | #include <iostream>
void DoThing()
{
std::cout << "do thing\n";
}
| [
"Spirrwell@gmail.com"
] | Spirrwell@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.