<commit_before>/******************************************************************
 *
 * Copyright 2015 Samsung Electronics 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 "simulator_manager.h"
#include "simulator_resource_factory.h"
#include "simulator_remote_resource_impl.h"
#include "simulator_utils.h"

SimulatorManager *SimulatorManager::getInstance()
{
    static SimulatorManager s_instance;
    return &s_instance;
}

SimulatorManager::SimulatorManager()
{
    OC::PlatformConfig conf
    {
        OC::ServiceType::InProc,
        OC::ModeType::Both,
        "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
        0,         // Uses randomly available port
        OC::QualityOfService::LowQos
    };

    OC::OCPlatform::Configure(conf);
}

std::shared_ptr<SimulatorResource> SimulatorManager::createResource(
    const std::string &configPath)
{
    VALIDATE_INPUT(configPath.empty(), "Empty path!")

    std::shared_ptr<SimulatorResource> resource;
    try
    {
        resource = SimulatorResourceFactory::getInstance()->createResource(configPath);
        if (!resource)
            throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
    }
    catch (RAML::RamlException &e)
    {
        throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
    }

    return resource;
}

std::vector<std::shared_ptr<SimulatorResource>> SimulatorManager::createResource(
            const std::string &configPath, unsigned int count)
{
    VALIDATE_INPUT(configPath.empty(), "Empty path!")
    VALIDATE_INPUT(!count, "Count is zero!")

    std::vector<std::shared_ptr<SimulatorResource>> resources;
    try
    {
        resources = SimulatorResourceFactory::getInstance()->createResource(configPath, count);
        if (!resources.size())
            throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
    }
    catch (RAML::RamlException &e)
    {
        throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
    }

    return resources;
}

std::shared_ptr<SimulatorSingleResource> SimulatorManager::createSingleResource(
    const std::string &name, const std::string &uri, const std::string &resourceType)
{
    VALIDATE_INPUT(name.empty(), "Empty resource name!")
    VALIDATE_INPUT(uri.empty(), "Empty URI!")
    VALIDATE_INPUT(resourceType.empty(), "Empty resource type!")

    return SimulatorResourceFactory::getInstance()->createSingleResource(name, uri, resourceType);
}

std::shared_ptr<SimulatorCollectionResource> SimulatorManager::createCollectionResource(
    const std::string &name, const std::string &uri, const std::string &resourceType)
{
    VALIDATE_INPUT(name.empty(), "Empty resource name!")
    VALIDATE_INPUT(uri.empty(), "Empty URI!")
    VALIDATE_INPUT(resourceType.empty(), "Empty resource type!")

    return SimulatorResourceFactory::getInstance()->createCollectionResource(name, uri, resourceType);
}

void SimulatorManager::findResource(ResourceFindCallback callback)
{
    VALIDATE_CALLBACK(callback)

    OC::FindCallback findCallback = std::bind(
                                        [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback)
    {
        if (!ocResource)
            return;

        callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource));
    }, std::placeholders::_1, callback);

    typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
                                          OCConnectivityType, OC::FindCallback);

    invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "",
                     OC_MULTICAST_DISCOVERY_URI, CT_DEFAULT, findCallback);
}

void SimulatorManager::findResource(const std::string &resourceType,
                                    ResourceFindCallback callback)
{
    VALIDATE_INPUT(resourceType.empty(), "Empty resource type!")
    VALIDATE_CALLBACK(callback)

    OC::FindCallback findCallback = std::bind(
                                        [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback)
    {
        if (!ocResource)
            return;

        callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource));
    }, std::placeholders::_1, callback);

    std::ostringstream query;
    query << OC_MULTICAST_DISCOVERY_URI << "?rt=" << resourceType;

    typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
                                          OCConnectivityType, OC::FindCallback);

    invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "", query.str(),
                     CT_DEFAULT, findCallback);
}

void SimulatorManager::getDeviceInfo(const std::string &host, DeviceInfoCallback callback)
{
    VALIDATE_CALLBACK(callback)

    OC::FindDeviceCallback deviceCallback = std::bind(
            [](const OC::OCRepresentation & rep, const std::string & hostUri, DeviceInfoCallback callback)
    {
        std::string deviceName = rep.getValue<std::string>("n");
        std::string deviceID = rep.getValue<std::string>("di");
        std::string deviceSpecVersion = rep.getValue<std::string>("lcv");
        std::string deviceDMV = rep.getValue<std::string>("dmv");

        DeviceInfo deviceInfo(deviceName, deviceID, deviceSpecVersion, deviceDMV);
        callback(hostUri, deviceInfo);
    }, std::placeholders::_1, host, callback);

    typedef OCStackResult (*GetDeviceInfo)(const std::string &, const std::string &,
                                           OCConnectivityType, OC::FindDeviceCallback);

    invokeocplatform(static_cast<GetDeviceInfo>(OC::OCPlatform::getDeviceInfo), host.c_str(),
                     "/oic/d", CT_DEFAULT, deviceCallback);
}

void SimulatorManager::setDeviceInfo(const std::string &deviceName)
{
    VALIDATE_INPUT(deviceName.empty(), "Empty resource type!")

    typedef OCStackResult (*RegisterDeviceInfo)(const OCDeviceInfo);

    OCDeviceInfo ocDeviceInfo;
    ocDeviceInfo.deviceName = const_cast<char *>(deviceName.c_str());
    invokeocplatform(static_cast<RegisterDeviceInfo>(OC::OCPlatform::registerDeviceInfo),
                     ocDeviceInfo);
}

void SimulatorManager::getPlatformInfo(const std::string &host, PlatformInfoCallback callback)
{
    VALIDATE_CALLBACK(callback)

    OC::FindPlatformCallback platformCallback = std::bind(
                [](const OC::OCRepresentation & rep, const std::string & hostUri, PlatformInfoCallback callback)
    {
        PlatformInfo platformInfo;
        platformInfo.setPlatformID(rep.getValue<std::string>("pi"));
        platformInfo.setPlatformVersion(rep.getValue<std::string>("mnpv"));
        platformInfo.setManufacturerName(rep.getValue<std::string>("mnmn"));
        platformInfo.setManufacturerUrl(rep.getValue<std::string>("mnml"));
        platformInfo.setModelNumber(rep.getValue<std::string>("mnmo"));
        platformInfo.setDateOfManfacture(rep.getValue<std::string>("mndt"));
        platformInfo.setOSVersion(rep.getValue<std::string>("mnos"));
        platformInfo.setHardwareVersion(rep.getValue<std::string>("mnhw"));
        platformInfo.setFirmwareVersion(rep.getValue<std::string>("mnfv"));
        platformInfo.setSupportUrl(rep.getValue<std::string>("mnsl"));
        platformInfo.setSystemTime(rep.getValue<std::string>("st"));

        callback(hostUri, platformInfo);
    }, std::placeholders::_1, host, callback);

    typedef OCStackResult (*GetPlatformInfo)(const std::string &, const std::string &,
            OCConnectivityType, OC::FindPlatformCallback);

    invokeocplatform(static_cast<GetPlatformInfo>(OC::OCPlatform::getPlatformInfo), host.c_str(),
                     "/oic/p", CT_DEFAULT, platformCallback);
}

void SimulatorManager::setPlatformInfo(PlatformInfo &platformInfo)
{
    OCPlatformInfo ocPlatformInfo;
    ocPlatformInfo.platformID = const_cast<char *>(platformInfo.getPlatformID().c_str());
    ocPlatformInfo.manufacturerName = const_cast<char *>(platformInfo.getManufacturerName().c_str());
    ocPlatformInfo.manufacturerUrl = const_cast<char *>(platformInfo.getManufacturerUrl().c_str());
    ocPlatformInfo.modelNumber = const_cast<char *>(platformInfo.getModelNumber().c_str());
    ocPlatformInfo.dateOfManufacture = const_cast<char *>(platformInfo.getDateOfManfacture().c_str());
    ocPlatformInfo.platformVersion = const_cast<char *>(platformInfo.getPlatformVersion().c_str());
    ocPlatformInfo.operatingSystemVersion = const_cast<char *>(platformInfo.getOSVersion().c_str());
    ocPlatformInfo.hardwareVersion = const_cast<char *>(platformInfo.getHardwareVersion().c_str());
    ocPlatformInfo.firmwareVersion = const_cast<char *>(platformInfo.getFirmwareVersion().c_str());
    ocPlatformInfo.supportUrl = const_cast<char *>(platformInfo.getSupportUrl().c_str());
    ocPlatformInfo.systemTime = const_cast<char *>(platformInfo.getSystemTime().c_str());

    typedef OCStackResult (*RegisterPlatformInfo)(const OCPlatformInfo);
    invokeocplatform(static_cast<RegisterPlatformInfo>(OC::OCPlatform::registerPlatformInfo),
                     ocPlatformInfo);
}

void SimulatorManager::setLogger(const std::shared_ptr<ILogger> &logger)
{
    simLogger().setCustomTarget(logger);
}

bool SimulatorManager::setConsoleLogger()
{
    return simLogger().setDefaultConsoleTarget();
}

bool SimulatorManager::setFileLogger(const std::string &path)
{
    return simLogger().setDefaultFileTarget(path);
}<commit_msg>Resolved simulator crash issue.<commit_after>/******************************************************************
 *
 * Copyright 2015 Samsung Electronics 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 "simulator_manager.h"
#include "simulator_resource_factory.h"
#include "simulator_remote_resource_impl.h"
#include "simulator_utils.h"

SimulatorManager *SimulatorManager::getInstance()
{
    static SimulatorManager s_instance;
    return &s_instance;
}

SimulatorManager::SimulatorManager()
{
    OC::PlatformConfig conf
    {
        OC::ServiceType::InProc,
        OC::ModeType::Both,
        "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
        0,         // Uses randomly available port
        OC::QualityOfService::LowQos
    };

    OC::OCPlatform::Configure(conf);
}

std::shared_ptr<SimulatorResource> SimulatorManager::createResource(
    const std::string &configPath)
{
    VALIDATE_INPUT(configPath.empty(), "Empty path!")

    std::shared_ptr<SimulatorResource> resource;
    try
    {
        resource = SimulatorResourceFactory::getInstance()->createResource(configPath);
        if (!resource)
            throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
    }
    catch (RAML::RamlException &e)
    {
        throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
    }

    return resource;
}

std::vector<std::shared_ptr<SimulatorResource>> SimulatorManager::createResource(
            const std::string &configPath, unsigned int count)
{
    VALIDATE_INPUT(configPath.empty(), "Empty path!")
    VALIDATE_INPUT(!count, "Count is zero!")

    std::vector<std::shared_ptr<SimulatorResource>> resources;
    try
    {
        resources = SimulatorResourceFactory::getInstance()->createResource(configPath, count);
        if (!resources.size())
            throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
    }
    catch (RAML::RamlException &e)
    {
        throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
    }

    return resources;
}

std::shared_ptr<SimulatorSingleResource> SimulatorManager::createSingleResource(
    const std::string &name, const std::string &uri, const std::string &resourceType)
{
    VALIDATE_INPUT(name.empty(), "Empty resource name!")
    VALIDATE_INPUT(uri.empty(), "Empty URI!")
    VALIDATE_INPUT(resourceType.empty(), "Empty resource type!")

    return SimulatorResourceFactory::getInstance()->createSingleResource(name, uri, resourceType);
}

std::shared_ptr<SimulatorCollectionResource> SimulatorManager::createCollectionResource(
    const std::string &name, const std::string &uri, const std::string &resourceType)
{
    VALIDATE_INPUT(name.empty(), "Empty resource name!")
    VALIDATE_INPUT(uri.empty(), "Empty URI!")
    VALIDATE_INPUT(resourceType.empty(), "Empty resource type!")

    return SimulatorResourceFactory::getInstance()->createCollectionResource(name, uri, resourceType);
}

void SimulatorManager::findResource(ResourceFindCallback callback)
{
    VALIDATE_CALLBACK(callback)

    OC::FindCallback findCallback = std::bind(
                                        [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback)
    {
        if (!ocResource)
            return;

        callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource));
    }, std::placeholders::_1, callback);

    typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
                                          OCConnectivityType, OC::FindCallback);

    invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "",
                     OC_MULTICAST_DISCOVERY_URI, CT_DEFAULT, findCallback);
}

void SimulatorManager::findResource(const std::string &resourceType,
                                    ResourceFindCallback callback)
{
    VALIDATE_INPUT(resourceType.empty(), "Empty resource type!")
    VALIDATE_CALLBACK(callback)

    OC::FindCallback findCallback = std::bind(
                                        [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback)
    {
        if (!ocResource)
            return;

        callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource));
    }, std::placeholders::_1, callback);

    std::ostringstream query;
    query << OC_MULTICAST_DISCOVERY_URI << "?rt=" << resourceType;

    typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
                                          OCConnectivityType, OC::FindCallback);

    invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "", query.str(),
                     CT_DEFAULT, findCallback);
}

void SimulatorManager::getDeviceInfo(const std::string &host, DeviceInfoCallback callback)
{
    VALIDATE_CALLBACK(callback)

    OC::FindDeviceCallback deviceCallback = std::bind(
            [](const OC::OCRepresentation & rep, const std::string & hostUri, DeviceInfoCallback callback)
    {
        std::string deviceName = rep.getValue<std::string>("n");
        std::string deviceID = rep.getValue<std::string>("di");
        std::string deviceSpecVersion = rep.getValue<std::string>("lcv");
        std::string deviceDMV = rep.getValue<std::string>("dmv");

        DeviceInfo deviceInfo(deviceName, deviceID, deviceSpecVersion, deviceDMV);
        callback(hostUri, deviceInfo);
    }, std::placeholders::_1, host, callback);

    typedef OCStackResult (*GetDeviceInfo)(const std::string &, const std::string &,
                                           OCConnectivityType, OC::FindDeviceCallback);

    invokeocplatform(static_cast<GetDeviceInfo>(OC::OCPlatform::getDeviceInfo), host.c_str(),
                     "/oic/d", CT_DEFAULT, deviceCallback);
}

void SimulatorManager::setDeviceInfo(const std::string &deviceName)
{
    VALIDATE_INPUT(deviceName.empty(), "Empty resource type!")

    typedef OCStackResult (*RegisterDeviceInfo)(const OCDeviceInfo);

    OCDeviceInfo ocDeviceInfo {nullptr, nullptr};
    ocDeviceInfo.deviceName = const_cast<char *>(deviceName.c_str());
    invokeocplatform(static_cast<RegisterDeviceInfo>(OC::OCPlatform::registerDeviceInfo),
                     ocDeviceInfo);
}

void SimulatorManager::getPlatformInfo(const std::string &host, PlatformInfoCallback callback)
{
    VALIDATE_CALLBACK(callback)

    OC::FindPlatformCallback platformCallback = std::bind(
                [](const OC::OCRepresentation & rep, const std::string & hostUri, PlatformInfoCallback callback)
    {
        PlatformInfo platformInfo;
        platformInfo.setPlatformID(rep.getValue<std::string>("pi"));
        platformInfo.setPlatformVersion(rep.getValue<std::string>("mnpv"));
        platformInfo.setManufacturerName(rep.getValue<std::string>("mnmn"));
        platformInfo.setManufacturerUrl(rep.getValue<std::string>("mnml"));
        platformInfo.setModelNumber(rep.getValue<std::string>("mnmo"));
        platformInfo.setDateOfManfacture(rep.getValue<std::string>("mndt"));
        platformInfo.setOSVersion(rep.getValue<std::string>("mnos"));
        platformInfo.setHardwareVersion(rep.getValue<std::string>("mnhw"));
        platformInfo.setFirmwareVersion(rep.getValue<std::string>("mnfv"));
        platformInfo.setSupportUrl(rep.getValue<std::string>("mnsl"));
        platformInfo.setSystemTime(rep.getValue<std::string>("st"));

        callback(hostUri, platformInfo);
    }, std::placeholders::_1, host, callback);

    typedef OCStackResult (*GetPlatformInfo)(const std::string &, const std::string &,
            OCConnectivityType, OC::FindPlatformCallback);

    invokeocplatform(static_cast<GetPlatformInfo>(OC::OCPlatform::getPlatformInfo), host.c_str(),
                     "/oic/p", CT_DEFAULT, platformCallback);
}

void SimulatorManager::setPlatformInfo(PlatformInfo &platformInfo)
{
    OCPlatformInfo ocPlatformInfo;
    ocPlatformInfo.platformID = const_cast<char *>(platformInfo.getPlatformID().c_str());
    ocPlatformInfo.manufacturerName = const_cast<char *>(platformInfo.getManufacturerName().c_str());
    ocPlatformInfo.manufacturerUrl = const_cast<char *>(platformInfo.getManufacturerUrl().c_str());
    ocPlatformInfo.modelNumber = const_cast<char *>(platformInfo.getModelNumber().c_str());
    ocPlatformInfo.dateOfManufacture = const_cast<char *>(platformInfo.getDateOfManfacture().c_str());
    ocPlatformInfo.platformVersion = const_cast<char *>(platformInfo.getPlatformVersion().c_str());
    ocPlatformInfo.operatingSystemVersion = const_cast<char *>(platformInfo.getOSVersion().c_str());
    ocPlatformInfo.hardwareVersion = const_cast<char *>(platformInfo.getHardwareVersion().c_str());
    ocPlatformInfo.firmwareVersion = const_cast<char *>(platformInfo.getFirmwareVersion().c_str());
    ocPlatformInfo.supportUrl = const_cast<char *>(platformInfo.getSupportUrl().c_str());
    ocPlatformInfo.systemTime = const_cast<char *>(platformInfo.getSystemTime().c_str());

    typedef OCStackResult (*RegisterPlatformInfo)(const OCPlatformInfo);
    invokeocplatform(static_cast<RegisterPlatformInfo>(OC::OCPlatform::registerPlatformInfo),
                     ocPlatformInfo);
}

void SimulatorManager::setLogger(const std::shared_ptr<ILogger> &logger)
{
    simLogger().setCustomTarget(logger);
}

bool SimulatorManager::setConsoleLogger()
{
    return simLogger().setDefaultConsoleTarget();
}

bool SimulatorManager::setFileLogger(const std::string &path)
{
    return simLogger().setDefaultFileTarget(path);
}<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include <utility>
#include <iosfwd>

#include <gmpxx.h>

// sam: this stuff should really be a class -- otherwise you have to understand
//      your implementation to use these functions without doing something you
//      do not want.
//      notably, you open a file and close it in different functions
//      maybe in the class version open in the constructor and close in the
//      destructor? (not totally sure that is good advice)
//      I've also left some comments in the cc
//      I also moved you to using std::blah, and removed all std:: from the file
//
// TODO:
//      - [ ] put in class (or atleast a namespace, these shouldn't be global)
//      - [ ] fix exceptions
//      - [ ] dedicate to either writing std or using std::blah, a mix is hard to
//            read
std::vector<std::pair<mpz_class, mpz_class>> findPrimeFactors(mpz_class n);

void generateNPrimes(long int n);

std::ifstream& skipToLine(std::ifstream& file, mpz_class num);

mpz_class getNthPrime(mpz_class n);

mpz_class getNextPrime(
    std::ifstream& prime_file,
    mpz_class n);  // this function is faster since you can hold onto your place
<commit_msg>clang formatted<commit_after>#pragma once

#include <vector>
#include <utility>
#include <iosfwd>

#include <gmpxx.h>

// sam: this stuff should really be a class -- otherwise you have to understand
//      your implementation to use these functions without doing something you
//      do not want.
//      notably, you open a file and close it in different functions
//      maybe in the class version open in the constructor and close in the
//      destructor? (not totally sure that is good advice)
//      I've also left some comments in the cc
//      I also moved you to using std::blah, and removed all std:: from the file
//
// TODO:
//      - [ ] put in class (or atleast a namespace, these shouldn't be global)
//      - [ ] fix exceptions
//      - [ ] dedicate to either writing std or using std::blah, a mix is hard
//      to
//            read
std::vector<std::pair<mpz_class, mpz_class>> findPrimeFactors(mpz_class n);

void generateNPrimes(long int n);

std::ifstream& skipToLine(std::ifstream& file, mpz_class num);

mpz_class getNthPrime(mpz_class n);

mpz_class getNextPrime(
    std::ifstream& prime_file,
    mpz_class n);  // this function is faster since you can hold onto your place
<|endoftext|>


<commit_before>#include<bits/stdc++.h>
#define MAXN 5001
#define MAXH 5001
#define INF 0x3f3f3f3f
using namespace std;

int N,H,R;
int rules[MAXN];
int DP[MAXN][MAXH];

int rec(int num_heads, int cur_health) {
    if(num_heads == 0) {
        return 0;
    }
    else if (DP[num_heads][cur_health] != INF){
        return DP[num_heads][cur_health];
    }
    else {
        // try defending
        int num_head_if_defend = rules[num_heads];
        int cur_health_if_defend  = cur_health-1;
        // avoid case where we constantly defend only to lose health, this is a lost battle anyway
        if(cur_health_if_defend > 0 && rules[num_heads] != num_heads) {
            DP[num_heads][cur_health] = min(DP[num_heads][cur_health], 1+rec(num_head_if_defend, cur_health_if_defend));
        }
        // try attacking
        int num_head_if_attack = rules[num_heads-1];
        int cur_health_if_attack = cur_health-num_heads;
        if(cur_health_if_attack > 0) {
            DP[num_heads][cur_health] = min(DP[num_heads][cur_health], 1+rec(num_head_if_attack, cur_health_if_attack));
        }
        if(DP[num_heads][cur_health] == INF)// i.e.e impossible
            DP[num_heads][cur_health] = INF+1;
        return DP[num_heads][cur_health];
    }
}

int main() {
    cin >> N >> H >> R;
    memset(DP, INF, sizeof(DP));
    for(int i = 0;i < MAXN;i++) {
        rules[i] = i;
    }
    for(int i = 0;i < R;i++) {
        int n_i, n_j;
        cin >> n_i >> n_j;
        rules[n_i] = n_j;
    }
    int ans = rec(N, H);
    if(ans >= INF)
        cout << "retreat" << endl;
    else
        cout << ans << endl;
    return 0;
}
<commit_msg>made solution more clear<commit_after>#include<bits/stdc++.h>
#define MAXN 5001
#define MAXH 5001
#define INF 0x3f3f3f3f
#define IMPOSSIBLE INF+1
using namespace std;

int N,H,R;
int rules[MAXN];
int DP[MAXN][MAXH];

int rec(int num_heads, int cur_health) {
    if(num_heads == 0) {
        return 0;
    }
    else if (DP[num_heads][cur_health] != INF){
        return DP[num_heads][cur_health];
    }
    else {
        // try defending
        int num_head_if_defend = rules[num_heads];
        int cur_health_if_defend  = cur_health-1;
        if(cur_health_if_defend > 0) {
            DP[num_heads][cur_health] = min(DP[num_heads][cur_health], 1+rec(num_head_if_defend, cur_health_if_defend));
        }
        // try attacking
        int num_head_if_attack = rules[num_heads-1];
        int cur_health_if_attack = cur_health-num_heads;
        if(cur_health_if_attack > 0) {
            DP[num_heads][cur_health] = min(DP[num_heads][cur_health], 1+rec(num_head_if_attack, cur_health_if_attack));
        }
        if(DP[num_heads][cur_health] == INF){ // we have attempted computing this state and it's impossible
            DP[num_heads][cur_health] = IMPOSSIBLE;
        }
        return DP[num_heads][cur_health];
    }
}

int main() {
    cin >> N >> H >> R;
    memset(DP, INF, sizeof(DP));
    for(int i = 0;i < MAXN;i++) {
        rules[i] = i;
    }
    for(int i = 0;i < R;i++) {
        int n_i, n_j;
        cin >> n_i >> n_j;
        rules[n_i] = n_j;
    }
    int ans = rec(N, H);
    if(ans == INF || ans == IMPOSSIBLE)
        cout << "retreat" << endl;
    else
        cout << ans << endl;
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>洛谷 T52793<commit_after><|endoftext|>


<commit_before>// Python includes
#include <Python.h>

// Stl includes
#include <fstream>

// Qt includes
#include <QResource>
#include <QMetaType>
#include <QFile>
#include <QDir>

// hyperion util includes
#include <utils/jsonschema/JsonSchemaChecker.h>
#include <utils/FileUtils.h>

// effect engine includes
#include <effectengine/EffectEngine.h>
#include "Effect.h"
#include "HyperionConfig.h"

EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectConfig)
	: _hyperion(hyperion)
	, _availableEffects()
	, _activeEffects()
	, _mainThreadState(nullptr)
	, _log(Logger::getInstance("EFFECTENGINE"))
{
	qRegisterMetaType<std::vector<ColorRgb>>("std::vector<ColorRgb>");

	// connect the Hyperion channel clear feedback
	connect(_hyperion, SIGNAL(channelCleared(int)), this, SLOT(channelCleared(int)));
	connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared()));

	// read all effects
	const Json::Value & paths = jsonEffectConfig["paths"];
	for (Json::UInt i = 0; i < paths.size(); ++i)
	{
		const std::string & path = paths[i].asString();
		QDir directory(QString::fromStdString(path));
		if (directory.exists())
		{
			int efxCount = 0;
			QStringList filenames = directory.entryList(QStringList() << "*.json", QDir::Files, QDir::Name | QDir::IgnoreCase);
			foreach (const QString & filename, filenames)
			{
				EffectDefinition def;
				if (loadEffectDefinition(path, filename.toStdString(), def))
				{
					_availableEffects.push_back(def);
					efxCount++;
				}
			}
			Info(_log, "%d effects loaded from directory %s", efxCount, path.c_str());
		}
	}

	if (_availableEffects.size() == 0)
	{
		Error(_log, "no effects found, check your effect directories");
	}

	// initialize the python interpreter
	Debug(_log,"Initializing Python interpreter");
    Effect::registerHyperionExtensionModule();
	Py_InitializeEx(0);
	PyEval_InitThreads(); // Create the GIL
	_mainThreadState = PyEval_SaveThread();
}

EffectEngine::~EffectEngine()
{
	// clean up the Python interpreter
	Debug(_log, "Cleaning up Python interpreter");
	PyEval_RestoreThread(_mainThreadState);
	Py_Finalize();
}

const std::list<EffectDefinition> &EffectEngine::getEffects() const
{
	return _availableEffects;
}

const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects()
{
	_availableActiveEffects.clear();

	for (Effect * effect : _activeEffects)
	{
		ActiveEffectDefinition activeEffectDefinition;
		activeEffectDefinition.script = effect->getScript();
		activeEffectDefinition.priority = effect->getPriority();
		activeEffectDefinition.timeout = effect->getTimeout();
		activeEffectDefinition.args = effect->getArgs();
		_availableActiveEffects.push_back(activeEffectDefinition);
	}

	return _availableActiveEffects;
}

bool EffectEngine::loadEffectDefinition(const std::string &path, const std::string &effectConfigFile, EffectDefinition & effectDefinition)
{
	std::string fileName = path + QDir::separator().toLatin1() + effectConfigFile;
	std::ifstream file(fileName.c_str());

	Logger * log = Logger::getInstance("EFFECTENGINE");
	if (!file.is_open())
	{
		Error( log, "Effect file '%s' could not be loaded", fileName.c_str());
		return false;
	}

	// Read the json config file
	Json::Reader jsonReader;
	Json::Value config;
	if (!jsonReader.parse(file, config, false))
	{
		Error( log, "Error while reading effect '%s': %s", fileName.c_str(), jsonReader.getFormattedErrorMessages().c_str());
		return false;
	}

	// Read the json schema file
	QResource schemaData(":effect-schema");
	JsonSchemaChecker schemaChecker;
	Json::Value schema;
	Json::Reader().parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schema, false);
	schemaChecker.setSchema(schema);
	if (!schemaChecker.validate(config))
	{
		const std::list<std::string> & errors = schemaChecker.getMessages();
		foreach (const std::string & error, errors) {
			Error( log, "Error while checking '%s':%s", fileName.c_str(), error.c_str());
		}
		return false;
	}

	// setup the definition
	effectDefinition.name = config["name"].asString();
	effectDefinition.script = path + QDir::separator().toLatin1() + config["script"].asString();
	effectDefinition.args = config["args"];

	return true;
}

int EffectEngine::runEffect(const std::string &effectName, int priority, int timeout)
{
	return runEffect(effectName, Json::Value(Json::nullValue), priority, timeout);
}

int EffectEngine::runEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout)
{
	Info( _log, "run effect %s on channel %d", effectName.c_str(), priority);

	const EffectDefinition * effectDefinition = nullptr;
	for (const EffectDefinition & e : _availableEffects)
	{
		if (e.name == effectName)
		{
			effectDefinition = &e;
			break;
		}
	}
	if (effectDefinition == nullptr)
	{
		// no such effect
		Error(_log, "effect %s not found",  effectName.c_str());
		return -1;
	}

	return runEffectScript(effectDefinition->script, args.isNull() ? effectDefinition->args : args, priority, timeout);
}

int EffectEngine::runEffectScript(const std::string &script, const Json::Value &args, int priority, int timeout)
{
	// clear current effect on the channel
	channelCleared(priority);

	// create the effect
    Effect * effect = new Effect(_mainThreadState, priority, timeout, script, args);
	connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool)), Qt::QueuedConnection);
	connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*)));
	_activeEffects.push_back(effect);

	// start the effect
	_hyperion->registerPriority("EFFECT: "+FileUtils::getBaseName(script), priority);
	effect->start();

	return 0;
}

void EffectEngine::channelCleared(int priority)
{
	for (Effect * effect : _activeEffects)
	{
		if (effect->getPriority() == priority)
		{
			effect->abort();
		}
	}
}

void EffectEngine::allChannelsCleared()
{
	for (Effect * effect : _activeEffects)
	{
		effect->abort();
	}
}

void EffectEngine::effectFinished(Effect *effect)
{
	if (!effect->isAbortRequested())
	{
		// effect stopped by itself. Clear the channel
		_hyperion->clear(effect->getPriority());
	}

	Info( _log, "effect finished");
	for (auto effectIt = _activeEffects.begin(); effectIt != _activeEffects.end(); ++effectIt)
	{
		if (*effectIt == effect)
		{
			_activeEffects.erase(effectIt);
			break;
		}
	}

	// cleanup the effect
	effect->deleteLater();
	_hyperion->unRegisterPriority("EFFECT: " + effect->getScript());
}
<commit_msg>fix effect prio unregister<commit_after>// Python includes
#include <Python.h>

// Stl includes
#include <fstream>

// Qt includes
#include <QResource>
#include <QMetaType>
#include <QFile>
#include <QDir>

// hyperion util includes
#include <utils/jsonschema/JsonSchemaChecker.h>
#include <utils/FileUtils.h>

// effect engine includes
#include <effectengine/EffectEngine.h>
#include "Effect.h"
#include "HyperionConfig.h"

EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectConfig)
	: _hyperion(hyperion)
	, _availableEffects()
	, _activeEffects()
	, _mainThreadState(nullptr)
	, _log(Logger::getInstance("EFFECTENGINE"))
{
	qRegisterMetaType<std::vector<ColorRgb>>("std::vector<ColorRgb>");

	// connect the Hyperion channel clear feedback
	connect(_hyperion, SIGNAL(channelCleared(int)), this, SLOT(channelCleared(int)));
	connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared()));

	// read all effects
	const Json::Value & paths = jsonEffectConfig["paths"];
	for (Json::UInt i = 0; i < paths.size(); ++i)
	{
		const std::string & path = paths[i].asString();
		QDir directory(QString::fromStdString(path));
		if (directory.exists())
		{
			int efxCount = 0;
			QStringList filenames = directory.entryList(QStringList() << "*.json", QDir::Files, QDir::Name | QDir::IgnoreCase);
			foreach (const QString & filename, filenames)
			{
				EffectDefinition def;
				if (loadEffectDefinition(path, filename.toStdString(), def))
				{
					_availableEffects.push_back(def);
					efxCount++;
				}
			}
			Info(_log, "%d effects loaded from directory %s", efxCount, path.c_str());
		}
	}

	if (_availableEffects.size() == 0)
	{
		Error(_log, "no effects found, check your effect directories");
	}

	// initialize the python interpreter
	Debug(_log,"Initializing Python interpreter");
    Effect::registerHyperionExtensionModule();
	Py_InitializeEx(0);
	PyEval_InitThreads(); // Create the GIL
	_mainThreadState = PyEval_SaveThread();
}

EffectEngine::~EffectEngine()
{
	// clean up the Python interpreter
	Debug(_log, "Cleaning up Python interpreter");
	PyEval_RestoreThread(_mainThreadState);
	Py_Finalize();
}

const std::list<EffectDefinition> &EffectEngine::getEffects() const
{
	return _availableEffects;
}

const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects()
{
	_availableActiveEffects.clear();

	for (Effect * effect : _activeEffects)
	{
		ActiveEffectDefinition activeEffectDefinition;
		activeEffectDefinition.script = effect->getScript();
		activeEffectDefinition.priority = effect->getPriority();
		activeEffectDefinition.timeout = effect->getTimeout();
		activeEffectDefinition.args = effect->getArgs();
		_availableActiveEffects.push_back(activeEffectDefinition);
	}

	return _availableActiveEffects;
}

bool EffectEngine::loadEffectDefinition(const std::string &path, const std::string &effectConfigFile, EffectDefinition & effectDefinition)
{
	std::string fileName = path + QDir::separator().toLatin1() + effectConfigFile;
	std::ifstream file(fileName.c_str());

	Logger * log = Logger::getInstance("EFFECTENGINE");
	if (!file.is_open())
	{
		Error( log, "Effect file '%s' could not be loaded", fileName.c_str());
		return false;
	}

	// Read the json config file
	Json::Reader jsonReader;
	Json::Value config;
	if (!jsonReader.parse(file, config, false))
	{
		Error( log, "Error while reading effect '%s': %s", fileName.c_str(), jsonReader.getFormattedErrorMessages().c_str());
		return false;
	}

	// Read the json schema file
	QResource schemaData(":effect-schema");
	JsonSchemaChecker schemaChecker;
	Json::Value schema;
	Json::Reader().parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schema, false);
	schemaChecker.setSchema(schema);
	if (!schemaChecker.validate(config))
	{
		const std::list<std::string> & errors = schemaChecker.getMessages();
		foreach (const std::string & error, errors) {
			Error( log, "Error while checking '%s':%s", fileName.c_str(), error.c_str());
		}
		return false;
	}

	// setup the definition
	effectDefinition.name = config["name"].asString();
	effectDefinition.script = path + QDir::separator().toLatin1() + config["script"].asString();
	effectDefinition.args = config["args"];

	return true;
}

int EffectEngine::runEffect(const std::string &effectName, int priority, int timeout)
{
	return runEffect(effectName, Json::Value(Json::nullValue), priority, timeout);
}

int EffectEngine::runEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout)
{
	Info( _log, "run effect %s on channel %d", effectName.c_str(), priority);

	const EffectDefinition * effectDefinition = nullptr;
	for (const EffectDefinition & e : _availableEffects)
	{
		if (e.name == effectName)
		{
			effectDefinition = &e;
			break;
		}
	}
	if (effectDefinition == nullptr)
	{
		// no such effect
		Error(_log, "effect %s not found",  effectName.c_str());
		return -1;
	}

	return runEffectScript(effectDefinition->script, args.isNull() ? effectDefinition->args : args, priority, timeout);
}

int EffectEngine::runEffectScript(const std::string &script, const Json::Value &args, int priority, int timeout)
{
	// clear current effect on the channel
	channelCleared(priority);

	// create the effect
    Effect * effect = new Effect(_mainThreadState, priority, timeout, script, args);
	connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool)), Qt::QueuedConnection);
	connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*)));
	_activeEffects.push_back(effect);

	// start the effect
	_hyperion->registerPriority("EFFECT: "+FileUtils::getBaseName(script), priority);
	effect->start();

	return 0;
}

void EffectEngine::channelCleared(int priority)
{
	for (Effect * effect : _activeEffects)
	{
		if (effect->getPriority() == priority)
		{
			effect->abort();
		}
	}
}

void EffectEngine::allChannelsCleared()
{
	for (Effect * effect : _activeEffects)
	{
		effect->abort();
	}
}

void EffectEngine::effectFinished(Effect *effect)
{
	if (!effect->isAbortRequested())
	{
		// effect stopped by itself. Clear the channel
		_hyperion->clear(effect->getPriority());
	}

	Info( _log, "effect finished");
	for (auto effectIt = _activeEffects.begin(); effectIt != _activeEffects.end(); ++effectIt)
	{
		if (*effectIt == effect)
		{
			_activeEffects.erase(effectIt);
			break;
		}
	}

	// cleanup the effect
	effect->deleteLater();
	_hyperion->unRegisterPriority("EFFECT: " + FileUtils::getBaseName(effect->getScript()));
}
<|endoftext|>


<commit_before>// Quick benchmark comparison of inlined 4-element sorting network
// vs std::sort.
// compile with: g++ --std=c++11 -O3 sort_compare.cc -o sort_compare
// Copyright (C) 2016 David G. Andersen.
// Apache licensed, see LICENSE file.

#include <sys/types.h>
#include <sys/time.h>
#include <inttypes.h>
#include <stdio.h>
#include <algorithm>
#include <iterator>

constexpr int WARMUP_ITERS = 1000;
constexpr int EVAL_ITERS = 200000000;
constexpr int NUM_TAGS = 4;

// Benchmark function 1 - the inlined version.  Note that both
// benchmark functions return the value of the last tag;  we use
// this to discourage the compiler from optimizing away all of this
// useless work.

inline void SortPair(uint32_t& a, uint32_t& b) {
  if ((a & 0x0f) > (b & 0x0f)) {
    std::swap(a, b);
  }
}

inline int32_t SortTags(uint32_t tags[4]) {
  SortPair(tags[0], tags[2]);
  SortPair(tags[1], tags[3]);
  SortPair(tags[0], tags[1]);
  SortPair(tags[2], tags[3]);
  SortPair(tags[1], tags[2]);
  return tags[3];
}

// STL version.
inline int32_t STLSortTags(uint32_t (&tags)[4]) {
  std::sort(std::begin(tags), std::end(tags), [](uint32_t a, uint32_t b) {
      return (a & 0xf) < (b & 0xf);
    });
  return tags[3];
}

// Quick hack LCRNG to seed tags.  We seed the tags randomly each
// time so that the benchmark isn't getting excess benefit from
// the branch predictor, which might change the results.  This
// isn't designed to be strong, it's designed to be fast and
// just good enough that the compiler doesn't invalidate our results.
uint64_t state = 1234567u;

inline void randomizeTags(uint32_t tags[NUM_TAGS]) {
  uint64_t old = state;
  tags[0] = state >> 4;
  tags[1] = state >> 16;
  tags[2] = state >> 24;
  tags[3] = state >> 32;
  state = state * 6364136223846793005ULL + 7;
}

void print_timing(const struct timeval *tv_start, const struct timeval *tv_end,
		  const char *name, int32_t sum) {
  int64_t usec = (tv_end->tv_sec - tv_start->tv_sec) * 1000000 +
    (tv_end->tv_usec - tv_start->tv_usec);
  float sec = (float)usec/1000000.0;
  printf("%s : %.2f seconds\n", name, sec);
  if (sum == 0) {
    printf("Hey, neat coincidence, sum is zero\n");
  }
}

#define BENCHMARK(f, name) do { \
  struct timeval tv_start, tv_end;	   \
  int32_t sum = 0;			   \
  for (int i = 0; i < WARMUP_ITERS; i++) { \
    randomizeTags(tags);		   \
    f;					   \
  }					   \
  gettimeofday(&tv_start, NULL);	   \
  for (int i = 0; i < EVAL_ITERS; i++) {   \
    randomizeTags(tags);		   \
    sum += f;				   \
  }					   \
  gettimeofday(&tv_end, NULL);		   \
  print_timing(&tv_start, &tv_end, name, sum); \
  } while(0)

int main() {
  uint32_t tags[4];

  BENCHMARK(SortTags(tags), "fully inlined");
  BENCHMARK(STLSortTags(tags), "STL sort");
}
<commit_msg>Bit more cleanup<commit_after>// Quick benchmark comparison of inlined 4-element sorting network
// vs std::sort.
// compile with: g++ --std=c++11 -O3 sort_compare.cc -o sort_compare
// Copyright (C) 2016 David G. Andersen.
// Apache licensed, see LICENSE file.

#include <sys/types.h>
#include <sys/time.h>
#include <inttypes.h>
#include <stdio.h>
#include <algorithm>
#include <iterator>

constexpr int WARMUP_ITERS = 2000;
constexpr int EVAL_ITERS = 200000000;
constexpr int NUM_TAGS = 4;

// Benchmark function 1 - the inlined version.  Note that both
// benchmark functions return the value of the last tag;  we use
// this to discourage the compiler from optimizing away all of this
// useless work.

inline void SortPair(uint32_t& a, uint32_t& b) {
  if ((a & 0x0f) > (b & 0x0f)) {
    std::swap(a, b);
  }
}

inline int32_t SortTags(uint32_t tags[4]) {
  SortPair(tags[0], tags[2]);
  SortPair(tags[1], tags[3]);
  SortPair(tags[0], tags[1]);
  SortPair(tags[2], tags[3]);
  SortPair(tags[1], tags[2]);
  return tags[3];
}

// STL version.
inline int32_t STLSortTags(uint32_t (&tags)[4]) {
  std::sort(std::begin(tags), std::end(tags), [](uint32_t a, uint32_t b) {
      return (a & 0xf) < (b & 0xf);
    });
  return tags[3];
}

// Quick hack LCRNG to seed tags.  We seed the tags randomly each
// time so that the benchmark isn't getting excess benefit from
// the branch predictor, which might change the results.  This
// isn't designed to be strong, it's designed to be fast and
// just good enough that the compiler doesn't invalidate our results.
uint64_t state = 1234567u;

inline void randomizeTags(uint32_t tags[NUM_TAGS]) {
  tags[0] = state >> 4;
  tags[1] = state >> 16;
  tags[2] = state >> 24;
  tags[3] = state >> 32;
  state = state * 6364136223846793005ULL + 7;
}

void print_timing(const struct timeval *tv_start, const struct timeval *tv_end,
		  const char *name, int32_t sum) {
  int64_t usec = (tv_end->tv_sec - tv_start->tv_sec) * 1000000 +
    (tv_end->tv_usec - tv_start->tv_usec);
  float sec = (float)usec/1000000.0;
  printf("%s : %.2f seconds\n", name, sec);
  if (sum == 0) {
    printf("Hey, neat coincidence, sum is zero\n");
  }
}

#define BENCHMARK(f, name) do { \
  struct timeval tv_start, tv_end;	   \
  int32_t sum = 0;			   \
  for (int i = 0; i < WARMUP_ITERS; i++) { \
    randomizeTags(tags);		   \
    f;					   \
  }					   \
  gettimeofday(&tv_start, NULL);	   \
  for (int i = 0; i < EVAL_ITERS; i++) {   \
    randomizeTags(tags);		   \
    sum += f;				   \
  }					   \
  gettimeofday(&tv_end, NULL);		   \
  print_timing(&tv_start, &tv_end, name, sum); \
  } while(0)

int main() {
  uint32_t tags[4];

  BENCHMARK(SortTags(tags), "fully inlined");
  BENCHMARK(STLSortTags(tags), "STL sort");
}
<|endoftext|>


<commit_before>#include <3ds.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include "file.h"
#include "display.h"
#include "file_io.h"

#define BUFFER_SIZE 60
#define MAX_BOTTOM_SIZE 28

#define VERSION "Notepad3DS Version 1.0"

PrintConsole topScreen, bottomScreen;
int scroll = 0;
bool fast_scroll = false;

void move_down(File file);
void move_up(File file);

unsigned int curr_line = 0;

int main(int argc, char **argv)
{
	gfxInitDefault();
	consoleInit(GFX_TOP, &topScreen);
    consoleInit(GFX_BOTTOM, &bottomScreen);
    consoleSelect(&bottomScreen);
    //Software keyboard thanks to fincs
    print_instructions();

    print_version(VERSION);

    File file;      //Use as default file

    update_screen(file, curr_line);

	while (aptMainLoop())
	{

		hidScanInput();

		u32 kDown = hidKeysDown();
        u32 kHeld = hidKeysHeld();

		if (kDown & KEY_START)
			break;

		static SwkbdState swkbd;
		static char mybuf[BUFFER_SIZE];
		SwkbdButton button = SWKBD_BUTTON_NONE;
		bool didit = false;

        swkbdInit(&swkbd, SWKBD_TYPE_NORMAL, 1, -1);
        swkbdSetValidation(&swkbd, SWKBD_ANYTHING, SWKBD_FILTER_DIGITS | SWKBD_FILTER_AT | SWKBD_FILTER_PERCENT /*| SWKBD_FILTER_BACKSLASH*/ | SWKBD_FILTER_PROFANITY, 2);
        swkbdSetFeatures(&swkbd, SWKBD_MULTILINE);

        if (kDown & KEY_A) {
            //Select current line for editing
            swkbdSetHintText(&swkbd, "Input text here.");
            //Iterator to find current selected line
            auto line = file.lines.begin();
            if (curr_line < file.lines.size())
            {
                if (curr_line != 0)
                    advance(line, curr_line);

                if (curr_line == file.lines.size() - 1) {
                    file.lines.push_back(std::vector<char>{'\n'});
                }
                //Need a char array to output to keyboard
                char current_text[BUFFER_SIZE] = "";
                copy(line->begin(), line->end(), current_text);
                swkbdSetInitialText(&swkbd, current_text);
            }
            didit = true;
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
        }

        if (kDown & KEY_B) {
            //Create new file

            //Clear buffer
            memset(mybuf, '\0', BUFFER_SIZE);
            //Confirm creating a new file
            swkbdSetHintText(&swkbd, "Are you sure you want to open a BLANK file? y/n");
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
            if (mybuf[0] == 'y') {
                File blankFile;
                file = blankFile;
                curr_line = 0;
                scroll = 0;
                update_screen(file, curr_line);
                print_save_status("New file created");
            } else
                print_save_status("No new file created");
        }

        if (kDown & KEY_R) {
            //find a thing

            //Clear buffer
            memset(mybuf, '\0', BUFFER_SIZE);
            //Get term to search for
            swkbdSetHintText(&swkbd, "Input search term here.");
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
            int line = file.find(mybuf);
            if (line < 0)
                printf("Could not find %s", mybuf);
            else {
                printf("Found %s at %d", mybuf, line);
                curr_line = line;
                if (curr_line > MAX_BOTTOM_SIZE) {
                    scroll = curr_line - MAX_BOTTOM_SIZE;
                }
                update_screen(file, curr_line);
            }

        }

        if (kHeld & KEY_L) {
            //If held, allows for jumping to end and start of file
            fast_scroll = true;
        } else {
            fast_scroll = false;
        }

        if (kDown & KEY_X) {
            //Save current file
            //Clear buffer
            memset(mybuf, '\0', BUFFER_SIZE);

            //Get file name

            swkbdSetHintText(&swkbd, "Input filename here.");
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
            std::string filename = "";
            for (int i = 0; mybuf[i] != '\0'; i++)
                filename.push_back(mybuf[i]);

            //Write out characters to file
            bool success = write_to_file(filename, file);

            if (success) {
                print_save_status("File written to " + filename);
                print_directory_status(filename);
            } else {
                print_save_status("Failed to write " + filename);
            }

        }

        if (kDown & KEY_Y) {
            //Similar code to pressing X, see about refactoring
            //Open a file
            curr_line = 0;
            scroll = 0;
            //Clear buffer
            memset(mybuf, '\0', BUFFER_SIZE);

            //Get file name

            swkbdSetHintText(&swkbd, "Input filename here.");
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
            std::string filename = "";
            for (int i = 0; mybuf[i] != '\0'; i++)
                filename.push_back(mybuf[i]);
            File oldfile = file;
            file = open_file(filename);

            //print functions here seem to crash the program
            if (file.read_success) {
                update_screen(file, curr_line);
                clear_save_status();
                std::cout << "Successfully opened " << filename << std::endl;
                clear_directory_status();
                std::cout << "Current file: " << filename;
                //print_directory_status(filename);
                consoleSelect(&topScreen);
                //print_save_status("Successfully opened " + filename);
            } else {
                file = oldfile;
                update_screen(file, curr_line);
                clear_save_status();
                std::cout << "Failed to open " << filename << std::endl;
                consoleSelect(&topScreen);
                //print_save_status("Failed to open " + filename);
            }
        }

        if (kDown & KEY_DDOWN) {
            //Move a line down (towards bottom of screen)
            move_down(file);
        }

        if (kHeld & KEY_CPAD_DOWN) {
            //Move a line down (towards bottom of screen)
            //as long as down is held
            move_down(file);
        }
        if (kDown & KEY_DUP) {
            //Move a line up (towards top of screen)
            move_up(file);
        }

        if (kHeld & KEY_CPAD_UP) {
            //Move a line up (towards top of screen)
            //as long as up is held
            move_up(file);
        }

		if (didit)
		{
			if (button != SWKBD_BUTTON_NONE)
			{
                std::vector<char> new_text = char_arr_to_vector(mybuf);

                if (curr_line >= file.lines.size()) {
                    //Empty line, add a new one.
                    file.add_line(new_text);
                } else {
                    file.edit_line(new_text, curr_line);
                }
                update_screen(file, curr_line);
			} else
				printf("swkbd event: %d\n", swkbdGetResult(&swkbd));
		}

		// Flush and swap framebuffers
		gfxFlushBuffers();
		gfxSwapBuffers();

		gspWaitForVBlank();
	}

	gfxExit();
	return 0;
}

void move_down(File file) {
    //Move a line down (towards bottom of screen)
    if (curr_line < file.lines.size() - 1) {
        if (fast_scroll) {
            curr_line = file.lines.size()-1;
            scroll = curr_line - MAX_BOTTOM_SIZE;

        } else {

            if ( (curr_line - scroll >= MAX_BOTTOM_SIZE) && (curr_line < file.lines.size() ) ) {
                scroll++;
                curr_line++;
            } else {
                curr_line++;
            }
        }
    }

    update_screen(file, curr_line);
}

void move_up(File file) {
    //Move a line up (towards top of screen)

    if (curr_line != 0) {
        if (fast_scroll) {
            //Jump to the top
            curr_line = 0;
            scroll = 0;

        } else {

            curr_line--;
            if (curr_line - scroll <= 0 && scroll != 0) {
                scroll--;
            }
        }
        update_screen(file, curr_line);
    }
}
<commit_msg>Removed keyboard filtering<commit_after>#include <3ds.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include "file.h"
#include "display.h"
#include "file_io.h"

#define BUFFER_SIZE 60
#define MAX_BOTTOM_SIZE 28

#define VERSION "Notepad3DS Version 1.0"

PrintConsole topScreen, bottomScreen;
int scroll = 0;
bool fast_scroll = false;

void move_down(File file);
void move_up(File file);

unsigned int curr_line = 0;

int main(int argc, char **argv)
{
	gfxInitDefault();
	consoleInit(GFX_TOP, &topScreen);
    consoleInit(GFX_BOTTOM, &bottomScreen);
    consoleSelect(&bottomScreen);
    //Software keyboard thanks to fincs
    print_instructions();

    print_version(VERSION);

    File file;      //Use as default file

    update_screen(file, curr_line);

	while (aptMainLoop())
	{

		hidScanInput();

		u32 kDown = hidKeysDown();
        u32 kHeld = hidKeysHeld();

		if (kDown & KEY_START)
			break;

		static SwkbdState swkbd;
		static char mybuf[BUFFER_SIZE];
		SwkbdButton button = SWKBD_BUTTON_NONE;
		bool didit = false;

        swkbdInit(&swkbd, SWKBD_TYPE_NORMAL, 1, -1);
        swkbdSetValidation(&swkbd, SWKBD_ANYTHING, SWKBD_ANYTHING, 2);
        swkbdSetFeatures(&swkbd, SWKBD_DARKEN_TOP_SCREEN);

        if (kDown & KEY_A) {
            //Select current line for editing
            swkbdSetHintText(&swkbd, "Input text here.");
            //Iterator to find current selected line
            auto line = file.lines.begin();
            if (curr_line < file.lines.size())
            {
                if (curr_line != 0)
                    advance(line, curr_line);

                if (curr_line == file.lines.size() - 1) {
                    file.lines.push_back(std::vector<char>{'\n'});
                }
                //Need a char array to output to keyboard
                char current_text[BUFFER_SIZE] = "";
                copy(line->begin(), line->end(), current_text);
                swkbdSetInitialText(&swkbd, current_text);
            }
            didit = true;
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
        }

        if (kDown & KEY_B) {
            //Create new file

            //Clear buffer
            memset(mybuf, '\0', BUFFER_SIZE);
            //Confirm creating a new file
            swkbdSetHintText(&swkbd, "Are you sure you want to open a BLANK file? y/n");
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
            if (mybuf[0] == 'y') {
                File blankFile;
                file = blankFile;
                curr_line = 0;
                scroll = 0;
                update_screen(file, curr_line);
                print_save_status("New file created");
            } else
                print_save_status("No new file created");
        }

        if (kDown & KEY_R) {
            //find a thing

            //Clear buffer
            memset(mybuf, '\0', BUFFER_SIZE);
            //Get term to search for
            swkbdSetHintText(&swkbd, "Input search term here.");
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
            int line = file.find(mybuf);
            if (line < 0)
                printf("Could not find %s", mybuf);
            else {
                printf("Found %s at %d", mybuf, line);
                curr_line = line;
                if (curr_line > MAX_BOTTOM_SIZE) {
                    scroll = curr_line - MAX_BOTTOM_SIZE;
                }
                update_screen(file, curr_line);
            }

        }

        if (kHeld & KEY_L) {
            //If held, allows for jumping to end and start of file
            fast_scroll = true;
        } else {
            fast_scroll = false;
        }

        if (kDown & KEY_X) {
            //Save current file
            //Clear buffer
            memset(mybuf, '\0', BUFFER_SIZE);

            //Get file name

            swkbdSetHintText(&swkbd, "Input filename here.");
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
            std::string filename = "";
            for (int i = 0; mybuf[i] != '\0'; i++)
                filename.push_back(mybuf[i]);

            //Write out characters to file
            bool success = write_to_file(filename, file);

            if (success) {
                print_save_status("File written to " + filename);
                print_directory_status(filename);
            } else {
                print_save_status("Failed to write " + filename);
            }

        }

        if (kDown & KEY_Y) {
            //Similar code to pressing X, see about refactoring
            //Open a file
            curr_line = 0;
            scroll = 0;
            //Clear buffer
            memset(mybuf, '\0', BUFFER_SIZE);

            //Get file name

            swkbdSetHintText(&swkbd, "Input filename here.");
            button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf));
            std::string filename = "";
            for (int i = 0; mybuf[i] != '\0'; i++)
                filename.push_back(mybuf[i]);
            File oldfile = file;
            file = open_file(filename);

            //print functions here seem to crash the program
            if (file.read_success) {
                update_screen(file, curr_line);
                clear_save_status();
                std::cout << "Successfully opened " << filename << std::endl;
                clear_directory_status();
                std::cout << "Current file: " << filename;
                //print_directory_status(filename);
                consoleSelect(&topScreen);
                //print_save_status("Successfully opened " + filename);
            } else {
                file = oldfile;
                update_screen(file, curr_line);
                clear_save_status();
                std::cout << "Failed to open " << filename << std::endl;
                consoleSelect(&topScreen);
                //print_save_status("Failed to open " + filename);
            }
        }

        if (kDown & KEY_DDOWN) {
            //Move a line down (towards bottom of screen)
            move_down(file);
        }

        if (kHeld & KEY_CPAD_DOWN) {
            //Move a line down (towards bottom of screen)
            //as long as down is held
            move_down(file);
        }
        if (kDown & KEY_DUP) {
            //Move a line up (towards top of screen)
            move_up(file);
        }

        if (kHeld & KEY_CPAD_UP) {
            //Move a line up (towards top of screen)
            //as long as up is held
            move_up(file);
        }

		if (didit)
		{
			if (button != SWKBD_BUTTON_NONE)
			{
                std::vector<char> new_text = char_arr_to_vector(mybuf);

                if (curr_line >= file.lines.size()) {
                    //Empty line, add a new one.
                    file.add_line(new_text);
                } else {
                    file.edit_line(new_text, curr_line);
                }
                update_screen(file, curr_line);
			} else
				printf("swkbd event: %d\n", swkbdGetResult(&swkbd));
		}

		// Flush and swap framebuffers
		gfxFlushBuffers();
		gfxSwapBuffers();

		gspWaitForVBlank();
	}

	gfxExit();
	return 0;
}

void move_down(File file) {
    //Move a line down (towards bottom of screen)
    if (curr_line < file.lines.size() - 1) {
        if (fast_scroll) {
            curr_line = file.lines.size()-1;
            scroll = curr_line - MAX_BOTTOM_SIZE;

        } else {

            if ( (curr_line - scroll >= MAX_BOTTOM_SIZE) && (curr_line < file.lines.size() ) ) {
                scroll++;
                curr_line++;
            } else {
                curr_line++;
            }
        }
    }

    update_screen(file, curr_line);
}

void move_up(File file) {
    //Move a line up (towards top of screen)

    if (curr_line != 0) {
        if (fast_scroll) {
            //Jump to the top
            curr_line = 0;
            scroll = 0;

        } else {

            curr_line--;
            if (curr_line - scroll <= 0 && scroll != 0) {
                scroll--;
            }
        }
        update_screen(file, curr_line);
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <stdexcept>
#include <vector>

#ifdef DURATION
    #include <chrono>
#endif

#include "version.h"
#include "Histogram.h"
#include "thresholding/OtsuMethod.h"
#include "thresholding/BalancedHistogramMethod.h"
#include "thresholding/IterativeMethod.h"
#include "thresholding/AdaptiveGaussMethod.h"
#include "thresholding/AdaptiveMeanCMethod.h"

using namespace std;
using namespace thresholding;

struct arguments {
    string inputPath;
    string outputPath;
    int method;
    int value;
    bool halfThresholding;

    arguments() : value(-1), halfThresholding(false)
    {}

    void print() {
        cout << "inputPath:  " << inputPath << endl <<
                "outputPath: " << outputPath << endl <<
                "method:     " << method << endl <<
                "value:      " << value << endl;
    }

    string getOutput(const string &methodName = "") {
        return outputPath + methodName + ".png";
    }
};

enum argsPosition {
    name = 0,
    method,
    inputImage,
    outputImage,
};

enum thresholdingOption {
    otsu = 0,
    adaptiveGauss,
    adaptiveMeanC,
    balanced,
    iterative,
    manual,
    all, //must be last
};

enum errorCode {
    noError = 0,
    invalidArguments,
};

map<string, int> thresholdingArgs({{"--otsu", thresholdingOption::otsu},
        {"--balanced", thresholdingOption::balanced},
        {"--adaptiveGauss", thresholdingOption::adaptiveGauss},
        {"--adaptiveMeanC", thresholdingOption::adaptiveMeanC},
        {"--iterative", thresholdingOption::iterative},
        {"--manual=", thresholdingOption::manual},
        {"--all", thresholdingOption::all}});

void printHelp()
{
    cout << "Help for cleanCppApplication " << endl;
    cout << "Version: " << Version::getVersionLong() << endl;
    cout << "Author:  " << endl;
    cout << "URL:     " << endl;
    /// @todo Do stuff in here also
}

int getMethod(char const* argv[])
{
    auto it = thresholdingArgs.find(argv[argsPosition::method]);

    if (it == thresholdingArgs.end())
        throw invalid_argument("Invalid argument " + string(argv[argsPosition::method]));

    return it->second;
}

void parseArguments(int argc, char const** argv, arguments & output)
{
    const int minArgs = 4;
    const int maxArgs = 5;
    if (argc < minArgs || argc > maxArgs)
        throw invalid_argument("Invalid count of arguments.\nExpected 4 arguments");

    output.method = getMethod(argv);
    output.inputPath = argv[argsPosition::inputImage];
    output.outputPath = argv[argsPosition::outputImage];

    if (argc == maxArgs)
        if (string("--half") == argv[4])
            output.halfThresholding = true;
}

void performThresholding(cv::Mat& inputImage, Histogram& histogram, arguments& args) {
    cv::Mat outputImage;

    cv::namedWindow( "Original", CV_WINDOW_AUTOSIZE );  // Create a window for display.
    cv::imshow( "Original", inputImage );              // Show our image inside it.

    if(args.method == thresholdingOption::otsu || args.method == thresholdingOption::all) {
        thresholding::OtsuMethod otsu(inputImage, histogram);
        otsu.run(outputImage);

        cv::imwrite(args.outputPath + ".otsu.png", outputImage);

        cv::namedWindow( otsu.getName(), CV_WINDOW_AUTOSIZE );  // Create a window for display.
        cv::imshow( otsu.getName(), outputImage );              // Show our image inside it.
    }
    if(args.method == thresholdingOption::balanced || args.method == thresholdingOption::all) {
        thresholding::BalancedHistogramMethod bht(inputImage, histogram);
        bht.run(outputImage);

        cv::imwrite(args.outputPath + ".bht.png", outputImage);

        cv::namedWindow( bht.getName(), CV_WINDOW_AUTOSIZE );  // Create a window for display.
        cv::imshow( bht.getName(), outputImage );              // Show our image inside it.
    }
    if(args.method == thresholdingOption::iterative || args.method == thresholdingOption::all) {
        thresholding::IterativeMethod iterative(inputImage, histogram);
        iterative.run(outputImage);

        cv::imwrite(args.outputPath + ".iterative.png", outputImage);

        cv::namedWindow( iterative.getName(), CV_WINDOW_AUTOSIZE );  // Create a window for display.
        cv::imshow( iterative.getName(), outputImage );              // Show our image inside it.
    }
    if(args.method == thresholdingOption::manual) {
        if(args.value < 0) {
            throw std::invalid_argument("Bad manual threshold argument");
        }

        throw std::runtime_error("Manual thresholding not supported yet");
    }

    cv::waitKey(0);
}

void saveImageWithTransparentBg(const string& outputFile, const cv::Mat &in) {
    uint8_t white = 255;
    cv::Mat outputMat;
    cv::cvtColor(in, outputMat, CV_GRAY2BGRA);
    for (int64_t x = 0; x < in.rows; ++x)
        for (int64_t y = 0; y < in.cols; ++y) {
            cv::Vec4b & pixel = outputMat.at<cv::Vec4b>(x,y);
            if (pixel[0] == white && pixel[1] == white && pixel[2] == white)
                pixel[3] = 0;
        }

    imwrite(outputFile, outputMat);
}

int main(int argc, char const* argv[])
{
    int retCode = errorCode::noError;
    cv::Mat inputImage;
    cv::Mat outputImage;
    arguments args;
    unique_ptr<Algorithm> algorithm = nullptr;
    bool allSet = false;
#ifdef DURATION
    chrono::time_point<chrono::system_clock> start, end;
#endif
    // Print help if no arguments are given
    try {
        parseArguments(argc, argv, args);
        inputImage = cv::imread(args.inputPath, CV_LOAD_IMAGE_GRAYSCALE);
        Histogram histogram(inputImage);

        //performThresholding(inputImage, histogram, args);
        // TODO: nevsimla jsem si metody all, tak asi predelat
        if (args.method == all) {
            allSet = true;
            args.method = 0;
        }

        while (args.method < all) {
            if (allSet && args.method == manual) {
                args.method++;
                continue;
            }

            switch (args.method) {
                case thresholdingOption::otsu:
                    algorithm = make_unique<OtsuMethod>(inputImage, histogram, args.halfThresholding);
                    break;
                case thresholdingOption::balanced:
                    algorithm = make_unique<BalancedHistogramMethod>(inputImage, histogram, args.halfThresholding);
                    break;
                case thresholdingOption::iterative:
                    algorithm = make_unique<IterativeMethod>(inputImage, histogram, args.halfThresholding);
                    break;
                case thresholdingOption::adaptiveMeanC:
                    algorithm = make_unique<AdaptiveMeanCMethod>(inputImage, histogram);
                    break;
                case thresholdingOption::adaptiveGauss:
                    algorithm = make_unique<AdaptiveGaussMethod>(inputImage, histogram);
                    break;
                default:
                    runtime_error("Invalid method option");
                    break;
            }

            // Run the algorithm
#ifdef DURATION
            start = chrono::system_clock::now();
#endif
            algorithm->run(outputImage);
#ifdef DURATION
            end = chrono::system_clock::now();
            chrono::duration<double> elapsedSeconds = end - start;
            chrono::microseconds micro = chrono::duration_cast<chrono::microseconds>(elapsedSeconds);
            cout << micro.count() << endl;
#endif
            if (allSet) {
                // Write image to the output file
                saveImageWithTransparentBg(args.getOutput(algorithm->getName()), outputImage);
                args.method++;
            }
            else {
                saveImageWithTransparentBg(args.getOutput(), outputImage);
                break;
            }
        }

    }
    catch (invalid_argument &e) {
        cerr << e.what() << endl;
        printHelp();
        retCode = errorCode::invalidArguments;
    }
    catch (exception &e) {
        cerr << e.what() << endl;
        retCode = errorCode::invalidArguments;
    }

    return retCode;
}
<commit_msg>main: add help message<commit_after>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <stdexcept>
#include <vector>

#ifdef DURATION
    #include <chrono>
#endif

//#include "version.h"
#include "Histogram.h"
#include "thresholding/OtsuMethod.h"
#include "thresholding/BalancedHistogramMethod.h"
#include "thresholding/IterativeMethod.h"
#include "thresholding/AdaptiveGaussMethod.h"
#include "thresholding/AdaptiveMeanCMethod.h"

using namespace std;
using namespace thresholding;

struct arguments {
    string inputPath;
    string outputPath;
    int method;
    int value;
    bool halfThresholding;

    arguments() : value(-1), halfThresholding(false)
    {}

    void print() {
        cout << "inputPath:  " << inputPath << endl <<
                "outputPath: " << outputPath << endl <<
                "method:     " << method << endl <<
                "value:      " << value << endl;
    }

    string getOutput(const string &methodName = "") {
        return outputPath + methodName + ".png";
    }
};

enum argsPosition {
    name = 0,
    method,
    inputImage,
    outputImage,
};

enum thresholdingOption {
    otsu = 0,
    adaptiveGauss,
    adaptiveMeanC,
    balanced,
    iterative,
    manual,
    all, //must be last
};

enum errorCode {
    noError = 0,
    invalidArguments,
};

map<string, int> thresholdingArgs({{"--otsu", thresholdingOption::otsu},
        {"--balanced", thresholdingOption::balanced},
        {"--adaptiveGauss", thresholdingOption::adaptiveGauss},
        {"--adaptiveMeanC", thresholdingOption::adaptiveMeanC},
        {"--iterative", thresholdingOption::iterative},
        {"--manual=", thresholdingOption::manual},
        {"--all", thresholdingOption::all}});

void printHelp()
{
    cout << "Help for zpo:" << endl <<
	    "Arguments: <method> <inputImage> <outputImage> [--half]" << endl <<
	    "Methods:" << endl;
    for (auto it : thresholdingArgs)
        cout << "    " << it.first << endl;
}

int getMethod(char const* argv[])
{
    auto it = thresholdingArgs.find(argv[argsPosition::method]);

    if (it == thresholdingArgs.end())
        throw invalid_argument("Invalid argument " + string(argv[argsPosition::method]));

    return it->second;
}

void parseArguments(int argc, char const** argv, arguments & output)
{
    const int minArgs = 4;
    const int maxArgs = 5;
    if (argc < minArgs || argc > maxArgs)
        throw invalid_argument("Invalid count of arguments.\nExpected 4 arguments");

    output.method = getMethod(argv);
    output.inputPath = argv[argsPosition::inputImage];
    output.outputPath = argv[argsPosition::outputImage];

    if (argc == maxArgs)
        if (string("--half") == argv[4])
            output.halfThresholding = true;
}

void performThresholding(cv::Mat& inputImage, Histogram& histogram, arguments& args) {
    cv::Mat outputImage;

    cv::namedWindow( "Original", CV_WINDOW_AUTOSIZE );  // Create a window for display.
    cv::imshow( "Original", inputImage );              // Show our image inside it.

    if(args.method == thresholdingOption::otsu || args.method == thresholdingOption::all) {
        thresholding::OtsuMethod otsu(inputImage, histogram);
        otsu.run(outputImage);

        cv::imwrite(args.outputPath + ".otsu.png", outputImage);

        cv::namedWindow( otsu.getName(), CV_WINDOW_AUTOSIZE );  // Create a window for display.
        cv::imshow( otsu.getName(), outputImage );              // Show our image inside it.
    }
    if(args.method == thresholdingOption::balanced || args.method == thresholdingOption::all) {
        thresholding::BalancedHistogramMethod bht(inputImage, histogram);
        bht.run(outputImage);

        cv::imwrite(args.outputPath + ".bht.png", outputImage);

        cv::namedWindow( bht.getName(), CV_WINDOW_AUTOSIZE );  // Create a window for display.
        cv::imshow( bht.getName(), outputImage );              // Show our image inside it.
    }
    if(args.method == thresholdingOption::iterative || args.method == thresholdingOption::all) {
        thresholding::IterativeMethod iterative(inputImage, histogram);
        iterative.run(outputImage);

        cv::imwrite(args.outputPath + ".iterative.png", outputImage);

        cv::namedWindow( iterative.getName(), CV_WINDOW_AUTOSIZE );  // Create a window for display.
        cv::imshow( iterative.getName(), outputImage );              // Show our image inside it.
    }
    if(args.method == thresholdingOption::manual) {
        if(args.value < 0) {
            throw std::invalid_argument("Bad manual threshold argument");
        }

        throw std::runtime_error("Manual thresholding not supported yet");
    }

    cv::waitKey(0);
}

void saveImageWithTransparentBg(const string& outputFile, const cv::Mat &in) {
    uint8_t white = 255;
    cv::Mat outputMat;
    cv::cvtColor(in, outputMat, CV_GRAY2BGRA);
    for (int64_t x = 0; x < in.rows; ++x)
        for (int64_t y = 0; y < in.cols; ++y) {
            cv::Vec4b & pixel = outputMat.at<cv::Vec4b>(x,y);
            if (pixel[0] == white && pixel[1] == white && pixel[2] == white)
                pixel[3] = 0;
        }

    imwrite(outputFile, outputMat);
}

int main(int argc, char const* argv[])
{
    int retCode = errorCode::noError;
    cv::Mat inputImage;
    cv::Mat outputImage;
    arguments args;
    unique_ptr<Algorithm> algorithm = nullptr;
    bool allSet = false;
#ifdef DURATION
    chrono::time_point<chrono::system_clock> start, end;
#endif
    // Print help if no arguments are given
    try {
        parseArguments(argc, argv, args);
        inputImage = cv::imread(args.inputPath, CV_LOAD_IMAGE_GRAYSCALE);
        Histogram histogram(inputImage);

        //performThresholding(inputImage, histogram, args);
        // TODO: nevsimla jsem si metody all, tak asi predelat
        if (args.method == all) {
            allSet = true;
            args.method = 0;
        }

        while (args.method < all) {
            if (allSet && args.method == manual) {
                args.method++;
                continue;
            }

            switch (args.method) {
                case thresholdingOption::otsu:
                    algorithm = make_unique<OtsuMethod>(inputImage, histogram, args.halfThresholding);
                    break;
                case thresholdingOption::balanced:
                    algorithm = make_unique<BalancedHistogramMethod>(inputImage, histogram, args.halfThresholding);
                    break;
                case thresholdingOption::iterative:
                    algorithm = make_unique<IterativeMethod>(inputImage, histogram, args.halfThresholding);
                    break;
                case thresholdingOption::adaptiveMeanC:
                    algorithm = make_unique<AdaptiveMeanCMethod>(inputImage, histogram);
                    break;
                case thresholdingOption::adaptiveGauss:
                    algorithm = make_unique<AdaptiveGaussMethod>(inputImage, histogram);
                    break;
                default:
                    runtime_error("Invalid method option");
                    break;
            }

            // Run the algorithm
#ifdef DURATION
            start = chrono::system_clock::now();
#endif
            algorithm->run(outputImage);
#ifdef DURATION
            end = chrono::system_clock::now();
            chrono::duration<double> elapsedSeconds = end - start;
            chrono::microseconds micro = chrono::duration_cast<chrono::microseconds>(elapsedSeconds);
            cout << micro.count() << endl;
#endif
            if (allSet) {
                // Write image to the output file
                saveImageWithTransparentBg(args.getOutput(algorithm->getName()), outputImage);
                args.method++;
            }
            else {
                saveImageWithTransparentBg(args.getOutput(), outputImage);
                break;
            }
        }

    }
    catch (invalid_argument &e) {
        cerr << e.what() << endl;
        printHelp();
        retCode = errorCode::invalidArguments;
    }
    catch (exception &e) {
        cerr << e.what() << endl;
        retCode = errorCode::invalidArguments;
    }

    return retCode;
}
<|endoftext|>


<commit_before>#include <ctrcommon/common.hpp>

#include <sstream>
#include <iomanip>

typedef enum {
    INSTALL,
    DELETE
} Mode;

int main(int argc, char **argv) {
    if(!platform_init()) {
        return 0;
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL;
    bool netInstall = false;
    u64 freeSpace = fs_get_free_space(destination);
    auto onLoop = [&]() {
        bool breakLoop = false;
        if(input_is_pressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fs_get_free_space(destination);
            if(mode == DELETE) {
                breakLoop = true;
            }
        }

        if(input_is_pressed(BUTTON_R)) {
            if(mode == INSTALL) {
                mode = DELETE;
            } else {
                mode = INSTALL;
            }

            breakLoop = true;
        }

        if(input_is_pressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        stream << "Y - Receive an app over the network" << "\n";

        std::string str = stream.str();
        screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](int progress) {
        ui_display_progress("Installing", "Press B to cancel.", true, progress);
        input_poll();
        return !input_is_pressed(BUTTON_B);
    };

    while(platform_is_running()) {
        std::string targetInstall;
        App targetDelete;
        bool obtained = false;
        if(mode == INSTALL) {
            obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
        } else if(mode == DELETE) {
            obtained = ui_select_app(&targetDelete, destination, onLoop);
        }

        if(netInstall) {
            netInstall = false;

            // Clear bottom screen on both buffers.
            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            RemoteFile file = ui_accept_remote_file();
            if(file.socket == -1) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(ui_prompt(confirmStream.str(), true)) {
                int ret = app_install(destination, file.socket, true, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);
            }

            socket_close(file.socket);
            continue;
        }

        if(obtained) {
            std::stringstream prompt;
            if(mode == INSTALL) {
                prompt << "Install ";
            } else if(mode == DELETE) {
                prompt << "Delete ";
            }

            prompt << "the selected title?";
            if(ui_prompt(prompt.str(), true)) {
                int ret = 0;
                if(mode == INSTALL) {
                    ret = app_install_file(destination, targetInstall, onProgress);
                } else if(mode == DELETE) {
                    ui_display_message("Deleting title...");
                    ret = app_delete(targetDelete);
                }

                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);

                freeSpace = fs_get_free_space(destination);
            }
        }
    }

    platform_cleanup();
    return 0;
}
<commit_msg>Properly report cancellation.<commit_after>#include <ctrcommon/common.hpp>

#include <sstream>
#include <iomanip>

typedef enum {
    INSTALL,
    DELETE
} Mode;

int main(int argc, char **argv) {
    if(!platform_init()) {
        return 0;
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL;
    bool netInstall = false;
    u64 freeSpace = fs_get_free_space(destination);
    auto onLoop = [&]() {
        bool breakLoop = false;
        if(input_is_pressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fs_get_free_space(destination);
            if(mode == DELETE) {
                breakLoop = true;
            }
        }

        if(input_is_pressed(BUTTON_R)) {
            if(mode == INSTALL) {
                mode = DELETE;
            } else {
                mode = INSTALL;
            }

            breakLoop = true;
        }

        if(input_is_pressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        stream << "Y - Receive an app over the network" << "\n";

        std::string str = stream.str();
        screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](int progress) {
        ui_display_progress("Installing", "Press B to cancel.", true, progress);
        input_poll();
        return !input_is_pressed(BUTTON_B);
    };

    while(platform_is_running()) {
        std::string targetInstall;
        App targetDelete;
        bool obtained = false;
        if(mode == INSTALL) {
            obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
        } else if(mode == DELETE) {
            obtained = ui_select_app(&targetDelete, destination, onLoop);
        }

        if(netInstall) {
            netInstall = false;

            // Clear bottom screen on both buffers.
            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            RemoteFile file = ui_accept_remote_file();
            if(file.socket == -1) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(ui_prompt(confirmStream.str(), true)) {
                int ret = app_install(destination, file.socket, true, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else if(ret == -2) {
                    resultMsg << "cancelled!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);
            }

            socket_close(file.socket);
            continue;
        }

        if(obtained) {
            std::stringstream prompt;
            if(mode == INSTALL) {
                prompt << "Install ";
            } else if(mode == DELETE) {
                prompt << "Delete ";
            }

            prompt << "the selected title?";
            if(ui_prompt(prompt.str(), true)) {
                int ret = 0;
                if(mode == INSTALL) {
                    ret = app_install_file(destination, targetInstall, onProgress);
                } else if(mode == DELETE) {
                    ui_display_message("Deleting title...");
                    ret = app_delete(targetDelete);
                }

                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else if(ret == -2) {
                    resultMsg << "cancelled!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);

                freeSpace = fs_get_free_space(destination);
            }
        }
    }

    platform_cleanup();
    return 0;
}
<|endoftext|>


<commit_before>#include <3ds.h>
#include <stdio.h>

void shutdown3DS()
{
	Handle ptmSysmHandle = 0;
	Result result = srvGetServiceHandle(&ptmSysmHandle, "ptm:sysm");
	if (result != 0)
		return;

	u32 *commandBuffer = getThreadCommandBuffer();
	commandBuffer[0] = 0x040700C0; //ptm:s::ShutdownAsync
	commandBuffer[1] = 0;
	commandBuffer[2] = 0;
	commandBuffer[3] = 0;

	svcSendSyncRequest(ptmSysmHandle);
	svcCloseHandle(ptmSysmHandle);
}

int main(int argc, char **argv) {
    hidScanInput();

	// If any key is pressed, cancel the shutdown.
	if (hidKeysDown() != 0)
		goto done;

	shutdown3DS();

done:
	// Hack: the 3ds crashes ("An error has occcurred.") for some reason
	// without one iteration of the main loop.
	aptMainLoop();
    return 0;
}
<commit_msg>Update main.cpp<commit_after>#include <3ds.h>
#include <stdio.h>

void shutdown3DS()
{
	Handle ptmSysmHandle = 0;
	Result result = srvGetServiceHandle(&ptmSysmHandle, "ptm:sysm");
	if (result != 0)
		return;

	u32 *commandBuffer = getThreadCommandBuffer();
	commandBuffer[0] = 0x040700C0; //ptm:s::ShutdownAsync
	commandBuffer[1] = 0;
	commandBuffer[2] = 0;
	commandBuffer[3] = 0;

	svcSendSyncRequest(ptmSysmHandle);
	svcCloseHandle(ptmSysmHandle);
}

int main(int argc, char **argv) {
	hidScanInput();

	// If any key is pressed, cancel the shutdown.
	if (hidKeysDown() != 0)
		goto done;

	shutdown3DS();

done:
	// Hack: the 3ds crashes ("An error has occcurred.") for some reason
	// without one iteration of the main loop.
	aptMainLoop();
	return 0;
}
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 6/23/2019, 5:37:29 AM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <memory>
#include <algorithm>

template <typename T, typename A = std::allocator<T>>
struct vector_base
{ // vector のためのメモリ構造
  A alloc;
  T *elem;  // 先頭
  T *space; // 拡張用領域の先頭
  T *last;  // 終端

  vector_base(const A &a, typename A::size_type n = 0, typename A::size_type m = 0)
      : alloc{a}, elem{alloc.allocate(n + m)}, space{elem + n}, last{elem + n + m} {}

  ~vector_base() { alloc.deallocate(elem, last - elem); }

  vector_base(const vector_base &) = delete;            // コピー演算は行えない
  vector_base &operator=(const vector_base &) = delete; // コピー代入演算子も無効化

  vector_base(vector_base &&);            // ムーブ演算を行う
  vector_base &operator=(vector_base &&); // ムーブ代入演算子
};

template <typename T, typename A = std::allocator<T>>
class vector
{
private:
  vector_base<T, A> vb;
  void destroy_elements();

public:
  using size_type = typename A::size_type; // vector 要素用の型
  explicit vector(size_type n = 0, const T &val = T(), const A &a = A());

  ~vector() { destroy_elements(); };

  vector(const vector &a);            // コピーコンストラクタ
  vector &operator=(const vector &a); // コピー代入演算子

  vector(vector &&a);            // ムーブコンストラクタ
  vector &operator=(vector &&a); // ムーブ代入演算子

  size_type size() const { return vb.space - vb.elem; }
  size_type capacity() const { return vb.last - vb.elem; }
  void reserve(size_type n);                // 容量を n まで増やす
  void resize(size_type n, const T & = {}); // 要素数を n に変更
  void clear() { resize(0); }
  void push_back(const T &);

  T *begin() { return vb.elem; }
  T *end() { return vb.space; }
  const T &operator[](const size_type t) const { return *(vb.elem + t); }
  T &operator[](const size_type t) { return *(vb.elem + t); }
};

template <typename T>
void my_swap(T &a, T &b)
{
  T tmp{std::move(a)};
  a = std::move(b);
  b = std::move(tmp);
}

template <typename T, typename A>
vector_base<T, A>::vector_base(vector_base &&a)
    : alloc{a.alloc}, elem{a.elem}, space{a.space}, last{a.last}
{
  a.elem = a.space = a.last = nullptr;
}

template <typename T, typename A>
vector_base<T, A> &vector_base<T, A>::operator=(vector_base &&a)
{
  std::swap(*this, a);
  return *this;
}

template <typename T, typename A>
void vector<T, A>::destroy_elements()
{
  for (T *p = vb.elem; p != vb.space; ++p)
  {
    p->~T();
  }
  vb.space = vb.elem;
}

template <typename T, typename A>
vector<T, A>::vector(size_type n, const T &val, const A &a) : vb{a, n}
{
  std::uninitialized_fill(vb.elem, vb.elem + n, val);
}

template <typename T, typename A>
vector<T, A>::vector(const vector &a) : vb{a.vb.alloc, a.size()}
{
  std::uninitialized_copy(a.begin(), a.end(), vb.elem);
}

template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(const vector &a)
{
  vector temp{a};
  my_swap<vector<T, A>>(*this, temp);
  return *this;
}

template <typename T, typename A>
vector<T, A>::vector(vector &&a) : vb{std::move(a.vb)} {}

template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(vector &&a)
{
  my_swap<vector<T, A>>(vb, a.vb);
  return *this;
}

/*
template <typename C>
using Value_type = typename C::value_type;

template <typename In, typename Out>
Out uninitialized_move(In b, In e, Out oo)
{
  using T = Value_type<Out>;
  for (; b != e; ++b, ++oo)
  {
    new (static_cast<void *>(&*oo)) T{std::move(*b)};
    b->~T();
  }
  return oo;
}
*/

template <typename T, typename A>
void vector<T, A>::reserve(size_type new_alloc)
{
  if (new_alloc <= capacity())
  {
    return;
  }
  vector_base<T, A> b{vb.alloc, new_alloc - size()};
  // uninitialized_move(vb.elem, vb.elem + size(), b.elem);
  T *oo = b.elem;
  for (auto begin = vb.elem; begin != vb.elem + size(); ++begin, ++oo)
  {
    new (static_cast<void *>(&*oo)) T{std::move(*begin)};
    begin->~T();
  }
  my_swap<vector_base<T, A>>(vb, b);
}

/*
template <typename In>
void destroy(In b, In e)
{
  for (; b != e; ++b)
  {
    b->~Value_type<In>();
  }
}
*/

template <typename T, typename A>
void vector<T, A>::resize(size_type new_size, const T &val)
{
  reserve(new_size);
  if (size() < new_size)
  {
    std::uninitialized_fill(vb.elem + size(), vb.elem + new_size, val);
  }
  else
  {
    auto b = vb.elem + new_size;
    auto e = vb.elem + size();
    for (; b != e; ++b)
    {
      b->~T();
    }
  }
  vb.space = vb.elem + new_size;
}

template <typename T, typename A>
void vector<T, A>::push_back(const T &val)
{
  if (capacity() == size())
  {
    reserve(size() ? 2 * size() : 8);
  }
  vb.alloc.construct(&vb.elem[size()], val);
  ++vb.space;
}

typedef long long ll;

int N;
typedef std::pair<ll, ll> work;
vector<work> V;

int main()
{
  std::cin >> N;
  for (auto i = 0; i < N; i++)
  {
    ll a, b;
    std::cin >> a >> b;
    V.push_back(work(b, a));
  }
  std::sort(V.begin(), V.end());
  ll now = 0;
  for (auto i = 0; i < N; i++)
  {
    now += V[i].first;
    if (now > V[i].second)
    {
      std::cout << "No" << std::endl;
      return 0;
    }
  }
  std::cout << "Yes" << std::endl;
}<commit_msg>tried D2.cpp to 'D'<commit_after>#define DEBUG 1
/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 6/23/2019, 5:37:29 AM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <memory>
#include <algorithm>

template <typename T, typename A = std::allocator<T>>
struct vector_base
{ // vector のためのメモリ構造
  A alloc;
  T *elem;  // 先頭
  T *space; // 拡張用領域の先頭
  T *last;  // 終端

  vector_base(const A &a, typename A::size_type n = 0, typename A::size_type m = 0)
      : alloc{a}, elem{alloc.allocate(n + m)}, space{elem + n}, last{elem + n + m} {}

  ~vector_base() { alloc.deallocate(elem, last - elem); }

  vector_base(const vector_base &) = delete;            // コピー演算は行えない
  vector_base &operator=(const vector_base &) = delete; // コピー代入演算子も無効化

  vector_base(vector_base &&);            // ムーブ演算を行う
  vector_base &operator=(vector_base &&); // ムーブ代入演算子
};

template <typename T, typename A = std::allocator<T>>
class vector
{
private:
  vector_base<T, A> vb;
  void destroy_elements();

public:
  using size_type = typename A::size_type; // vector 要素用の型
  explicit vector(size_type n = 0, const T &val = T(), const A &a = A());

  ~vector() { destroy_elements(); };

  vector(const vector &a);            // コピーコンストラクタ
  vector &operator=(const vector &a); // コピー代入演算子

  vector(vector &&a);            // ムーブコンストラクタ
  vector &operator=(vector &&a); // ムーブ代入演算子

  size_type size() const { return vb.space - vb.elem; }
  size_type capacity() const { return vb.last - vb.elem; }
  void reserve(size_type n);                // 容量を n まで増やす
  void resize(size_type n, const T & = {}); // 要素数を n に変更
  void clear() { resize(0); }
  void push_back(const T &);

  T *begin() { return vb.elem; }
  T *end() { return vb.space; }
  const T &operator[](const size_type t) const { return *(vb.elem + t); }
  T &operator[](const size_type t) { return *(vb.elem + t); }
};

template <typename T, typename A>
vector_base<T, A>::vector_base(vector_base &&a)
    : alloc{a.alloc}, elem{a.elem}, space{a.space}, last{a.last}
{
  a.elem = a.space = a.last = nullptr;
}

template <typename T, typename A>
vector_base<T, A> &vector_base<T, A>::operator=(vector_base &&a)
{
  std::swap(*this, a);
  return *this;
}

template <typename T, typename A>
void vector<T, A>::destroy_elements()
{
  for (T *p = vb.elem; p != vb.space; ++p)
  {
    p->~T();
  }
  vb.space = vb.elem;
}

template <typename T, typename A>
vector<T, A>::vector(size_type n, const T &val, const A &a) : vb{a, n}
{
  std::uninitialized_fill(vb.elem, vb.elem + n, val);
}

template <typename T, typename A>
vector<T, A>::vector(const vector &a) : vb{a.vb.alloc, a.size()}
{
  std::uninitialized_copy(a.begin(), a.end(), vb.elem);
}

template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(const vector &a)
{
  vector temp{a};
  std::swap(*this, temp);
  return *this;
}

template <typename T, typename A>
vector<T, A>::vector(vector &&a) : vb{std::move(a.vb)} {}

template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(vector &&a)
{
  std::swap(vb, a.vb);
  return *this;
}

/*
template <typename C>
using Value_type = typename C::value_type;

template <typename In, typename Out>
Out uninitialized_move(In b, In e, Out oo)
{
  using T = Value_type<Out>;
  for (; b != e; ++b, ++oo)
  {
    new (static_cast<void *>(&*oo)) T{std::move(*b)};
    b->~T();
  }
  return oo;
}
*/

template <typename T, typename A>
void vector<T, A>::reserve(size_type new_alloc)
{
  if (new_alloc <= capacity())
  {
    return;
  }
  vector_base<T, A> b{vb.alloc, new_alloc - size()};
  // uninitialized_move(vb.elem, vb.elem + size(), b.elem);
  T *oo = b.elem;
  for (auto begin = vb.elem; begin != vb.elem + size(); ++begin, ++oo)
  {
    new (static_cast<void *>(&*oo)) T{std::move(*begin)};
    begin->~T();
  }
  vb = move(b);
}

/*
template <typename In>
void destroy(In b, In e)
{
  for (; b != e; ++b)
  {
    b->~Value_type<In>();
  }
}
*/

template <typename T, typename A>
void vector<T, A>::resize(size_type new_size, const T &val)
{
  reserve(new_size);
  if (size() < new_size)
  {
    std::uninitialized_fill(vb.elem + size(), vb.elem + new_size, val);
  }
  else
  {
    auto b = vb.elem + new_size;
    auto e = vb.elem + size();
    for (; b != e; ++b)
    {
      b->~T();
    }
  }
  vb.space = vb.elem + new_size;
}

template <typename T, typename A>
void vector<T, A>::push_back(const T &val)
{
  if (capacity() == size())
  {
    reserve(size() ? 2 * size() : 8);
  }
  vb.alloc.construct(&vb.elem[size()], val);
  ++vb.space;
}

typedef long long ll;

int N;
typedef std::pair<ll, ll> work;
vector<work> V;

int main()
{
  std::cin >> N;
  for (auto i = 0; i < N; i++)
  {
    ll a, b;
    std::cin >> a >> b;
    V.push_back(work(b, a));
  }
  std::sort(V.begin(), V.end());
  ll now = 0;
  for (auto i = 0; i < N; i++)
  {
    now += V[i].first;
    if (now > V[i].second)
    {
      std::cout << "No" << std::endl;
      return 0;
    }
  }
  std::cout << "Yes" << std::endl;
}<|endoftext|>