text
stringlengths 8
6.88M
|
|---|
/*
* Copyright 2017 Roman Katuntsev <sbkarr@stappler.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SRC_RUNTIMEENVIRONMENT_H_
#define SRC_RUNTIMEENVIRONMENT_H_
#include "Environment.h"
#include "Thread.h"
namespace wasm {
struct LinkingThreadOptions : LinkingPolicy {
uint32_t valueStackSize = Thread::kDefaultValueStackSize;
uint32_t callStackSize = Thread::kDefaultCallStackSize;
};
class ThreadedRuntime : public Runtime {
public:
virtual ~ThreadedRuntime() { }
ThreadedRuntime();
bool init(const Environment *, const LinkingThreadOptions & = LinkingThreadOptions());
const Func *getExportFunc(const StringView &module, const StringView &name) const;
const Func *getExportFunc(const RuntimeModule &module, const StringView &name) const;
const RuntimeGlobal *getGlobal(const StringView &module, const StringView &name) const;
const RuntimeGlobal *getGlobal(const RuntimeModule &module, const StringView &name) const;
bool setGlobal(const StringView &module, const StringView &name, const Value &);
bool setGlobal(const RuntimeModule &module, const StringView &name, const Value &);
bool call(const RuntimeModule &module, const Func &, Vector<Value> ¶msInOut);
bool call(const RuntimeModule &module, const Func &, Value *paramsInOut);
bool call(const Func &, Vector<Value> ¶msInOut);
bool call(const Func &, Value *paramsInOut);
Thread::Result callSafe(const RuntimeModule &module, const Func &, Vector<Value> ¶msInOut);
Thread::Result callSafe(const RuntimeModule &module, const Func &, Value *paramsInOut);
Thread::Result callSafe(const Func &, Vector<Value> ¶msInOut);
Thread::Result callSafe(const Func &, Value *paramsInOut);
virtual void onError(StringStream &) const;
virtual void onThreadError(const Thread &) const;
protected:
bool _silent = false;
Thread _mainThread;
};
}
#endif /* SRC_RUNTIMEENVIRONMENT_H_ */
|
#pragma once
#include "Entity.h"
class Plane :
public Entity
{
public:
sf::String getClass(){
return "Plane";
}
Plane(sf::String F, int X, int Y, int Width, int Height) {
setDamage(5);
setLife(true);
setX(X); setY(Y); // координаты появления спрайта
setW(Width); setH(Height); // ширина и высота
setSpeed(0); setHealth(3); setDX(0); setDY(0);
imageLoadFromFile(F);
textureLoadFromImage(getImage());
spriteSetTexture(getTexture());
spriteSetTextureRect(getW(), getH());
setOrigin(getW(), getH());
}
Plane() {
setDamage(5);
setLife(true);
setSpeed(0); setHealth(3); setDX(0); setDY(0);
imageLoadFromFile("plane.png");
textureLoadFromImage(getImage());
spriteSetTexture(getTexture());
setX(150); setY(10); // координаты появления спрайта
setW(50); setH(55); // ширина и высота
spriteSetTextureRect(getW(), getH());
setOrigin(getW(), getH());
}
void move(float time, float speed){
if (getX() == 150 && getY() < 850) {
moveDown(speed, time);
}
else if (getX() < 350 && getY() > 850) {
moveRight(speed, time);
}
else if (getX() > 350 && getX() < 550 && getY() > 150) {
moveUp(speed, time);
}
else if (getX() < 550 && getY() < 150) {
moveRight(speed, time);
}
else if (getX() > 550 && getX() < 750 && getY() < 850) {
moveDown(speed, time);
}
else if (getX() < 750 && getY() > 850) {
moveRight(speed, time);
}
else if (getX() > 750 && getY() > 150) {
moveUp(speed, time);
}
else if (getX() < 1000 && getY() < 150) {
moveRight(speed, time);
}
return;
}
void update(float time) {
switch (getDirection()) { // направление движение
case 0: setDX(getSpeed()); setDY(0); break;
case 1: setDX(-getSpeed()); setDY(0); break;
case 2: setDX(0); setDY(getSpeed()); break;
case 3: setDX(0); setDY(-getSpeed()); break;
}
setX(getX()+getDX() * time); // изменение координат
setY(getY()+getDY() * time);
spriteSetTextureRect(3-getHealth(), getW(), getH());
spriteSetPosition(getX(), getY());
}
};
|
#include "asio/tcp_client_handler.hpp"
tcp_client_handler::tcp_client_handler(boost::asio::io_service & io_service, std::unique_ptr<deviceDescription> description)
{
device_ = std::unique_ptr<tcp_client>(new tcp_client(io_service, std::move(description)));
}
void tcp_client_handler::kickstart(const boost::system::error_code& err)
{
device_->handle_connect(err);
}
boost::asio::ip::tcp::socket& tcp_client_handler::get_socket()
{
return device_->socket();
}
//useufl if underlying connection uses the asio_read, asio_read_at, or
//asio_read_until free functions returning stream_buf types
bool tcp_client_handler::handle_receive(std::streambuf& msg_stream)
{
}
|
/*************************************************************
Author : qmeng
MailTo : qmeng1128@163.com
QQ : 1163306125
Blog : http://blog.csdn.net/Mq_Go/
Create : 2018-03-17 09:55:59
Version: 1.0
**************************************************************/
#include <cstdio>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
bool isequl(int qa[],int qb[]){
for(int i = 0 ; i < 10 ; i++){
if(qa[i] != qb[i])return false;
}
return true;
}
int main(){
string str1;
cin >> str1;
vector<int> v1,v2;
int qa[10] = {0},qb[10] = {0};
int len = str1.length();
v1.resize(len);
v2.resize(len+1);
for(int i = len-1 ; i >=0 ; i--)v1[len-i-1]=str1[i]-'0';
//for(int i = 0; i < len ; i++)cout << v1[i];
int temp = 0,temp2 = 0;
for(int i = 0 ; i < len ; i++){
temp = v1[i]*2;
v2[i] = (temp + temp2)%10;
temp2 = (temp+temp2)/10;
qa[v1[i]]++;
qb[v2[i]]++;
}
//for(int i = 0; i < len ; i++)cout << v2[i];
if(temp2>0){
printf("No\n");
printf("%d",temp2);
for(int i = v1.size()-1 ; i >=0 ; i-- )printf("%d",v2[i]);
return 0;
}
if(isequl(qa,qb)){
printf("Yes\n");
for(int i = v1.size()-1 ; i >=0 ; i-- )printf("%d",v2[i]);
}else{
printf("No\n");
for(int i = v1.size()-1 ; i >=0 ; i-- )printf("%d",v2[i]);
}
return 0;
}
|
#include<iostream>
#include<vector>
//typedef vector<int> vi;
using namespace std;
vector<int> coins = {1,3,4};
int coinchange(int sum)
{
if(sum<0)
return 1e9;
else if (sum == 0)
return 0;
else
{
int minimumCoins = 1e9;
for(auto c: coins)
minimumCoins = min(minimumCoins, coinchange(sum-c)+1);
return minimumCoins;
}
}
int main()
{
int sum = 0;
cin>>sum;
cout<<coinchange(sum);
return 0;
}
|
#include<stdio.h>
#include<malloc.h>
struct node{
int data;
struct node *next;
};
int push(struct node **,int);
int removeDup(struct node *);
int print(struct node *);
int push(struct node **head_ref,int new_data){
struct node *temp=(struct node *)malloc(sizeof(struct node ));
temp->data=new_data;
temp->next=*head_ref;
*head_ref=temp;
}
int removeDup(struct node *head){
struct node *current=head;
struct node *next_next;
if(current==NULL)
return 0;
while(current->next!=NULL){
if(current->data==current->next->data){
next_next=current->next->next;
free(current->next);
current->next=next_next;
}
else{
current=current->next;
}
}
}
int main(void){
struct node *head=NULL;
push(&head,12);
push(&head,14);
push(&head,14);
push(&head,23);
removeDup(head);
print(head);
return 0;
}
int print(struct node *head){
while(head!=NULL){
printf("%d ",head->data);
head=head->next;
}
}
|
#include <cstdlib>
#include <fmt/format.h>
#include "ast.h"
#include "ast_format.h"
#include "parser.h"
#include "tokenizer.h"
#include "util.h"
#include "test.h"
#if defined(__unix__)
#define PATH_SEPARATOR "/"
#else
#error "Path separator not defined for this target"
#endif
using namespace wcc;
const char testsrc[] = "void func() {\n"
"u64 a;\n"
"u64 b;\n"
"u64 c;\n"
"a = 10 + 20 * 30 + 5;\n"
"b = 12 * 13 + 4;\n"
"}\n";
struct test_ctx
{
struct
{
size_t muls_checked = 0;
size_t adds_checked = 0;
bool arg_10 = false;
bool arg_5 = false;
} first_assignment;
struct
{
size_t muls_checked = 0;
size_t adds_checked = 0;
} second_assignment;
};
static bool
check_first_assign_(struct test_ctx& ctx, const AstStmt& stmt)
{
const auto& call = std::get<AstFunctionCall>(stmt.value);
if (call.args[0].type == StmtType::call)
TEST_ASSERT(check_first_assign_(ctx, call.args[0]));
if (call.args[1].type == StmtType::call)
TEST_ASSERT(check_first_assign_(ctx, call.args[1]));
if (call.name == STDOP_FUNC_STR[underlay_cast(TOKENID::OP_MUL)]) {
TEST_ASSERT(ctx.first_assignment.muls_checked < 1);
TEST_ASSERT(call.args.size() == 2);
bool arg_20 = false, arg_30 = false;
for (const auto& arg : call.args) {
TEST_ASSERT(arg.type == StmtType::varref);
arg_20 |= std::get<AstSymRef>(arg.value).name == "20";
arg_30 |= std::get<AstSymRef>(arg.value).name == "30";
}
TEST_ASSERT(arg_20);
TEST_ASSERT(arg_30);
++ctx.first_assignment.muls_checked;
}
if (call.name == STDOP_FUNC_STR[underlay_cast(TOKENID::OP_PLUS)]) {
TEST_ASSERT(call.args.size() == 2);
for (const auto& arg : call.args) {
if (arg.type != StmtType::varref)
continue;
// Make sure we have seen arg 10 and arg 5 only once and never at the
// same time as an argument to the same operator plus.
const auto arg_10_local =
std::get<AstSymRef>(call.args[0].value).name == "10";
const auto arg_5_local =
std::get<AstSymRef>(call.args[0].value).name == "5";
ctx.first_assignment.arg_10 += arg_10_local;
ctx.first_assignment.arg_5 += arg_5_local;
TEST_ASSERT((arg_10_local ^ arg_5_local));
}
++ctx.first_assignment.adds_checked;
}
return true;
}
static bool
check_first_assign(struct test_ctx& ctx, const AstStmt& stmt)
{
check_first_assign_(ctx, stmt);
TEST_ASSERT(ctx.first_assignment.adds_checked == 2);
TEST_ASSERT(ctx.first_assignment.muls_checked == 1);
TEST_ASSERT(ctx.first_assignment.arg_10 == 1);
TEST_ASSERT(ctx.first_assignment.arg_5 == 1);
return true;
}
static bool
check_second_assign_(struct test_ctx& ctx, const AstStmt& stmt)
{
const auto& call = std::get<AstFunctionCall>(stmt.value);
if (call.args[0].type == StmtType::call)
TEST_ASSERT(check_second_assign_(ctx, call.args[0]));
if (call.args[1].type == StmtType::call)
TEST_ASSERT(check_second_assign_(ctx, call.args[1]));
if (call.name == STDOP_FUNC_STR[underlay_cast(TOKENID::OP_MUL)]) {
TEST_ASSERT(call.args.size() == 2);
bool arg_12 = false, arg_13 = false;
for (const auto& arg : call.args) {
TEST_ASSERT(arg.type == StmtType::varref);
arg_12 |= std::get<AstSymRef>(arg.value).name == "12";
arg_13 |= std::get<AstSymRef>(arg.value).name == "13";
}
TEST_ASSERT(arg_12);
TEST_ASSERT(arg_13);
++ctx.second_assignment.muls_checked;
}
if (call.name == STDOP_FUNC_STR[underlay_cast(TOKENID::OP_PLUS)]) {
TEST_ASSERT(call.args.size() == 2);
for (const auto& arg : call.args) {
if (arg.type != StmtType::varref)
continue;
TEST_ASSERT(std::get<AstSymRef>(call.args[0].value).name == "4");
}
++ctx.second_assignment.adds_checked;
}
return true;
}
static bool
check_second_assign(struct test_ctx& ctx, const AstStmt& stmt)
{
check_second_assign_(ctx, stmt);
TEST_ASSERT(ctx.second_assignment.adds_checked == 1);
TEST_ASSERT(ctx.second_assignment.muls_checked == 1);
return true;
}
bool
operator_precedence_test()
{
struct test_ctx ctx;
Tokenizer tokenizer(testsrc, sizeof(testsrc) - 1);
Parser parser(tokenizer);
AST ast = parser.buildAST();
auto* func_node = ast.root.nodes[0].get();
TEST_ASSERT(func_node->id == ASTID::funcdecl);
auto& func = std::get<AstFunction>(func_node->value);
TEST_ASSERT(func.name == "func");
TEST_ASSERT(func.return_type == LangType::lt_void);
TEST_ASSERT(func.args.size() == 0);
TEST_ASSERT(func_node->nodes[0]->id == ASTID::vardecl);
TEST_ASSERT(func_node->nodes[1]->id == ASTID::vardecl);
TEST_ASSERT(func_node->nodes[2]->id == ASTID::vardecl);
//
// Check AST for first assignment
//
const auto *stmt_node = func_node->nodes[3].get();
TEST_ASSERT(stmt_node->id == ASTID::stmt);
const auto* stmt = &std::get<AstStmt>(stmt_node->value);
TEST_ASSERT(stmt->type == StmtType::call);
auto* call = &std::get<AstFunctionCall>(stmt->value);
TEST_ASSERT(call->name == STDOP_FUNC_STR[underlay_cast(TOKENID::OP_EQ)]);
TEST_ASSERT(call->args[0].type == StmtType::varref);
TEST_ASSERT(std::get<AstSymRef>(call->args[0].value).name == "a");
TEST_ASSERT(check_first_assign(ctx, *stmt));
//
// Check AST for second assignment
//
stmt_node = func_node->nodes[4].get();
TEST_ASSERT(stmt_node->id == ASTID::stmt);
stmt = &std::get<AstStmt>(stmt_node->value);
TEST_ASSERT(stmt->type == StmtType::call);
call = &std::get<AstFunctionCall>(stmt->value);
TEST_ASSERT(call->name == STDOP_FUNC_STR[underlay_cast(TOKENID::OP_EQ)]);
TEST_ASSERT(call->args[0].type == StmtType::varref);
TEST_ASSERT(std::get<AstSymRef>(call->args[0].value).name == "b");
TEST_ASSERT(check_second_assign(ctx, *stmt));
return true;
}
|
/*
* SPDX-FileCopyrightText: (C) 2020-2022 Daniel Nicoletti <dantti12@gmail.com>
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "action.h"
#include "application.h"
#include "config.h"
#include "context.h"
#include "cuteleeview_p.h"
#include "cutelystcutelee.h"
#include "response.h"
#include <cutelee/metatype.h>
#include <cutelee/qtlocalizer.h>
#include <QDirIterator>
#include <QString>
#include <QTranslator>
#include <QtCore/QLoggingCategory>
Q_LOGGING_CATEGORY(CUTELYST_CUTELEE, "cutelyst.cutelee", QtWarningMsg)
using namespace Cutelyst;
CUTELEE_BEGIN_LOOKUP(ParamsMultiMap)
return object.value(property);
CUTELEE_END_LOOKUP
CUTELEE_BEGIN_LOOKUP_PTR(Cutelyst::Request)
return object->property(property.toLatin1().constData());
CUTELEE_END_LOOKUP
CuteleeView::CuteleeView(QObject *parent, const QString &name)
: View(new CuteleeViewPrivate, parent, name)
{
Q_D(CuteleeView);
Cutelee::registerMetaType<ParamsMultiMap>();
Cutelee::registerMetaType<Cutelyst::Request *>(); // To be able to access it's properties
d->loader = std::make_shared<Cutelee::FileSystemTemplateLoader>();
d->engine = new Cutelee::Engine(this);
d->engine->addTemplateLoader(d->loader);
d->initEngine();
auto app = qobject_cast<Application *>(parent);
if (app) {
// make sure templates can be found on the current directory
setIncludePaths({app->config(QStringLiteral("root")).toString()});
// If CUTELYST_VAR is set the template might have become
// {{ Cutelyst.req.base }} instead of {{ c.req.base }}
d->cutelystVar = app->config(QStringLiteral("CUTELYST_VAR"), QStringLiteral("c")).toString();
app->loadTranslations(QStringLiteral("plugin_view_cutelee"));
} else {
// make sure templates can be found on the current directory
setIncludePaths({QDir::currentPath()});
}
}
QStringList CuteleeView::includePaths() const
{
Q_D(const CuteleeView);
return d->includePaths;
}
void CuteleeView::setIncludePaths(const QStringList &paths)
{
Q_D(CuteleeView);
d->loader->setTemplateDirs(paths);
d->includePaths = paths;
Q_EMIT changed();
}
QString CuteleeView::templateExtension() const
{
Q_D(const CuteleeView);
return d->extension;
}
void CuteleeView::setTemplateExtension(const QString &extension)
{
Q_D(CuteleeView);
d->extension = extension;
Q_EMIT changed();
}
QString CuteleeView::wrapper() const
{
Q_D(const CuteleeView);
return d->wrapper;
}
void CuteleeView::setWrapper(const QString &name)
{
Q_D(CuteleeView);
d->wrapper = name;
Q_EMIT changed();
}
void CuteleeView::setCache(bool enable)
{
Q_D(CuteleeView);
if (enable && d->cache) {
return; // already enabled
}
delete d->engine;
d->engine = new Cutelee::Engine(this);
if (enable) {
d->cache = std::make_shared<Cutelee::CachingLoaderDecorator>(d->loader);
d->engine->addTemplateLoader(d->cache);
} else {
d->cache = {};
d->engine->addTemplateLoader(d->loader);
}
d->initEngine();
Q_EMIT changed();
}
Cutelee::Engine *CuteleeView::engine() const
{
Q_D(const CuteleeView);
return d->engine;
}
void CuteleeView::preloadTemplates()
{
Q_D(CuteleeView);
if (!isCaching()) {
setCache(true);
}
const auto includePaths = d->includePaths;
for (const QString &includePath : includePaths) {
QDirIterator it(includePath, {QLatin1Char('*') + d->extension}, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
while (it.hasNext()) {
QString path = it.next();
path.remove(includePath);
if (path.startsWith(u'/')) {
path.remove(0, 1);
}
if (d->cache->canLoadTemplate(path)) {
d->cache->loadByName(path, d->engine);
}
}
}
}
bool CuteleeView::isCaching() const
{
Q_D(const CuteleeView);
return !!d->cache;
}
QByteArray CuteleeView::render(Context *c) const
{
Q_D(const CuteleeView);
QByteArray ret;
c->setStash(d->cutelystVar, QVariant::fromValue(c));
const QVariantHash stash = c->stash();
auto it = stash.constFind(QStringLiteral("template"));
QString templateFile;
if (it != stash.constEnd()) {
templateFile = it.value().toString();
} else {
if (c->action() && !c->action()->reverse().isEmpty()) {
templateFile = c->action()->reverse() + d->extension;
if (templateFile.startsWith(u'/')) {
templateFile.remove(0, 1);
}
}
if (templateFile.isEmpty()) {
c->error(QStringLiteral("Cannot render template, template name or template stash key not defined"));
return ret;
}
}
qCDebug(CUTELYST_CUTELEE) << "Rendering template" << templateFile;
Cutelee::Context gc(stash);
auto localizer = std::make_shared<Cutelee::QtLocalizer>(c->locale());
auto transIt = d->translators.constFind(c->locale());
if (transIt != d->translators.constEnd()) {
localizer.get()->installTranslator(transIt.value(), transIt.key().name());
}
auto catalogIt = d->translationCatalogs.constBegin();
while (catalogIt != d->translationCatalogs.constEnd()) {
localizer.get()->loadCatalog(catalogIt.value(), catalogIt.key());
++it;
}
gc.setLocalizer(localizer);
Cutelee::Template tmpl = d->engine->loadByName(templateFile);
if (tmpl->error() != Cutelee::NoError) {
c->res()->setBody(c->translate("Cutelyst::CuteleeView", "Internal server error."));
c->error(QLatin1String("Error while rendering template: ") + tmpl->errorString());
return ret;
}
QString content = tmpl->render(&gc);
if (tmpl->error() != Cutelee::NoError) {
c->res()->setBody(c->translate("Cutelyst::CuteleeView", "Internal server error."));
c->error(QLatin1String("Error while rendering template: ") + tmpl->errorString());
return ret;
}
if (!d->wrapper.isEmpty()) {
Cutelee::Template wrapper = d->engine->loadByName(d->wrapper);
if (tmpl->error() != Cutelee::NoError) {
c->res()->setBody(c->translate("Cutelyst::CuteleeView", "Internal server error."));
c->error(QLatin1String("Error while rendering template: ") + tmpl->errorString());
return ret;
}
Cutelee::SafeString safeContent(content, true);
gc.insert(QStringLiteral("content"), safeContent);
content = wrapper->render(&gc);
if (wrapper->error() != Cutelee::NoError) {
c->res()->setBody(c->translate("Cutelyst::CuteleeView", "Internal server error."));
c->error(QLatin1String("Error while rendering template: ") + tmpl->errorString());
return ret;
}
}
ret = content.toUtf8();
return ret;
}
void CuteleeView::addTranslator(const QLocale &locale, QTranslator *translator)
{
Q_D(CuteleeView);
Q_ASSERT_X(translator, "add translator to CuteleeView", "invalid QTranslator object");
d->translators.insert(locale, translator);
}
void CuteleeView::addTranslator(const QString &locale, QTranslator *translator)
{
addTranslator(QLocale(locale), translator);
}
void CuteleeView::addTranslationCatalog(const QString &path, const QString &catalog)
{
Q_D(CuteleeView);
Q_ASSERT_X(!path.isEmpty(), "add translation catalog to CuteleeView", "empty path");
Q_ASSERT_X(!catalog.isEmpty(), "add translation catalog to CuteleeView", "empty catalog name");
d->translationCatalogs.insert(catalog, path);
}
void CuteleeView::addTranslationCatalogs(const QMultiHash<QString, QString> &catalogs)
{
Q_D(CuteleeView);
Q_ASSERT_X(!catalogs.empty(), "add translation catalogs to GranteleeView", "empty QHash");
d->translationCatalogs.unite(catalogs);
}
QVector<QLocale> CuteleeView::loadTranslationsFromDir(const QString &filename, const QString &directory, const QString &prefix, const QString &suffix)
{
QVector<QLocale> locales;
if (Q_LIKELY(!filename.isEmpty() && !directory.isEmpty())) {
const QDir i18nDir(directory);
if (Q_LIKELY(i18nDir.exists())) {
const QString _prefix = prefix.isEmpty() ? QStringLiteral(".") : prefix;
const QString _suffix = suffix.isEmpty() ? QStringLiteral(".qm") : suffix;
const QStringList namesFilter = QStringList({filename + _prefix + QLatin1Char('*') + _suffix});
const QFileInfoList tsFiles = i18nDir.entryInfoList(namesFilter, QDir::Files);
if (Q_LIKELY(!tsFiles.empty())) {
locales.reserve(tsFiles.size());
for (const QFileInfo &ts : tsFiles) {
const QString fn = ts.fileName();
const int prefIdx = fn.indexOf(_prefix);
const QString locString = fn.mid(prefIdx + _prefix.length(), fn.length() - prefIdx - _suffix.length() - _prefix.length());
QLocale loc(locString);
if (Q_LIKELY(loc.language() != QLocale::C)) {
auto trans = new QTranslator(this);
if (Q_LIKELY(trans->load(loc, filename, _prefix, directory))) {
addTranslator(loc, trans);
locales.append(loc);
qCDebug(CUTELYST_CUTELEE) << "Loaded translations for locale" << loc << "from" << ts.absoluteFilePath();
} else {
delete trans;
qCWarning(CUTELYST_CUTELEE) << "Can not load translations for locale" << loc;
}
} else {
qCWarning(CUTELYST_CUTELEE) << "Can not load translations for invalid locale string" << locString;
}
}
locales.squeeze();
} else {
qCWarning(CUTELYST_CUTELEE) << "Can not find translation files for" << filename << "in directory" << directory;
}
} else {
qCWarning(CUTELYST_CUTELEE) << "Can not load translations from not existing directory:" << directory;
}
} else {
qCWarning(CUTELYST_CUTELEE) << "Can not load translations for empty file name or empty path.";
}
return locales;
}
void CuteleeViewPrivate::initEngine()
{
// Set also the paths from CUTELYST_PLUGINS_DIR env variable as plugin paths of cutelee engine
const QByteArrayList dirs = QByteArrayList{QByteArrayLiteral(CUTELYST_PLUGINS_DIR)} + qgetenv("CUTELYST_PLUGINS_DIR").split(';');
for (const QByteArray &dir : dirs) {
engine->addPluginPath(QString::fromLocal8Bit(dir));
}
engine->insertDefaultLibrary(QStringLiteral("cutelee_cutelyst"), new CutelystCutelee(engine));
}
#include "moc_cuteleeview.cpp"
|
#include<iostream>
#define s 5
void merges(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{int m=(l+r)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merges(arr, l, m, r);
}
}
using namespace std;
int main(){
int arr[s];
cout<<"enter array of "<<s<<" elements:";
for(int i=0;i<s;i++)
cin>>arr[i];
mergeSort(arr,0,s-1);
cout<<"\nsorted array is: ";
for(int i=0;i<s;i++)
cout<<arr[i]<<" ";
return 0;}
|
#pragma once
#include "stdafx.h"
#include <stdlib.h>
#include "Book.h"
#define MAX_LEN 20
#define amount_of_books 20 //поменять
class BookList
{
public:
BookList();//не используется
BookList(FILE * SourceFile);//конструктор от текстовго файла
void PrintAllInfo();
//void CleanList();
void ListByAuthor(char nameQ[MAX_LEN]);//вывод книг, отстортированных по параметрам
void ListByYear(int yearQ);
void ListByPublished(char nameQ[MAX_LEN]);
~BookList();
private:
Book * arrPtr[amount_of_books];
};
|
#ifndef OBJOBJECT_H
#define OBJOBJECT_H
#ifdef __APPLE__
#include <OpenGL/gl3.h>
#include <OpenGL/glext.h>
#include <OpenGL/gl.h> // Remove this line in future projects
#else
#include <GL/glew.h>
#endif
#include <GLFW/glfw3.h>
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vector>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
class OBJObject
{
private:
std::vector<unsigned int> indices, uvIndices, normalIndices;
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> uvs;
std::vector<glm::vec3> normals;
glm::mat4 toWorld;
public:
OBJObject(const char* filepath);
~OBJObject();
glm::mat4 getToWorld();
void parse(const char* filepath);
void draw(GLuint shaderProgram);
unsigned int loadTexture(std::vector<std::string> faces);
void translate(int key);
void zoom(double);
void rotate(int rotAng);
std::vector<std::string> texFace = {
"C:/Users/Matthew/Documents/_UCSD/CSE 167/CSE167Final/dark_wood_planks.ppm"
};
unsigned int texmap;
int angle;
float scale = 0.0f;
glm::vec3 dir;
float maxX;
float minX;
float maxY;
float minY;
float maxZ;
float minZ;
GLuint VBO, VAO, EBO, NBO, TBO;
GLuint uProjection, uModelview;
};
#endif
|
#include <xtl.h>
#include "xLCD.h"
#include "..\\main.h"
char X3LcdAnimIndex=0;
//*************************************************************************************************************
static void outb(unsigned short port, unsigned char data)
{
__asm
{
nop
mov dx, port
nop
mov al, data
nop
out dx,al
nop
nop
}
}
//*************************************************************************************************************
static unsigned char inb(unsigned short port)
{
unsigned char data;
__asm
{
mov dx, port
in al, dx
mov data,al
}
return data;
}
void xLCDSysInfo::SetBackLight( int iBLight )
{
m_iBackLight = iBLight;
}
//************************************************************************************************************************
//Set brightness level
//************************************************************************************************************************
void xLCDSysInfo::DisplaySetBacklight(unsigned char level)
{
outb(DISP_O_LIGHT, level);
}
bool xLCDSysInfo::Init()
{
int iOriginalLight=-1;
if (myDash.x3Settings.enabled && myDash.x3Settings.xLCD.enabled) {
myxLCD.SetRenderTextStatus(false);
bRunning = true;
while (bRunning) {
X3LcdAnimIndex=7;
// Backlight idea from XBMC
if (m_iBackLight != iOriginalLight)
{
// backlight setting changed
iOriginalLight=m_iBackLight;
DisplaySetBacklight(m_iBackLight);
}
myxLCD.DisplayProgressBarChars();
switch (pos) {
case 1:
myxLCD.RenderDriveStatus(2);
break;
case 2:
myxLCD.RenderDVDDriveStatus();
break;
case 3:
myxLCD.RenderDriveStatus(1);
break;
case 4:
myxLCD.RenderDriveStatus(6);
break;
case 5:
myxLCD.RenderDriveStatus(7);
break;
case 6:
myxLCD.RenderDriveStatus(3);
break;
case 7:
myxLCD.RenderDriveStatus(4);
break;
case 8:
myxLCD.RenderDriveStatus(5);
break;
}
if (pos == 8 )
pos =1;
else
pos++;
Sleep(1000);
}
myxLCD.SetRenderTextStatus(true);
return true;
}
return false;
}
void xLCD::SetBackLight( int iBLight )
{
m_iBackLight = iBLight;
}
//************************************************************************************************************************
// Init: setup the dispay
// Input: ()
//************************************************************************************************************************
bool xLCD::Init()
{
int iOriginalLight=-1;
if (myDash.x3Settings.enabled && myDash.x3Settings.xLCD.enabled) {
DisplayInit();
bDeviceRunning = true;
char tmpLine[21];
for (int i=0; i < 4 ; i++)
DisplayClearChars(0,i,20);
while ( bDeviceRunning )
{
if (bRenderText) {
// Lets slow things down a bit to stop it running away
Sleep(SCROLL_SPEED_IN_MSEC);
// Backlight idea from XBMC
if (m_iBackLight != iOriginalLight)
{
// backlight setting changed
iOriginalLight=m_iBackLight;
DisplaySetBacklight(m_iBackLight);
}
while(UpdateInProgress || UpdateLock)
Sleep(10); // Dont do anything while were updating whats on the LCD
// Stop any further updates from happening while were displaying the current LCD
UpdateLock = true;
DisplayBuildCustomChars();
for (int iLine = 0; iLine < (int)m_iRows; ++iLine)
{
if (RowData[iLine].Updated) {
DisplaySetPos(0,iLine);
if (strlen(RowData[iLine].text) > 20) {
strncpy(tmpLine,RowData[iLine].text,20);
tmpLine[20]='\0';
DisplayClearChars(0,iLine,20);
DisplayWriteString(tmpLine);
RowData[iLine].ScrollForwards = true;
RowData[iLine].StartPos = 0;
} else {
DisplayClearChars(0,iLine,20);
DisplayWriteString(RowData[iLine].text);
}
RowData[iLine].Updated = false;
}
if (strlen(RowData[iLine].text) > (unsigned int) m_iCols && !RowData[iLine].Updated ) {
DisplaySetPos(0,iLine);
if (strlen(RowData[iLine].text) > 20) {
// text is longer than the display
DisplaySetPos(0,iLine);
if (RowData[iLine].ScrollForwards && RowData[iLine].StartPos + 21 > (int) strlen(RowData[iLine].text) ) {
RowData[iLine].ScrollForwards = false;
} else if (!RowData[iLine].ScrollForwards && RowData[iLine].StartPos == 0 ) {
RowData[iLine].ScrollForwards = true;
}
DisplayClearChars(0,iLine,20);
if (RowData[iLine].ScrollForwards) {
strncpy(tmpLine,RowData[iLine].text + RowData[iLine].StartPos,20);
RowData[iLine].StartPos++;
} else {
strncpy(tmpLine,RowData[iLine].text + RowData[iLine].StartPos,20);
RowData[iLine].StartPos--;
}
tmpLine[20]='\0';
DisplayWriteString(tmpLine);
}
}
}
UpdateLock = false;
} else
Sleep(SCROLL_SPEED_IN_MSEC);
}
return true;
} else {
return false;
}
}
void xLCD::UpdateLine(int line, char *pointer)
{
// Does the line match what is there at the moment?
if (strcmp(pointer,myxLCD.RowData[line - 1].text) != 0) {
// Only update if something has changed :-)
while (UpdateLock || UpdateInProgress)
Sleep(10);
// Stop the screen
UpdateInProgress = true;
myxLCD.RowData[line -1].Updated = true;
strcpy(myxLCD.RowData[line -1].text,pointer);
UpdateInProgress = false;
}
}
void xLCD::UpdateDisplayText(char *pointer)
{
char szLCDText[255];
strcpy(szLCDText,pointer);
// Only update if something has changed :-)
while (UpdateLock || UpdateInProgress)
Sleep(10);
UpdateInProgress = true;
if (strcmp(szDisplayText,szLCDText) == 0)
return;
OutputDebugString ("Yup, clearing display\n");
strcpy(szDisplayText,szLCDText);
int RowId = 0;
char *token;
token = strtok( szLCDText, "\n");
while( token != NULL && RowId < 4)
{
// Erase everything and start again
strcpy(RowData[RowId].text,token);
RowData[RowId].ScrollForwards = true;
RowData[RowId].StartPos = 0;
RowData[RowId].Updated = true;
RowId++;
token = strtok( NULL, "\n");
}
while (RowId < 4 ) {
strcpy(RowData[RowId].text,"");
RowData[RowId].Updated = true;
RowData[RowId].StartPos = 0;
RowData[RowId].ScrollForwards = true;
RowId++;
}
UpdateInProgress = false;
}
//************************************************************************************************************************
// wait_us: delay routine
// Input: (wait in ~us)
//************************************************************************************************************************
void xLCD::wait_us(unsigned int value)
{
// 1 us = 1000msec
int iValue = value / 30;
if (iValue>10)
iValue = 10;
if (iValue)
Sleep(iValue);
}
void xLCD::DisplayInit()
{
//initialize GP/IO
outb(DISP_O_DAT, 0);
outb(DISP_O_CMD, 0);
outb(DISP_O_DIR_DAT, 0xFF);
outb(DISP_O_DIR_CMD, 0x07);
DisplayOut(DISP_FUNCTION_SET | DISP_DL_FLAG, INI); // 8-Bit Datalength if display is already initialized to 4 bit
Sleep(5);
DisplayOut(DISP_FUNCTION_SET | DISP_DL_FLAG, INI); // 8-Bit Datalength if display is already initialized to 4 bit
Sleep(5);
DisplayOut(DISP_FUNCTION_SET | DISP_DL_FLAG, INI); // 8-Bit Datalength if display is already initialized to 4 bit
Sleep(5);
DisplayOut(DISP_FUNCTION_SET, INI); // 4-Bit Datalength
Sleep(5);
DisplayOut(DISP_FUNCTION_SET | DISP_N_FLAG ,CMD); // 4-Bit Datalength, 2 Lines, Font 5x7, clear RE Flag
Sleep(5);
DisplayOut(DISP_CONTROL | DISP_D_FLAG ,CMD); // Display on
Sleep(5);
DisplayOut(DISP_CLEAR, CMD); // Display clear
Sleep(5);
DisplayOut(DISP_ENTRY_MODE_SET | DISP_ID_FLAG,CMD); // Cursor autoincrement
Sleep(5);
DisplayBuildCustomChars();
DisplaySetPos(0,0);
}
//************************************************************************************************************************
//Set brightness level
//************************************************************************************************************************
void xLCD::DisplaySetBacklight(unsigned char level)
{
outb(DISP_O_LIGHT, level);
}
void xLCD::RenderDVDDriveStatus()
{
LPCSTR szDirectory;
ULARGE_INTEGER u64Free, u64FreeTotal, u64Total;
// Make sure nothing else is writing to the screen
while (UpdateLock || UpdateInProgress)
Sleep(10);
UpdateLock = true;
if (bRenderText)
SetRenderTextStatus(false);
char displaytxt[21]="";
char blank[21]=" ";
DisplaySetPos(0,0);
XBOXDriveStatus.GetDriveState();
if ( XBOXDriveStatus.m_bTrayOpen ) {
strcat(displaytxt,"DVD: OPEN");
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
for (int i=1; i < 4 ; i++) {
DisplaySetPos(0,i);
DisplayWriteString(blank);
}
} else if( XBOXDriveStatus.m_iDVDType == XBI_DVD_INIT ) {
strcat(displaytxt,"DVD: INIT");
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
for (int i=1; i < 4 ; i++) {
DisplaySetPos(0,i);
DisplayWriteString(blank);
}
} else if( XBOXDriveStatus.m_iDVDType == XBI_DVD_EMPTY ) {
strcat(displaytxt,"DVD: EMPTY");
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
for (int i=1; i < 4 ; i++) {
DisplaySetPos(0,i);
DisplayWriteString(blank);
}
} else if( XBOXDriveStatus.m_iDVDType == XBI_DVD_XBOX ) {
strcat(displaytxt,"DVD: GAME");
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
DisplaySetPos(0,1);
strcpy(displaytxt,"Name: ");
strcat(displaytxt,xbeReader.GetXboxTitleName("D:\\Default.xbe"));
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
DisplaySetPos(0,2);
strcpy(displaytxt,"Size: ");
// Display game size
szDirectory = _T("D:\\");
if ( GetDiskFreeSpaceEx(szDirectory, &u64Free, &u64Total, &u64FreeTotal) )
{
string sSpace = XMakeNiceNumber(u64Total.QuadPart,_T('.'));
strcat(displaytxt,sSpace.c_str());
} else {
strcat(displaytxt,"Unknown");
}
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
for (int i=3; i < 4 ; i++) {
DisplaySetPos(0,i);
DisplayWriteString(blank);
}
} else if( XBOXDriveStatus.m_iDVDType == XBI_DVD_MOVIE ) {
strcat(displaytxt,"DVD: MOVIE");
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
for (int i=1; i < 4 ; i++) {
DisplaySetPos(0,i);
DisplayWriteString(blank);
}
} else {
strcat(displaytxt,"DVD: UNKNOWN");
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
// NEED TO CLEAR THE OTHER THREE LINES BUW THAT CAN WAIT
}
UpdateLock = false;
}
void xLCD::RenderDriveStatus(int iPartition)
{
LPCSTR szDirectory;
ULARGE_INTEGER u64Free, u64FreeTotal, u64Total;
// Make sure nothing else is writing to the screen
while (UpdateLock || UpdateInProgress)
Sleep(10);
UpdateLock = true;
if (bRenderText)
SetRenderTextStatus(false);
switch (iPartition) {
case 1:
szDirectory = _T("E:\\");
break;
case 2:
szDirectory = _T("C:\\");
break;
case 3:
szDirectory = _T("X:\\");
break;
case 4:
szDirectory = _T("Y:\\");
break;
case 5:
szDirectory = _T("Z:\\");
break;
case 6:
szDirectory = _T("F:\\");
break;
case 7:
szDirectory = _T("G:\\");
break;
default:
UpdateLock = false;
SetRenderTextStatus(true);
break;
}
char displaytxt[21]="";
char blank[21]=" ";
if ( GetDiskFreeSpaceEx(szDirectory, &u64Free, &u64Total, &u64FreeTotal) )
{
unsigned __int64 free = u64FreeTotal.QuadPart;
unsigned __int64 total = u64Total.QuadPart;
double percentage = (double)free/(double)total;
percentage *= 100.0;
if (percentage > 100.0f)
percentage = 100.0f;
DisplaySetPos(0,0);
char szpcnt[5] = "";
strcpy(displaytxt,szDirectory);
strcat(displaytxt," ");
itoa(100 - (int) percentage,szpcnt,10);
strcat(displaytxt,szpcnt);
strcat(displaytxt,"%");
while (strlen(displaytxt) < 10)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
DisplayProgressBar(100 - (int) percentage ,10);
DisplaySetPos(0,1);
strcpy(displaytxt,"Total : ");
string sSpace = XMakeNiceNumber(u64Total.QuadPart,_T('.'));
strcat(displaytxt,sSpace.c_str());
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
DisplaySetPos(0,2);
strcpy(displaytxt,"Used : ");
ULONGLONG used = u64Total.QuadPart - u64FreeTotal.QuadPart;
sSpace = XMakeNiceNumber(used, _T('.'));
strcat(displaytxt,sSpace.c_str());
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
DisplaySetPos(0,3);
strcpy(displaytxt,"Free : ");
sSpace = XMakeNiceNumber(u64FreeTotal.QuadPart,_T('.'));
strcat(displaytxt,sSpace.c_str());
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
} else {
DisplaySetPos(0,0);
strcpy(displaytxt,szDirectory);
strcat(displaytxt," ");
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
DisplaySetPos(0,1);
strcpy(displaytxt,"Not Used");
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
DisplayWriteString(displaytxt);
while (strlen(displaytxt) < 20)
strcat(displaytxt," ");
for (int i = 2; i < 4 ; i++) {
DisplaySetPos(0,i);
DisplayWriteString(blank);
}
}
UpdateLock = false;
return;
}
void xLCD::SetRenderTextStatus(bool bnewStatus)
{
// Lets clear the screen now matter what
for (int i = 0 ; i < 4 ; i++) {
DisplayClearChars(0,i,20);
if (bnewStatus == true )
RowData[i].Updated = true;
}
bRenderText = bnewStatus;
return;
}
//************************************************************************************************************************
// DisplaySetPos: sets cursor position
// Input: (row position, line number from 0 to 3)
//************************************************************************************************************************
void xLCD::DisplaySetPos(unsigned char pos, unsigned char line)
{
unsigned int cursorpointer;
cursorpointer = pos % m_iCols;
if (line == 0) {
cursorpointer += m_iRow1Addr;
}
if (line == 1) {
cursorpointer += m_iRow2Addr;
}
if (line == 2) {
cursorpointer += m_iRow3Addr;
}
if (line == 3) {
cursorpointer += m_iRow4Addr;
}
DisplayOut(DISP_DDRAM_SET | cursorpointer, CMD);
m_iActualpos = cursorpointer;
}
xLCD::xLCD() {
m_iRow1Addr = 0x00;
m_iRow2Addr = 0x40;
m_iRow3Addr = 0x14;
m_iRow4Addr = 0x54;
m_iRows = 4;
m_iCols = 20;
m_iActualpos = 0;
m_iBackLight = 32;
szDisplayText = (char *) malloc (255); // Max LCD buffer siez of 255
ZeroMemory(szDisplayText,255);
DisplayInit();
bneXgenSplash = true;
bRenderText = true;
}
//************************************************************************************************************************
// DisplayWriteFixText: write a fixed text to actual cursor position
// Input: ("fixed text like")
//************************************************************************************************************************
void xLCD::DisplayWriteFixtext(const char *textstring)
{
unsigned char c;
while (c = *textstring++) {
DisplayOut(c,DAT);
}
}
//************************************************************************************************************************
// DisplayWriteString: write a string to acutal cursor position
// Input: (pointer to a 0x00 terminated string)
//************************************************************************************************************************
void xLCD::DisplayWriteString(char *pointer)
{
/* display a normal 0x00 terminated string on the LCD display */
unsigned char c;
do {
c = *pointer;
if (c == 0x00)
break;
DisplayOut(c, DAT);
*pointer++;
} while(1);
}
//************************************************************************************************************************
// DisplayClearChars: clears a number of chars in a line and resets cursor position to it's startposition
// Input: (Startposition of clear in row, row number, number of chars to clear)
//************************************************************************************************************************
void xLCD::DisplayClearChars(unsigned char startpos , unsigned char line, unsigned char lenght)
{
int i;
DisplaySetPos(startpos,line);
for (i=0;i<lenght; i++){
DisplayOut(0x20,DAT);
}
DisplaySetPos(startpos,line);
}
//************************************************************************************************************************
// DisplayProgressBar: shows a grafic bar staring at actual cursor position
// Input: (percent of bar to display, lenght of whole bar in chars when 100 %)
//************************************************************************************************************************
void xLCD::DisplayProgressBar(unsigned char percent, unsigned char charcnt)
{
unsigned int barcnt100;
barcnt100 = charcnt * 5 * percent / 100;
int i;
int a;
for (i=1; i<=charcnt; i++) {
if (i<=(int)(barcnt100 / 5)){
DisplayOut(4,DAT);
}
else
{
if ( (i == (barcnt100 /5)+1) && (barcnt100 % 5 != 0) ){
a = (barcnt100 % 5)-1;
DisplayOut(a,DAT);
}
else{
DisplayOut(0x20,DAT);
}
}
}
}
//************************************************************************************************************************
//DisplayBuildCustomChars: load customized characters to character ram of display, resets cursor to pos 0
//************************************************************************************************************************
void xLCD::DisplayBuildCustomChars()
{
int I;
static char Bar0[] ={0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10};
static char Bar1[] ={0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18};
static char Bar2[] ={0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c};
static char REW[8][8]=
{
{0x00, 0x05, 0x0a, 0x14, 0x0a, 0x05, 0x00, 0x00},
{0x00, 0x0a, 0x14, 0x08, 0x14, 0x0a, 0x00, 0x00},
{0x00, 0x14, 0x08, 0x10, 0x08, 0x14, 0x00, 0x00},
{0x00, 0x08, 0x10, 0x00, 0x10, 0x08, 0x00, 0x00},
{0x00, 0x10, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00},
{0x00, 0x00, 0x01, 0x02, 0x01, 0x00, 0x00, 0x00},
{0x00, 0x01, 0x02, 0x05, 0x02, 0x01, 0x00, 0x00},
{0x00, 0x02, 0x05, 0x0a, 0x05, 0x02, 0x00, 0x00}
};
static char FF[8][8]=
{
{0x00, 0x14, 0x0a, 0x05, 0x0a, 0x14, 0x00, 0x00},
{0x00, 0x0a, 0x05, 0x02, 0x05, 0x0a, 0x00, 0x00},
{0x00, 0x05, 0x02, 0x01, 0x02, 0x05, 0x00, 0x00},
{0x00, 0x02, 0x01, 0x00, 0x01, 0x02, 0x00, 0x00},
{0x00, 0x01, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00},
{0x00, 0x00, 0x10, 0x08, 0x10, 0x00, 0x00, 0x00},
{0x00, 0x10, 0x08, 0x14, 0x08, 0x10, 0x00, 0x00},
{0x00, 0x08, 0x14, 0x0a, 0x14, 0x08, 0x00, 0x00}
};
static char Play[] ={0x00, 0x04, 0x06, 0x07, 0x07, 0x06, 0x04, 0x00};
static char Stop[] ={0x00, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x00};
static char Pause[]={0x00, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x00};
//static char Backslash[]={0x00, 0x10, 0x08, 0x04, 0x02, 0x01, 0x00, 0x00};
//static char Underscore[]={0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F};
DisplayOut(DISP_CGRAM_SET, CMD);
for(I=0;I<8;I++) DisplayOut(Bar0[I], DAT); // Bar0
for(I=0;I<8;I++) DisplayOut(Bar1[I], DAT); // Bar1
for(I=0;I<8;I++) DisplayOut(Bar2[I], DAT); // Bar2
for(I=0;I<8;I++) DisplayOut(REW[X3LcdAnimIndex][I], DAT); // REW
for(I=0;I<8;I++) DisplayOut(FF[X3LcdAnimIndex][I], DAT); // FF
for(I=0;I<8;I++) DisplayOut(Play[I], DAT); // Play
for(I=0;I<8;I++) DisplayOut(Stop[I], DAT); // Stop
for(I=0;I<8;I++) DisplayOut(Pause[I], DAT); // Pause
//for(I=0;I<8;I++) DisplayOut(Underscore[I], DAT); // Underscore
//for(I=0;I<8;I++) DisplayOut(Backslash[I], DAT); // Backslash
DisplayOut(DISP_DDRAM_SET, CMD);
X3LcdAnimIndex=(X3LcdAnimIndex+1) & 0x7;
}
void xLCD::DisplayProgressBarChars()
{
int I;
static char Bar0[] ={0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10};
static char Bar1[] ={0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18};
static char Bar2[] ={0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c};
static char Bar3[] ={0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e};
static char Bar4[] ={0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f};
DisplayOut(DISP_CGRAM_SET, CMD);
for(I=0;I<8;I++) DisplayOut(Bar0[I], DAT); // Bar0
for(I=0;I<8;I++) DisplayOut(Bar1[I], DAT); // Bar0
for(I=0;I<8;I++) DisplayOut(Bar2[I], DAT); // Bar0
for(I=0;I<8;I++) DisplayOut(Bar3[I], DAT); // Bar0
for(I=0;I<8;I++) DisplayOut(Bar4[I], DAT); // Bar0
DisplayOut(DISP_DDRAM_SET, CMD);
}
//************************************************************************************************************************
// DisplayOut: writes command or datas to display
// Input: (Value to write, token as CMD = Command / DAT = DATAs / INI for switching to 4 bit mode)
//************************************************************************************************************************
void xLCD::DisplayOut(unsigned char data, unsigned char command)
{
unsigned char cmd = 0;
static DWORD dwTick=0;
if ((GetTickCount()-dwTick) < 3)
{
Sleep(1);
}
dwTick=GetTickCount();
if (command & DAT)
{
cmd |= DISPCON_RS;
}
//outbut higher nibble
outb(DISP_O_DAT, data & 0xF0); // set Data high nibble
outb(DISP_O_CMD, cmd); // set RS if needed
outb(DISP_O_CMD, DISPCON_E | cmd); // set E
outb(DISP_O_CMD, cmd); // reset E
if ((command & INI) == 0)
{
// if it's not the init command, do second nibble
//outbut lower nibble
outb(DISP_O_DAT, (data << 4) & 0xF0); // set Data low nibble
outb(DISP_O_CMD, cmd); // set RS if needed
outb(DISP_O_CMD, DISPCON_E | cmd); // set E
outb(DISP_O_CMD, cmd); // reset E
if ((data & 0xFC) == 0)
{
// if command was a Clear Display
// or Cursor Home, wait at least 1.5 ms more
m_iActualpos = 0;
Sleep(2);
}
if ((command & DAT) == 0x02)
m_iActualpos++;
}
else
{
m_iActualpos = 0;
//wait_us(2500); // wait 2.5 msec
}
wait_us(30);
}
|
#include <iostream>
#include <unistd.h>
#include <string.h>
#include "Socket.h"
using namespace socketops;
Socket::Socket(int sockfd) :
sockfd_(sockfd)
{
}
int socketops::createNonBlockfd(sa_family_t family)
{
int sockfd = socket(family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
if(sockfd < 0)
{
std::cout << "socket create error" << std::endl;
}
return sockfd;
}
int socketops::createBlockfd(sa_family_t family)
{
int sockfd = socket(family, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
if(sockfd < 0)
{
std::cout << "socket create error" << std::endl;
}
return sockfd;
}
void socketops::Close(int fd)
{
int ret = close(fd);
if(ret < 0)
{
std::cout << "socket close error" << std::endl;
}
}
void socketops::Bind(int fd, const InetAddress& addr)
{
int ret = bind(fd, addr.addr(), sizeof(struct sockaddr));
if(ret < 0)
{
std::cout << "socket bind error" << std::endl;
}
}
int socketops::Accept(int fd, const InetAddress& peeraddr)
{
struct sockaddr_in addr;
socklen_t addrlen = sizeof(struct sockaddr_in);
int connfd = accept(fd, peeraddr.addr(), &addrlen);
if(connfd < 0)
{
std::cout << "socket accept error" << std::endl;
}
else
{
std::cout << "socket accept success" << std::endl;
char sendbuf[] = "111";
send(connfd, sendbuf, sizeof(sendbuf), 0);
}
return connfd;
}
void socketops::Listen(int fd)
{
int ret = listen(fd, SOMAXCONN);
if(ret < 0)
{
std::cout << "listen error" << std::endl;
}
}
struct sockaddr_in socketops::getLocalAddr(int fd)
{
struct sockaddr_in peeraddr;
memset(&peeraddr, 0, sizeof(peeraddr));
socklen_t addrlen = static_cast<socklen_t>(sizeof peeraddr);
if (::getpeername(fd, (struct sockaddr*)&peeraddr, &addrlen) < 0)
{
std::cout << "sockets::getPeerAddr error" << std::endl;
}
return peeraddr;
}
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int finish,start,n,f,h;
vector<int> prime,mark;//prime-звідки,mark=чи вже проходили
vector<vector<int>> edges;
int main()
{
cin>>n>>start>>finish;
prime.resize(n);
mark.resize(n);
edges.resize(n);
start--;
finish--;
for(int i=0;i<n-1;i++){
cin>>f>>h;
f--;
h--;
edges[f].push_back(h);
edges[h].push_back(f);
}
}
|
#include "driver.h"
#include "sim_lib.h"
#include <stdint.h>
void bias_add(int *a, int *b, int *out, int out_dim, int in_dim) {
DriverHandle dev = DriverAlloc();
DriverReset(dev, 1);
for (int64_t i = 0; i < out_dim; ++i) {
for (int64_t j = 0; j < in_dim; ++j) {
int64_t k = i * in_dim + j;
DriverWrite(dev, 0, 0, a[k]);
DriverWrite(dev, 1, 0, b[j]);
DriverRun(dev, 1);
out[k] = DriverRead(dev, 2, 0);
}
}
DriverDealloc(dev);
}
|
#include "mainwindow.h"
#include "adddlg.h"
#include "aboutdlg.h"
#include "savedlg.h"
#include "ui_mainwindow.h"
//bool isOpen = false;
bool isModified = false;
bool isNew = true;
QString lastFilename = "";
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle("TodoList");
iniUI();
mytimer = new QTimer();
iniSignalSlots();
mytimer->start(500);
}
MainWindow::~MainWindow()
{
delete ui;
delete mytimer;
}
void MainWindow::iniUI()
{
ui->tableWidget->setColumnCount(7);
//ui->tableWidget->setRowCount(5);
QStringList header;
header << ""
<< "状态"
<< "标题"
<< "内容"
<< "时间"
<< "";
ui->tableWidget->setHorizontalHeaderLabels(header);
//ui->tableWidget->horizontalHeader()->resizeSection(0, 50);
ui->tableWidget->horizontalHeader()->resizeSection(1, 36);
ui->tableWidget->horizontalHeader()->resizeSection(2, 170);
ui->tableWidget->horizontalHeader()->resizeSection(3, 320);
ui->tableWidget->horizontalHeader()->resizeSection(4, 150);
ui->tableWidget->horizontalHeader()->resizeSection(5, 70);
ui->tableWidget->setColumnHidden(0, true);
ui->tableWidget->setColumnHidden(6, true);
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
ui->tableWidget->horizontalHeader()->setSortIndicatorShown(true);
}
void MainWindow::iniSignalSlots()
{
connect(ui->tableWidget->verticalHeader(), SIGNAL(sectionDoubleClicked(int)), this, SLOT(modify(int)));
connect(ui->tableWidget->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(sort(int)));
connect(mytimer, SIGNAL(timeout()), this, SLOT(timeResponse()));
//connect(ui->tableWidget, SIGNAL())
}
void MainWindow::addList(int status, QStringList title_cont, QDateTimeEdit* timeedit)
{
int rowcount = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(rowcount);
QTableWidgetItem* checked = new QTableWidgetItem();
if (status == 0)
{
checked->setCheckState(Qt::Unchecked);
ui->tableWidget->setItem(rowcount, 0, new QTableWidgetItem("0"));
}
else
{
checked->setCheckState(Qt::Checked);
ui->tableWidget->setItem(rowcount, 0, new QTableWidgetItem("1"));
}
ui->tableWidget->setItem(rowcount, 1, checked);
ui->tableWidget->setItem(rowcount, 2, new QTableWidgetItem(title_cont[0]));
ui->tableWidget->setItem(rowcount, 3, new QTableWidgetItem(title_cont[1]));
//QDateTimeEdit* datetime = new QDateTimeEdit(dlg->getDateTime());
ui->tableWidget->setItem(rowcount, 4, new QTableWidgetItem(timeedit->dateTime().toString("yyyy/MM/dd hh:mm")));
QPushButton* Delete = new QPushButton();
Delete->setText("删除");
Delete->setFixedSize(69, 29);
QWidget* widget = new QWidget;
QHBoxLayout* layout = new QHBoxLayout;
layout->setSpacing(0);
layout->setMargin(0);
layout->addWidget(Delete);
widget->setLayout(layout);
ui->tableWidget->setCellWidget(rowcount, 5, widget);
connect(Delete, SIGNAL(clicked()), this, SLOT(deleteRow()));
//QDateTimeEdit* datetime = new QDateTimeEdit(dlg->getDateTime());
ui->tableWidget->setCellWidget(rowcount, 6, timeedit);
}
void MainWindow::on_actionAddlist_triggered()
{
AddDlg* dlg = new AddDlg;
dlg->setWindowTitle("添加日程");
dlg->exec();
if (dlg->getStatus())
{
QStringList res = dlg->getData();
if (res[0] != "" || res[1] != "")
{
isModified = true;
QDateTimeEdit* datetime = new QDateTimeEdit(dlg->getDateTime());
addList(0, res, datetime);
}
}
}
void MainWindow::on_actionAbout_triggered()
{
AboutDlg* dlg = new AboutDlg;
dlg->exec();
}
void MainWindow::modify(int index)
{
isModified = true;
QStringList content;
content.push_back(ui->tableWidget->item(index, 2)->text());
content.push_back(ui->tableWidget->item(index, 3)->text());
QDateTimeEdit* datetime = (QDateTimeEdit*)(ui->tableWidget->cellWidget(index, 6));
AddDlg* dlg = new AddDlg;
dlg->set(content, datetime->dateTime());
dlg->setWindowTitle("修改日程");
dlg->exec();
if (dlg->getStatus()) {
QStringList res = dlg->getData();
if (res[0] != "" || res[1] != "") {
ui->tableWidget->item(index, 2)->setText(res[0]);
ui->tableWidget->item(index, 3)->setText(res[1]);
QDateTimeEdit* datetime = new QDateTimeEdit(dlg->getDateTime());
ui->tableWidget->item(index, 4)->setText(datetime->dateTime().toString("yyyy/MM/dd hh:mm"));
ui->tableWidget->setCellWidget(index, 6, datetime);
}
}
}
void MainWindow::deleteRow()
{
QPushButton* btn = (QPushButton*)sender();
int x = btn->frameGeometry().x();
int y = btn->frameGeometry().y();
QModelIndex index = ui->tableWidget->indexAt(QPoint(x, y));
int row = index.row();
ui->tableWidget->removeRow(row);
}
void MainWindow::timeResponse()
{
for (int i = 0; i < ui->tableWidget->rowCount(); i++)
{
QDateTimeEdit* obj = (QDateTimeEdit*)(ui->tableWidget->cellWidget(i, 6));
QDateTime temp = obj->dateTime();
QDateTime cur = QDateTime::currentDateTime();
if (temp.date() == cur.date() &&
temp.time().hour() == cur.time().hour() &&
temp.time().minute() == cur.time().minute() &&
cur.time().second() < 4 &&
ui->tableWidget->item(i, 1)->checkState() == Qt::Unchecked)
{
QSound::play(":/sound/msg.wav");
break;
}
}
}
void MainWindow::on_tableWidget_cellChanged(int row, int column)
{
if (column == 1)
{
if (ui->tableWidget->item(row, column)->checkState() == Qt::Checked)
{
ui->tableWidget->item(row, 0)->setText("1");
}
else
{
ui->tableWidget->item(row, 0)->setText("0");
}
}
}
void MainWindow::sort(int index)
{
if (index == 2 || index == 3 || index == 4)
ui->tableWidget->sortByColumn(index);
else if (index == 1)
{
ui->tableWidget->sortByColumn(0);
}
}
QString MainWindow::on_actionImport_triggered()
{
QString fileName;
fileName = QFileDialog::getOpenFileName(this, tr("Open File"), tr(""), tr("Text File (*.todo)"));
if (fileName == "")
{
return "";
}
else
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::warning(this, tr("错误"), tr("打开文件失败"));
return "";
}
else
{
if (!file.isReadable())
{
QMessageBox::warning(this, tr("错误"), tr("该文件不可读"));
}
else
{
QTextStream textStream(&file);
QTextCodec* codec = QTextCodec::codecForName("UTF-8");
textStream.setCodec(codec);
while (!textStream.atEnd())
{
int status;
QStringList res;
QDateTime time;
QString temp = textStream.readLine();
status = temp.toInt();
temp = textStream.readLine();
res.push_back(temp);
temp = textStream.readLine();
res.push_back(temp);
temp = textStream.readLine();
time = QDateTime::fromString(temp, "yyyy/MM/dd hh:mm");
QDateTimeEdit* edit = new QDateTimeEdit(time);
addList(status, res, edit);
}
file.close();
//isOpen = true;
if (lastFilename == "")
isNew = true;
else
isNew = false;
//isNew = false;
isModified = true;
//lastFilename = fileName;
}
return fileName;
}
}
}
void MainWindow::on_actionOpen_triggered()
{
if (isModified)
{
SaveDlg* dlg = new SaveDlg();
dlg->exec();
if (dlg->getCancel())
{
return;
}
else if (dlg->getSave())
{
//将原文件保存
int ret = on_actionSave_triggered();
if (ret != 0)
return;
}
}
ui->tableWidget->clearContents();
ui->tableWidget->setRowCount(0);
QString name = on_actionImport_triggered();
if (name != "")
{
lastFilename = name;
isNew = false;
isModified = false;
QString title = lastFilename.section("/", -1);
setWindowTitle(title);
}
}
void MainWindow::on_actionNewFile_triggered()
{
if (isModified)
{
SaveDlg* dlg = new SaveDlg();
dlg->exec();
if (dlg->getCancel())
{
return;
}
else if (dlg->getSave())
{
//将原文件保存
int ret = on_actionSave_triggered();
if (ret != 0)
return;
}
}
setWindowTitle("TodoList");
ui->tableWidget->clearContents();
ui->tableWidget->setRowCount(0);
isNew = true;
//isOpen = true;
}
int MainWindow::on_actionSaveAs_triggered()
{
QFileDialog fileDialog;
QString str = fileDialog.getSaveFileName(this, tr("另存为"), "/新建事项", tr("TodoList File(*.todo)"));
if (str == "")
{
return 1;
}
QFile filename(str);
if (!filename.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::warning(this, tr("错误"), tr("打开文件失败"), QMessageBox::Ok);
return -1;
}
else
{
QTextStream textStream(&filename);
QTextCodec* codec = QTextCodec::codecForName("UTF-8");
textStream.setCodec(codec);
QString str;
for (int i = 0; i < ui->tableWidget->rowCount(); i++)
{
if (ui->tableWidget->item(i, 1)->checkState() == Qt::Checked)
str = "1";
else
str = "0";
textStream << str << endl;
textStream << ui->tableWidget->item(i, 2)->text() << endl
<< ui->tableWidget->item(i, 3)->text() << endl
<< ui->tableWidget->item(i, 4)->text() << endl;
}
//Last_FileContent = str;
}
//QMessageBox::information(this, "保存文件", "保存文件成功", QMessageBox::Ok);
filename.close();
isNew = false;
lastFilename = str;
isModified = false;
QString title = lastFilename.section("/", -1);
setWindowTitle(title);
return 0;
}
int MainWindow::on_actionSave_triggered()
{
if (isNew)
{
return on_actionSaveAs_triggered();
}
else
{
//if (isOpen)
QFile file(lastFilename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::warning(this, tr("警告"), tr("打开文件失败"));
return -1;
}
else
{
QTextStream textStream(&file);
QTextCodec* codec = QTextCodec::codecForName("UTF-8");
textStream.setCodec(codec);
QString str;
for (int i = 0; i < ui->tableWidget->rowCount(); i++)
{
if (ui->tableWidget->item(i, 1)->checkState() == Qt::Checked)
str = "1";
else
str = "0";
textStream << str << endl;
textStream << ui->tableWidget->item(i, 2)->text() << endl
<< ui->tableWidget->item(i, 3)->text() << endl
<< ui->tableWidget->item(i, 4)->text() << endl;
}
file.close();
isModified = false;
}
QString title = lastFilename.section("/", -1);
setWindowTitle(title);
return 0;
}
}
void MainWindow::closeEvent(QCloseEvent* event)
{
if (isModified)
{
SaveDlg* dlg = new SaveDlg();
dlg->exec();
if (dlg->getCancel())
{
event->ignore();
}
else if (dlg->getSave())
{
//将原文件保存
int ret = on_actionSave_triggered();
if (ret != 0)
event->ignore();
}
}
else
{
event->accept();
}
}
|
#include "matchit/core.h"
#include "matchit/patterns.h"
#include "matchit/expression.h"
using namespace matchit;
double relu(double value)
{
return match(value)(
// pattern(meet([](auto &&v) { return v >= 0; })) = [&] { return value; },
pattern(_ >= 0) = [&] { return value; },
pattern(_) = [] { return 0; });
}
int main()
{
printf("%f\n", relu(3));
return 0;
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTMUTABLEMESH_HPP_
#define TESTMUTABLEMESH_HPP_
#include <cxxtest/TestSuite.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <fstream>
#include "MutableMesh.hpp"
#include "TrianglesMeshReader.hpp"
#include "TrianglesMeshWriter.hpp"
#include "RandomNumberGenerator.hpp"
#include "PetscSetupAndFinalize.hpp"
#include "PetscTools.hpp"
#include "ArchiveOpener.hpp"
#include <cmath>
#include <vector>
class TestMutableMesh : public CxxTest::TestSuite
{
private:
template<unsigned DIM>
void EdgeIteratorTest(std::string meshFilename)
{
// Create a simple mesh
TrianglesMeshReader<DIM,DIM> mesh_reader(meshFilename);
MutableMesh<DIM,DIM> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
// Delete one of the nodes and hence an element
// to check that iterator skips deleted elements
// this causes element 0 to be deleted which is a good choice for coverage of the begin method
mesh.DeleteBoundaryNodeAt(0);
// Check that we can iterate over the set of edges
std::set< std::set<unsigned> > edges_visited;
for (typename MutableMesh<DIM,DIM>::EdgeIterator edge_iterator=mesh.EdgesBegin();
edge_iterator!=mesh.EdgesEnd();
++edge_iterator)
{
std::set<unsigned> node_pair;
node_pair.insert(edge_iterator.GetNodeA()->GetIndex());
node_pair.insert(edge_iterator.GetNodeB()->GetIndex());
TS_ASSERT_EQUALS(edges_visited.find(node_pair), edges_visited.end());
edges_visited.insert(node_pair);
}
// Set up expected node pairs
std::set< std::set<unsigned> > expected_node_pairs;
for (unsigned i=0; i<mesh.GetNumAllElements(); i++)
{
Element<DIM,DIM>* p_element = mesh.GetElement(i);
if (!p_element->IsDeleted())
{
for (unsigned j=0; j<DIM+1; j++)
{
for (unsigned k=0; k<DIM+1; k++)
{
unsigned node_A = p_element->GetNodeGlobalIndex(j);
unsigned node_B = p_element->GetNodeGlobalIndex(k);
if (node_A != node_B)
{
std::set<unsigned> node_pair;
node_pair.insert(node_A);
node_pair.insert(node_B);
expected_node_pairs.insert(node_pair);
}
}
}
}
}
TS_ASSERT_EQUALS(edges_visited, expected_node_pairs);
}
public:
void TestNodeIterator()
{
TrianglesMeshReader<2,3> mesh_reader("mesh/test/data/disk_in_3d");
MutableMesh<2,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
unsigned counter = 0;
for (AbstractTetrahedralMesh<2,3>::NodeIterator iter = mesh.GetNodeIteratorBegin();
iter != mesh.GetNodeIteratorEnd();
++iter)
{
unsigned node_index = (*iter).GetIndex();
TS_ASSERT_EQUALS(counter, node_index); // assumes the iterator will give node 0,1..,N in that order
counter++;
}
TS_ASSERT_EQUALS(counter, mesh.GetNumNodes());
mesh.DeleteNode(0);
mesh.DeleteNode(10);
mesh.DeleteNode(70);
unsigned another_counter = 0;
for (AbstractTetrahedralMesh<2,3>::NodeIterator iter = mesh.GetNodeIteratorBegin();
iter != mesh.GetNodeIteratorEnd();
++iter)
{
another_counter++;
}
TS_ASSERT_EQUALS(another_counter+3, counter)
TS_ASSERT_EQUALS(another_counter+3, mesh.GetNumAllNodes());
TS_ASSERT_EQUALS(another_counter, mesh.GetNumNodes());
}
void TestElementIterator()
{
TrianglesMeshReader<2,3> mesh_reader("mesh/test/data/disk_in_3d");
MutableMesh<2,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
unsigned counter = 0;
for (AbstractTetrahedralMesh<2,3>::ElementIterator iter = mesh.GetElementIteratorBegin();
iter != mesh.GetElementIteratorEnd();
++iter)
{
unsigned element_index = (*iter).GetIndex();
TS_ASSERT_EQUALS(counter, element_index); // assumes the iterator will give element 0,1..,N in that order
counter++;
}
TS_ASSERT_EQUALS(counter, mesh.GetNumElements());
}
void TestRescaleMeshFromBoundaryNode()
{
TrianglesMeshReader<1,1> mesh_reader("mesh/test/data/1D_0_to_1_10_elements");
MutableMesh<1,1> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
ChastePoint<1> updatedPoint(1.5);
mesh.RescaleMeshFromBoundaryNode(updatedPoint,10);
for (int i=0; i<11; i++)
{
TS_ASSERT_DELTA(mesh.GetNode(i)->GetPoint()[0], 1.5*(i/10.0), 0.001);
}
}
void Test1DSetPoint()
{
TrianglesMeshReader<1,1> mesh_reader("mesh/test/data/1D_0_to_1_10_elements");
MutableMesh<1,1> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
const int node_index = 3;
Node<1>* p_node = mesh.GetNode(node_index);
ChastePoint<1> point=p_node->GetPoint();
TS_ASSERT_DELTA(point[0], 0.3, 1e-6);
Element<1,1>* p_element;
Node<1>::ContainingElementIterator elt_iter = p_node->ContainingElementsBegin();
p_element = mesh.GetElement(*elt_iter);
c_matrix<double,1,1> jacobian;
double jacobian_det;
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.1, 1e-6);
p_element = mesh.GetElement(*++elt_iter);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.1, 1e-6);
// Move node 3 from 0.3 (between node 2 at 0.2 and node 4 at 0.4)
point.SetCoordinate(0, 0.25);
mesh.SetNode(node_index, point);
elt_iter = p_node->ContainingElementsBegin();
p_element = mesh.GetElement(*elt_iter);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.05, 1e-6);
p_element = mesh.GetElement(*++elt_iter);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.15, 1e-6);
// Move node 3 from 0.3 (between node 2 at 0.2 and node 4 at 0.4)
point.SetCoordinate(0, 0.201);
mesh.SetNode(node_index, point);
elt_iter = p_node->ContainingElementsBegin();
p_element = mesh.GetElement(*elt_iter);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.001, 1e-6);
p_element = mesh.GetElement(*++elt_iter);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.199, 1e-6);
// Move node 3 so that one element is empty
point.SetCoordinate(0, 0.200);
TS_ASSERT_THROWS_THIS(mesh.SetNode(node_index, point),
"Moving node caused an element to have a non-positive Jacobian determinant");
// Move node 3 so that one element is negative
point.SetCoordinate(0, 0.15);
TS_ASSERT_THROWS_THIS(mesh.SetNode(node_index, point),
"Moving node caused an element to have a non-positive Jacobian determinant");
// Move node 3 back (and recover)
point.SetCoordinate(0, 0.3);
mesh.SetNode(node_index, point);
elt_iter = p_node->ContainingElementsBegin();
p_element = mesh.GetElement(*elt_iter);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.1, 1e-6);
p_element = mesh.GetElement(*++elt_iter);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.1, 1e-6);
TS_ASSERT_EQUALS(mesh.IsMeshChanging(), true);
}
void Test2DSetPoint()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/disk_984_elements");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
const int node_index = 234;
const int boundary_node_index = 99;
Node<2>* p_node = mesh.GetNode(node_index);
// Just focus on one element
Element<2,2>* p_element;
Node<2>::ContainingElementIterator elt_iter = p_node->ContainingElementsBegin();
p_element = mesh.GetElement(*elt_iter);
ChastePoint<2> point = p_node->GetPoint();
TS_ASSERT_DELTA(point[0], 0.063497248392600097, 1e-6);
TS_ASSERT_DELTA(point[1], -0.45483180039309123, 1e-6);
c_matrix<double,2,2> jacobian;
double jacobian_det;
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.00907521, 1e-6);
// Nudge
point.SetCoordinate(0, 0.06);
mesh.SetNode(node_index, point);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.00861908, 1e-6);
// Nudge
point.SetCoordinate(0, 0.02);
mesh.SetNode(node_index, point);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.00340215, 1e-6);
// Nudge
point.SetCoordinate(0, -0.006);
mesh.SetNode(node_index, point);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 1.11485e-05, 1e-6);
// Nudge too far
point.SetCoordinate(0, -0.0065);
TS_ASSERT_THROWS_THIS(mesh.SetNode(node_index, point),
"Moving node caused an element to have a non-positive Jacobian determinant");
// Put it back
point.SetCoordinate(0, 0.063497248392600097);
mesh.SetNode(node_index, point);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.00907521, 1e-6);
// Now try to move a boundary node
p_node=mesh.GetNode(boundary_node_index);
ChastePoint<2> boundary_point = p_node->GetPoint();
TS_ASSERT_DELTA(boundary_point[0], 0.99211470130000001, 1e-6);
TS_ASSERT_DELTA(boundary_point[1], -0.12533323360000001, 1e-6);
Node<2>::ContainingBoundaryElementIterator b_elt_iter = p_node->ContainingBoundaryElementsBegin();
const BoundaryElement<1,2>* p_boundary_element = mesh.GetBoundaryElement(*b_elt_iter);
c_vector<double,2> weighted_dir;
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0628215, 1e-6);
boundary_point.SetCoordinate(0, 1.0);
mesh.SetNode(boundary_node_index, boundary_point);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0645268, 1e-6);
}
void TestMovingNodesIn3D()
{
TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/cube_136_elements");
MutableMesh<3,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double reference_volume = mesh.GetVolume();
const int interior_node_index = 34;
Node<3>* p_node = mesh.GetNode(interior_node_index);
// Just focus on one element
Element<3,3>* p_element = mesh.GetElement(*p_node->ContainingElementsBegin());
BoundaryElement<2,3>* p_boundary_element = mesh.GetBoundaryElement(*p_node->ContainingBoundaryElementsBegin());
ChastePoint<3> point = p_node->GetPoint();
TS_ASSERT_DELTA(point[0], 1, 1e-6);
TS_ASSERT_DELTA(point[1], 0.75, 1e-6);
TS_ASSERT_DELTA(point[2], 0.75, 1e-6);
c_matrix<double,3,3> jacobian;
c_vector<double,3> weighted_dir;
double jacobian_det;
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.03125, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.125, 1e-6);
// Check the mesh volume hasn't changed
TS_ASSERT_DELTA(mesh.GetVolume(), reference_volume, 1e-6);
// Nudge
point.SetCoordinate(2, 0.9);
mesh.SetNode(interior_node_index, point);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0125, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.05, 1e-6);
// Nudge
point.SetCoordinate(2, 0.999);
mesh.SetNode(interior_node_index, point);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.000125, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0005, 1e-6);
// Nudge
point.SetCoordinate(2, 0.99999);
mesh.SetNode(interior_node_index, point);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 1.25e-06, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 5.0e-06, 1e-6);
// Nudge too far
point.SetCoordinate(2, 1.0);
TS_ASSERT_THROWS_THIS(mesh.SetNode(interior_node_index, point),
"Moving node caused a boundary element to have a non-positive Jacobian determinant");
// Put it back
point.SetCoordinate(2, 0.75);
mesh.SetNode(interior_node_index, point);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.03125, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.125, 1e-6);
// Find exterior node
const int exterior_node_index = 0;
p_node = mesh.GetNode(exterior_node_index); // this exterior node is at (0,0,0)
point = p_node->GetPoint();
TS_ASSERT_DELTA(point[0], 0, 1e-6);
TS_ASSERT_DELTA(point[1], 0, 1e-6);
TS_ASSERT_DELTA(point[2], 0, 1e-6);
// Move exterior node
point.SetCoordinate(2, -10.0);
mesh.SetNode(exterior_node_index, point);
// Check mesh volume has changed
TS_ASSERT(fabs(mesh.GetVolume() - reference_volume) > 1e-1);
}
void Test1DMeshIn2DSetPoint()
{
TrianglesMeshReader<1,2> mesh_reader("mesh/test/data/semicircle_outline");
MutableMesh<1,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
const int boundary_node_index = 50;
Node<2>* p_node = mesh.GetNode(boundary_node_index);
// Just focus on one element
Element<1,2>* p_element = mesh.GetElement(*p_node->ContainingElementsBegin());
BoundaryElement<0,2>* p_boundary_element = mesh.GetBoundaryElement(*p_node->ContainingBoundaryElementsBegin());
ChastePoint<2> point = p_node->GetPoint();
TS_ASSERT_DELTA(point[0], -1.0, 1e-6);
TS_ASSERT_DELTA(point[1], 0.0, 1e-6);
c_vector<double,2> weighted_dir;
double jacobian_det;
mesh.GetWeightedDirectionForElement(p_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0628215, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 1.0, 1e-6);
// Nudge left
point.SetCoordinate(0, -1.5);
mesh.SetNode(boundary_node_index, point);
mesh.GetWeightedDirectionForElement(p_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.505885, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 1.0, 1e-6);
// Can't nudge right since an element flips chirality
point.SetCoordinate(0, -0.5);
TS_ASSERT_THROWS_THIS(mesh.SetNode(boundary_node_index, point),
"Moving node caused an subspace element to change direction");
// Put it back
point.SetCoordinate(0, -1.0);
mesh.SetNode(boundary_node_index, point);
mesh.GetWeightedDirectionForElement(p_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0628215, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 1.0, 1e-6);
}
void Test2DMeshIn3DSetPoint()
{
TrianglesMeshReader<2,3> mesh_reader("mesh/test/data/disk_in_3d");
MutableMesh<2,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
const int boundary_node_index = 99;
Node<3>* p_node = mesh.GetNode(boundary_node_index);
//Just focus on one element
Element<2,3>* p_element = mesh.GetElement(*p_node->ContainingElementsBegin());
BoundaryElement<1,3>* p_boundary_element = mesh.GetBoundaryElement(*p_node->ContainingBoundaryElementsBegin());
ChastePoint<3> point = p_node->GetPoint();
TS_ASSERT_DELTA(point[0], 0.99211470130000001, 1e-6);
TS_ASSERT_DELTA(point[1], -0.12533323360000001, 1e-6);
TS_ASSERT_DELTA(point[2], 0.0, 1e-6);
c_vector<double,3> weighted_dir;
double jacobian_det;
mesh.GetWeightedDirectionForElement(p_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0163772, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0628215, 1e-6);
// Nudge above the plane
point.SetCoordinate(2, 1e-2);
mesh.SetNode(boundary_node_index, point);
mesh.GetWeightedDirectionForElement(p_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0164274, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0636124, 1e-6);
// Nudge it back
point.SetCoordinate(2, 0.0);
mesh.SetNode(boundary_node_index, point);
mesh.GetWeightedDirectionForElement(p_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0163772, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0628215, 1e-6);
// Nudge below the plane
point.SetCoordinate(2, -1e-2);
mesh.SetNode(boundary_node_index, point);
mesh.GetWeightedDirectionForElement(p_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0164274, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0636124, 1e-6);
// Put it back
point.SetCoordinate(2, 0.0);
mesh.SetNode(boundary_node_index, point);
mesh.GetWeightedDirectionForElement(p_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0163772, 1e-6);
mesh.GetWeightedDirectionForBoundaryElement(p_boundary_element->GetIndex(), weighted_dir, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0628215, 1e-6);
// Can't nudge to the other side of the circle without changing handedness
point.SetCoordinate(0, -1.0);
point.SetCoordinate(2, 0.0);
TS_ASSERT_THROWS_THIS(mesh.SetNode(boundary_node_index, point),
"Moving node caused an subspace element to change direction");
}
void TestDeletingNodes()
{
TrianglesMeshReader<1,1> mesh_reader("mesh/test/data/1D_0_to_1_10_elements");
MutableMesh<1,1> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
Node<1>* p_old_rhs_node = mesh.GetNode(10);
Node<1>* p_old_lhs_node = mesh.GetNode(0);
MutableMesh<1,1>::BoundaryElementIterator b_elt_iter;
MutableMesh<1,1>::BoundaryNodeIterator b_node_iter;
// Delete the right end node
mesh.DeleteBoundaryNodeAt(10);
TS_ASSERT(p_old_rhs_node->IsDeleted());
// Number of *all* nodes & elements should be unchanged, even though we've deleted one,
// since this is the size of the vector, not the number of active nodes/elements.
// Yes, it's confusing.
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 11u);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), 10u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 10u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 9u);
// Check the boundary lists are correct
TS_ASSERT_EQUALS(mesh.GetNumBoundaryNodes(), 2u);
b_node_iter = mesh.GetBoundaryNodeIteratorBegin();
TS_ASSERT_EQUALS((*b_node_iter++)->GetIndex(), 0u);
TS_ASSERT_EQUALS((*b_node_iter++)->GetIndex(), 9u);
// NB: New boundary elements not added
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 1u);
b_elt_iter = mesh.GetBoundaryElementIteratorBegin();
TS_ASSERT_EQUALS((*b_elt_iter)->GetNumNodes(), 1u);
TS_ASSERT_EQUALS((*b_elt_iter++)->GetNode(0)->GetIndex(), 0u);
// Check the new boundary node
Node<1>* p_new_rhs_node = mesh.GetNode(9);
TS_ASSERT(p_new_rhs_node->IsBoundaryNode());
TS_ASSERT_EQUALS(p_new_rhs_node->GetNumContainingElements(), 1u);
// Only allowed to remove boundary nodes
TS_ASSERT_THROWS_THIS(mesh.DeleteBoundaryNodeAt(5)," You may only delete a boundary node ");
// Delete the left end node
mesh.DeleteBoundaryNodeAt(0);
TS_ASSERT(p_old_lhs_node->IsDeleted());
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 11u);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), 10u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 9u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 8u);
// Check the boundary lists are correct
TS_ASSERT_EQUALS(mesh.GetNumBoundaryNodes(), 2u);
b_node_iter = mesh.GetBoundaryNodeIteratorBegin();
TS_ASSERT_EQUALS((*b_node_iter++)->GetIndex(), 9u); // Note that the boundary is now
TS_ASSERT_EQUALS((*b_node_iter++)->GetIndex(), 1u); // 'reversed'
// NB: New boundary elements not added
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 0u);
// Check the new boundary node
Node<1>* p_new_lhs_node = mesh.GetNode(1);
TS_ASSERT(p_new_lhs_node->IsBoundaryNode());
TS_ASSERT_EQUALS(p_new_lhs_node->GetNumContainingElements(), 1u);
// Check the deleted element/node vectors
}
void TestDeleteNodePriorToReMesh()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/circular_fan");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
// Test it can also delete a boundary node
mesh.DeleteNodePriorToReMesh(0);
mesh.DeleteNodePriorToReMesh(11);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 100u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 98u);
NodeMap map(mesh.GetNumNodes());
mesh.ReMesh(map);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 98u);
}
void TestAddingAndDeletingNodes()
{
TrianglesMeshReader<1,1> mesh_reader("mesh/test/data/1D_0_to_1_10_elements");
MutableMesh<1,1> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
// Add a node at position 0.01
ChastePoint<1> new_point(0.01);
Element<1,1>* p_first_element = mesh.GetElement(0);
TS_ASSERT_THROWS_NOTHING(mesh.RefineElement(p_first_element, new_point));
TS_ASSERT_EQUALS(p_first_element->GetNode(1)->GetIndex(), 11u);
// Check the new element is index 10, by comparing nodes
TS_ASSERT_EQUALS(mesh.GetElement(10)->GetNode(0), p_first_element->GetNode(1));
// Delete the last node
mesh.DeleteBoundaryNodeAt(10);
// Add a node
ChastePoint<1> new_point2(0.55);
Element<1,1>* p_sixth_element = mesh.GetElement(5);
mesh.RefineElement(p_sixth_element, new_point2);
TS_ASSERT_EQUALS(p_sixth_element->GetNode(1)->GetIndex(), 10u);
// Check the new element is index 9, by comparing nodes
TS_ASSERT_EQUALS(mesh.GetElement(9)->GetNode(0), p_sixth_element->GetNode(1));
}
void Test1DBoundaryNodeMerger()
{
TrianglesMeshReader<1,1> mesh_reader("mesh/test/data/1D_0_to_1_1_element");
MutableMesh<1,1> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
TS_ASSERT_EQUALS(mesh.GetVolume(), 1.0);
TS_ASSERT_THROWS_THIS(mesh.MoveMergeNode(0, 1),
"These nodes cannot be merged since they are not neighbours on the boundary");
}
void Test1DNodeMerger()
{
TrianglesMeshReader<1,1> mesh_reader("mesh/test/data/1D_0_to_1_10_elements");
MutableMesh<1,1> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double length = mesh.GetVolume();
const int node_index = 3;
const int target_index = 4;
const int not_neighbour_index = 5;
// Cannot merge node 3 with node 5 since they are not neighbours
TS_ASSERT_THROWS_THIS(mesh.MoveMergeNode(node_index, not_neighbour_index),
"These nodes cannot be merged since they are not neighbours");
// Merge node 3 with node 4
mesh.MoveMergeNode(node_index, target_index);
Element<1,1>* p_element;
p_element = mesh.GetElement(2);
c_matrix<double,1,1> jacobian;
double jacobian_det;
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.2, 1e-6);
p_element = mesh.GetElement(3);
mesh.GetJacobianForElement(p_element->GetIndex(), jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0, 1e-6);
TS_ASSERT_DELTA(length, mesh.GetVolume(), 1e-6);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements() + 1);
}
void Test2DNodeMerger()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/disk_984_elements");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double area = mesh.GetVolume();
// Node 432 is supported by a non-convex region
// Node 206 is the sole reflex vertex in the region
// Node 172 is not feasible since it is neighbour to the reflex
const int node_index = 432;
const int target_index = 206;
const int not_neighbour_index = 204;
const int not_feasible_index = 172;
// Element 309 is shared by the moving node (432), the reflex node (206)
// the non-feasible node (172) - it will vanish
// Element 762 is shared by the moving node (432), some other node (205)
// the non-feasible node (172) - it will increase in size
c_matrix<double,2,2> jacobian;
double jacobian_det;
mesh.GetJacobianForElement(309, jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.00753493, 1e-6);
mesh.GetJacobianForElement(762, jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.00825652, 1e-6);
// Cannot merge since they are not neighbours
TS_ASSERT_THROWS_THIS(mesh.MoveMergeNode(node_index, not_neighbour_index),
"These nodes cannot be merged since they are not neighbours");
// Cannot merge since an element goes negative
// The element 763 shared by moving node (432), reflex node (206) and the
// other neighbour to the reflex node goes negative
TS_ASSERT_THROWS_THIS(mesh.MoveMergeNode(node_index, not_feasible_index, false),
"Moving node caused an element to have a non-positive Jacobian determinant");
// Added "crossReference=false" to stop elements deregistering
mesh.MoveMergeNode(node_index, target_index);
TS_ASSERT_DELTA(area, mesh.GetVolume(), 1e-6);
mesh.GetJacobianForElement(309, jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0, 1e-6);
mesh.GetJacobianForElement(762, jacobian, jacobian_det);
TS_ASSERT_DELTA(jacobian_det, 0.0126728, 1e-6);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements() + 2);
}
void Test3DNodeMerger()
{
TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/cube_1626_elements");
MutableMesh<3,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double volume = mesh.GetVolume();
const int node_index = 22; // in the middle
const int target_index = 310;
const int not_neighbour_index = 204;
const int not_feasible_index = 103;
TS_ASSERT_THROWS_THIS(mesh.MoveMergeNode(node_index, not_neighbour_index),
"These nodes cannot be merged since they are not neighbours");
TS_ASSERT_THROWS_THIS(mesh.MoveMergeNode(node_index, not_feasible_index, false),
"Moving node caused an element to have a non-positive Jacobian determinant");
// Added "crossReference=false" to stop elements deregistering
TS_ASSERT_THROWS_NOTHING( mesh.MoveMergeNode(node_index, target_index));
TS_ASSERT_DELTA(volume, mesh.GetVolume(), 1e-6);
//Ten elements share 22 and 310. See:
/* Element N1 N2 N3 N4
510 310 348 22 294
645 22 328 310 216
753 22 329 310 120
1164 295 310 22 175
1217 294 310 175 22
1251 310 336 328 22
1254 120 310 22 295
1357 310 336 22 193
1365 22 329 216 310
1484 310 348 193 22
*/
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements() + 10);
}
void Test2DBoundaryNodeMergerChangeArea()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/disk_984_elements");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double area = mesh.GetVolume();
double perim = mesh.GetSurfaceArea();
unsigned num_nodes = mesh.GetNumNodes();
unsigned num_elements = mesh.GetNumElements();
unsigned num_boundary_elements = mesh.GetNumBoundaryElements();
const int node_index = 19;
const int target_index = 20;
const int not_boundary_index = 400;
TS_ASSERT_THROWS_THIS(mesh.MoveMergeNode(node_index, not_boundary_index),"A boundary node can only be moved on to another boundary node");
mesh.MoveMergeNode(node_index, target_index);
TS_ASSERT_DELTA(area - mesh.GetVolume(), 1.24e-4, 1e-6);
TS_ASSERT_DELTA(perim - mesh.GetSurfaceArea(), 6.20e-5, 1e-7);
TS_ASSERT_EQUALS(num_nodes-mesh.GetNumNodes(), 1u);
TS_ASSERT_EQUALS(num_elements-mesh.GetNumElements(), 1u);
TS_ASSERT_EQUALS(num_boundary_elements-mesh.GetNumBoundaryElements(), 1u);
}
void Test2DBoundaryNodeMerger()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/2D_0_to_1mm_800_elements");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double area = mesh.GetVolume();
double perim = mesh.GetSurfaceArea();
int num_nodes = mesh.GetNumNodes();
unsigned num_elements = mesh.GetNumElements();
unsigned num_boundary_elements = mesh.GetNumBoundaryElements();
const int node_index = 9;
const int target_index = 10;
const int not_boundary_index = 31;
TS_ASSERT_THROWS_THIS(mesh.MoveMergeNode(node_index, not_boundary_index),"A boundary node can only be moved on to another boundary node");
mesh.MoveMergeNode(node_index, target_index);
TS_ASSERT_DELTA(area - mesh.GetVolume(), 0.00, 1e-6);
TS_ASSERT_DELTA(perim - mesh.GetSurfaceArea(), 0.00, 1e-7);
TS_ASSERT_EQUALS(num_nodes-mesh.GetNumNodes(), 1u);
TS_ASSERT_EQUALS(num_elements-mesh.GetNumElements(), 1u);
TS_ASSERT_EQUALS(num_boundary_elements-mesh.GetNumBoundaryElements(), 1u);
const int corner_index = 20;
const int corner_target_index = 19;
mesh.MoveMergeNode(corner_index, corner_target_index);
TS_ASSERT_DELTA(area - mesh.GetVolume(), 1.25e-5, 1e-7);
TS_ASSERT_DELTA(perim - mesh.GetSurfaceArea(), 2.92893e-3, 1e-7);
TS_ASSERT_EQUALS(num_nodes-mesh.GetNumNodes(), 2u);
TS_ASSERT_EQUALS(num_elements-mesh.GetNumElements(), 2u);
TS_ASSERT_EQUALS(num_boundary_elements-mesh.GetNumBoundaryElements(), 2u);
}
void Test3DBoundaryNodeMerger()
{
TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/cube_1626_elements");
MutableMesh<3,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double volume = mesh.GetVolume();
double surface = mesh.GetSurfaceArea();
unsigned num_nodes = mesh.GetNumNodes();
unsigned num_elements = mesh.GetNumElements();
unsigned num_boundary_elements = mesh.GetNumBoundaryElements();
const int node_index = 147;
const int target_index = 9;
//const int not_boundary_index=400;
mesh.MoveMergeNode(node_index, target_index);
TS_ASSERT_DELTA(volume, mesh.GetVolume(), 1e-7);
TS_ASSERT_DELTA(surface, mesh.GetSurfaceArea(), 1e-7);
TS_ASSERT_EQUALS(num_nodes-mesh.GetNumNodes(), 1u);
TS_ASSERT_EQUALS(num_elements-mesh.GetNumElements(), 3u);
TS_ASSERT_EQUALS(num_boundary_elements-mesh.GetNumBoundaryElements(), 2u);
// Can't move corner nodes since this forces some zero volume elements which aren't on the shared list
}
void TestCheckVoronoiDisk()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/disk_984_elements");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
TS_ASSERT_EQUALS(mesh.CheckIsVoronoi(), true);
}
void TestCheckVoronoiSquare()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/square_128_elements");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
TS_ASSERT_EQUALS(mesh.CheckIsVoronoi(), true);
}
void TestCheckCircularFan()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/circular_fan");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
TS_ASSERT_EQUALS(mesh.CheckIsVoronoi(5e-3), true);
}
void TestCheckMovingMesh()
{
MutableMesh<2,2> mesh;
mesh.ConstructRectangularMesh(1,1,false);
unsigned top_right=3;
Node<2>* p_node = mesh.GetNode(top_right);
ChastePoint<2> point = p_node->GetPoint();
TS_ASSERT_DELTA(point[0], 1.0, 1e-7);
TS_ASSERT_DELTA(point[1], 1.0, 1e-7);
TS_ASSERT_EQUALS(p_node->GetNumContainingElements(), 1u);
for (double x=1.1; x>=0.9; x-=0.01)
{
point.SetCoordinate(0,x);
point.SetCoordinate(1,x);
mesh.SetNode(top_right, point);
if (x >= 0.94)
{
TS_ASSERT_EQUALS(mesh.CheckIsVoronoi(0.15), true);
}
else
{
TS_ASSERT_EQUALS(mesh.CheckIsVoronoi(0.15), false);
}
}
}
void TestDeleteNodes()
{
MutableMesh<2,2> mesh;
mesh.ConstructRectangularMesh(2,3);
TS_ASSERT_EQUALS(mesh.GetVolume(), 6.0);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 12u);
// Delete from interior
mesh.DeleteNode(7);
TS_ASSERT_EQUALS(mesh.GetVolume(), 6.0);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 11u);
// Delete from edge
mesh.DeleteNode(5);
TS_ASSERT_EQUALS(mesh.GetVolume(), 6.0);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 10u);
// Delete from corner
mesh.DeleteNode(2);
TS_ASSERT_EQUALS(mesh.GetVolume(), 5.0);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 9u);
// Deleting a deleted node should throw an exception
TS_ASSERT_THROWS_THIS(mesh.DeleteNode(2),"Trying to delete a deleted node");
// Moving a deleted node should throw an exception
TS_ASSERT_THROWS_THIS(mesh.MoveMergeNode(2,1),"Trying to move a deleted node");
}
void TestDeleteNodeFails()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/HalfSquareWithExtraNode");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
TS_ASSERT_THROWS_THIS(mesh.DeleteNode(0),"Failure to delete node");
}
void TestMeshAddNodeAndReMeshMethod()
{
MutableMesh<2,2> mesh;
mesh.ConstructRectangularMesh(1, 1, false);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 4u);
TS_ASSERT_DELTA(mesh.GetNode(2u)->rGetLocation()[0], 0.0, 1e-7);
TS_ASSERT_DELTA(mesh.GetNode(2u)->rGetLocation()[1], 1.0, 1e-7);
TS_ASSERT_DELTA(mesh.GetNode(3u)->rGetLocation()[0], 1.0, 1e-7);
TS_ASSERT_DELTA(mesh.GetNode(3u)->rGetLocation()[1], 1.0, 1e-7);
TS_ASSERT_DELTA(mesh.GetNode(0u)->rGetLocation()[0], 0.0, 1e-7);
TS_ASSERT_DELTA(mesh.GetNode(0u)->rGetLocation()[1], 0.0, 1e-7);
TS_ASSERT_DELTA(mesh.GetNode(1u)->rGetLocation()[0], 1.0, 1e-7);
TS_ASSERT_DELTA(mesh.GetNode(1u)->rGetLocation()[1], 0.0, 1e-7);
// Test the add node method
c_vector<double,2> point;
point[0] = 2.0;
point[1] = 0.0;
Node<2>* p_node = new Node<2>(4u, point);
unsigned new_index = mesh.AddNode(p_node);
TS_ASSERT_EQUALS(new_index, 4u);
TS_ASSERT_DELTA(mesh.GetNode(4u)->rGetLocation()[0], 2.0, 1e-7);
TS_ASSERT_DELTA(mesh.GetNode(4u)->rGetLocation()[1], 0.0, 1e-7);
// Test the add node and ReMesh method
point[0] = 2.0;
point[1] = 1.0;
Node<2>* p_node2 = new Node<2>(5u, point);
NodeMap map(mesh.GetNumNodes());
new_index = mesh.AddNode(p_node2);
mesh.ReMesh(); // call the version of ReMesh which doesn't use a map
TS_ASSERT_EQUALS(new_index, 5u);
TS_ASSERT_DELTA(mesh.GetNode(5u)->rGetLocation()[0], 2.0, 1e-7);
TS_ASSERT_DELTA(mesh.GetNode(5u)->rGetLocation()[1], 1.0, 1e-7);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 4u);
}
void TestReindex()
{
MutableMesh<2,2> mesh;
mesh.ConstructRectangularMesh(10, 10);
unsigned num_old_nodes = mesh.GetNumNodes();
mesh.DeleteNode(50);
mesh.DeleteNode(0);
NodeMap map(num_old_nodes);
mesh.ReIndex(map);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), (unsigned)(num_old_nodes-2));
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), (unsigned)(num_old_nodes-2));
TS_ASSERT_EQUALS(map.GetSize(), num_old_nodes);
TS_ASSERT_EQUALS(map.IsDeleted(50), true);
TS_ASSERT_EQUALS(map.IsDeleted(0), true);
for (unsigned i=1; i<num_old_nodes; i++)
{
if (i<50)
{
TS_ASSERT_EQUALS(map.GetNewIndex(i), (unsigned)(i-1));
}
if (i>50)
{
TS_ASSERT_EQUALS(map.GetNewIndex(i), (unsigned)(i-2));
}
}
}
void TestReindex2dMeshIn3dSpace()
{
TrianglesMeshReader<2,3> mesh_reader("mesh/test/data/disk_in_3d");
MutableMesh<2,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
unsigned num_old_nodes = mesh.GetNumNodes();
mesh.DeleteNode(50);
mesh.DeleteNode(0);
NodeMap map(num_old_nodes);
mesh.ReIndex(map);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), (unsigned)(num_old_nodes-2));
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), (unsigned)(num_old_nodes-2));
TS_ASSERT_EQUALS(map.GetSize(), num_old_nodes);
TS_ASSERT_EQUALS(map.IsDeleted(50), true);
TS_ASSERT_EQUALS(map.IsDeleted(0), true);
for (unsigned i=1; i<num_old_nodes; i++)
{
if (i<50)
{
TS_ASSERT_EQUALS(map.GetNewIndex(i), (unsigned)(i-1));
}
if (i>50)
{
TS_ASSERT_EQUALS(map.GetNewIndex(i), (unsigned)(i-2));
}
}
}
void TestConstructFromNodes()
{
// Create mutable tetrahedral mesh which is Delaunay
std::vector<Node<3> *> nodes;
nodes.push_back(new Node<3>(0, true, 0.0, 0.0, 0.0));
nodes.push_back(new Node<3>(1, true, 1.0, 1.0, 0.0));
nodes.push_back(new Node<3>(2, true, 1.0, 0.0, 1.0));
nodes.push_back(new Node<3>(3, true, 0.0, 1.0, 1.0));
nodes.push_back(new Node<3>(4, false, 0.5, 0.5, 0.5));
MutableMesh<3,3> mesh(nodes);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 5u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 4u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 4u);
TS_ASSERT_DELTA(mesh.GetVolume(), 0.3333, 1e-4);
}
void TestEdgeIterator()
{
EdgeIteratorTest<3>("mesh/test/data/cube_2mm_12_elements");
EdgeIteratorTest<2>("mesh/test/data/square_4_elements");
EdgeIteratorTest<1>("mesh/test/data/1D_0_to_1_10_elements");
}
void TestDeleteElement()
{
TrianglesMeshReader<2,3> mesh_reader("mesh/test/data/disk_in_3d");
MutableMesh<2,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
unsigned num_old_nodes = mesh.GetNumNodes();
unsigned num_old_eles = mesh.GetNumElements();
mesh.DeleteElement(18);
mesh.DeleteElement(0);
TS_ASSERT_EQUALS(mesh.GetNumElements(), (unsigned)(num_old_eles-2));
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), (unsigned)(num_old_eles));
TS_ASSERT_EQUALS(mesh.GetNumNodes(), (unsigned)(num_old_nodes));
//Elements 18, 71, 74, 90, 380, 381 are the only elements using Node 241
mesh.DeleteElement(71);
mesh.DeleteElement(74);
mesh.DeleteElement(90);
mesh.DeleteElement(380);
mesh.DeleteElement(381);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), (unsigned)(num_old_nodes - 1));
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), (unsigned)(num_old_nodes));
NodeMap map(num_old_nodes);
mesh.ReIndex(map);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), (unsigned)(num_old_nodes - 1));
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), (unsigned)(num_old_nodes - 1));
TS_ASSERT_EQUALS(mesh.GetNumElements(), (unsigned)(num_old_eles - 7));
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), (unsigned)(num_old_eles - 7));
TS_ASSERT_EQUALS(map.GetSize(), num_old_nodes);
TS_ASSERT_EQUALS(map.IsDeleted(241), true);
}
void TestDeleteElement1DIn3D()
{
TrianglesMeshReader<1,3> mesh_reader("mesh/test/data/y_branch_3d_mesh");
MutableMesh<1,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 4u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 3u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 3u);
mesh.DeleteElement(1u);
NodeMap node_map(mesh.GetNumAllNodes());
mesh.ReIndex(node_map);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 3u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 2u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 2u);
//Check that nodes have been shuffled to fill in the indexing
TS_ASSERT_DELTA(mesh.GetNode(2u)->rGetLocation()[0], 1.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(2u)->rGetLocation()[1], -1.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(2u)->rGetLocation()[2], 0.0, 1e-6);
}
void TestArchiving()
{
FileFinder archive_dir("archive_mutable_mesh", RelativeTo::ChasteTestOutput);
std::string archive_file = "mutable_mesh.arch";
unsigned num_nodes;
unsigned num_elements;
unsigned total_num_nodes;
unsigned total_num_elements;
std::vector<c_vector<double,2> > node_locations;
std::vector<c_vector<unsigned,3> > element_nodes;
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/disk_984_elements");
AbstractTetrahedralMesh<2,2>* const p_mesh = new MutableMesh<2,2>;
p_mesh->ConstructFromMeshReader(mesh_reader);
// Create output archive
ArchiveOpener<boost::archive::text_oarchive, std::ofstream> arch_opener(archive_dir, archive_file);
boost::archive::text_oarchive* p_arch = arch_opener.GetCommonArchive();
NodeMap map(p_mesh->GetNumNodes());
static_cast<MutableMesh<2,2>* >(p_mesh)->ReMesh(map);
// Record values to test
for (MutableMesh<2,2>::NodeIterator it = static_cast<MutableMesh<2,2>* >(p_mesh)->GetNodeIteratorBegin();
it != static_cast<MutableMesh<2,2>* >(p_mesh)->GetNodeIteratorEnd();
++it)
{
// Mess with the locations of the nodes before archiving.
// checks that a modified version of the mesh is written to archive.
(it->rGetModifiableLocation())[0] += 0.1;
(it->rGetModifiableLocation())[1] += -0.1;
node_locations.push_back(it->rGetLocation());
}
for (MutableMesh<2,2>::ElementIterator it2 = static_cast<MutableMesh<2,2>* >(p_mesh)->GetElementIteratorBegin();
it2 != static_cast<MutableMesh<2,2>* >(p_mesh)->GetElementIteratorEnd();
++it2)
{
c_vector<unsigned, 3> nodes;
for (unsigned i=0; i<3; i++)
{
nodes[i]=it2->GetNodeGlobalIndex(i);
}
element_nodes.push_back(nodes);
}
num_nodes = p_mesh->GetNumNodes();
num_elements = p_mesh->GetNumElements();
total_num_nodes = p_mesh->GetNumAllNodes();
total_num_elements = p_mesh->GetNumAllElements();
(*p_arch) << p_mesh;
delete p_mesh;
}
{
// Should archive the most abstract class you can to check boost knows what individual classes are.
// (but here AbstractMesh doesn't have the methods below).
AbstractTetrahedralMesh<2,2>* p_mesh2;
// Create an input archive
ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(archive_dir, archive_file);
boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive();
// restore from the archive
(*p_arch) >> p_mesh2;
// Check we have the right number of nodes & elements
TS_ASSERT_EQUALS(num_nodes, p_mesh2->GetNumNodes());
TS_ASSERT_EQUALS(num_elements, p_mesh2->GetNumElements());
TS_ASSERT_EQUALS(total_num_nodes, p_mesh2->GetNumAllNodes());
TS_ASSERT_EQUALS(total_num_elements, p_mesh2->GetNumAllElements());
// Test recorded node locations
unsigned counter = 0;
for (MutableMesh<2,2>::NodeIterator it = static_cast<MutableMesh<2,2>* >(p_mesh2)->GetNodeIteratorBegin();
it != static_cast<MutableMesh<2,2>* >(p_mesh2)->GetNodeIteratorEnd();
++it)
{
TS_ASSERT_DELTA(node_locations[counter][0], it->rGetLocation()[0], 1e-9);
TS_ASSERT_DELTA(node_locations[counter][1], it->rGetLocation()[1], 1e-9);
counter++;
}
counter = 0;
// Test each element contains the correct nodes.
for (MutableMesh<2,2>::ElementIterator it2 = static_cast<MutableMesh<2,2>* >(p_mesh2)->GetElementIteratorBegin();
it2 != static_cast<MutableMesh<2,2>* >(p_mesh2)->GetElementIteratorEnd();
++it2)
{
for (unsigned i=0; i<3; i++)
{
TS_ASSERT_EQUALS(element_nodes[counter][i],it2->GetNodeGlobalIndex(i));
}
counter++;
}
delete p_mesh2;
}
}
};
#endif /*TESTMUTABLEMESH_HPP_*/
|
/*
Author: Nayeemul Islam Swad
Idea:
- We'll use divide and conquer method.
- For the merge process, we intially set `max_diff` = d[mid + 1] - d[mid].
Then as we're moving our left/right pointers L/R, we compare
diff(d[L], d[L + 1]) with diff(d[R], d[R - 1]) and whichever one is
smaller, we go that way, updating `max_diff` accordingly.
- Also, as we're moving our two pointers to left or right, we also
maintain minimum prefix sum `prefL` for the left pointer and maximum
prefix sum `prefR` for the right pointer. So, as we're moving the
pointers, the best possible gain for the current position of the
two pointers would be (prefR - prefL - max_diff * max_diff).
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
#define x first
#define y second
#ifdef LOCAL
#include "debug.h"
#endif
const int N = int(3e5) + 10;
int n;
ll a;
ll d[N], c;
ll pref[N];
ll solve(int L, int R) {
if (L == R) return max(0LL, pref[L] - pref[L - 1]);
ll ret = 0LL;
int mid = (L + R) / 2;
ret = max(ret, solve(L, mid));
ret = max(ret, solve(mid + 1, R));
int ptrL = mid, ptrR = mid + 1;
ll diff = 0;
ll prefL = pref[mid], prefR = pref[mid];
while (L <= ptrL || ptrR <= R) {
if (R < ptrR || (L <= ptrL && (d[ptrL + 1] - d[ptrL] <= d[ptrR] - d[ptrR - 1]))) {
prefL = min(prefL, pref[ptrL - 1]);
diff = max(diff, d[ptrL + 1] - d[ptrL]);
ptrL--;
}
else {
prefR = max(prefR, pref[ptrR]);
diff = max(diff, d[ptrR] - d[ptrR - 1]);
ptrR++;
}
ret = max(ret, prefR - prefL - diff * diff);
};
return ret;
}
int main() {
#ifdef LOCAL
freopen("in", "r", stdin);
freopen("out", "w", stdout);
#endif
scanf("%d %lld", &n, &a);
for (int i = 1; i <= n; i++) {
scanf("%lld %lld", &d[i], &c);
c = a - c;
pref[i] = pref[i - 1] + c;
}
printf("%lld\n", solve(1, n));
return 0;
}
|
#pragma once
#include "WorldObject.h"
/*! \brief
* Draws the rounded edges when we generate a turn
*/
class Curve : public WorldObject
{
private:
void DrawObject();
int turn; /*!< The rotation of the crossing: 1 -> right, 2 -> left, 3 -> both */
public:
Curve(int TURN);
~Curve();
};
|
#include <iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t > 0)
{
int a, b;
cin >> a >> b;
int arr[a];
int res = 0;
for (int i = 0; i < a; i++)
{
cin >> arr[i];
res += arr[i] / b;
}
cout << res << endl;
t--;
}
return 0;
}
|
#include "protoc2rcfcomm.h"
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/command_line_interface.h>
#include <boost/algorithm/string.hpp>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
namespace google {
namespace protobuf {
namespace compiler {
bool GeneratorRcfServiceDefFile( const string& sFileBaseName, const string& sServiceName, const ServiceDescriptor* sd )
{
//generator sk_servicedef.h
string sServiceDefTemplateFileName = PROJ_ROOT"/t/tserver/SK___t__servicedef.h";
string sServiceDefOutputFileName = "SK___t__servicedef.h";
boost::algorithm::replace_all(sServiceDefOutputFileName, "__t__", sFileBaseName);
ifstream in(sServiceDefTemplateFileName.c_str());
if( !in )
{
cerr << sServiceDefTemplateFileName<< " Error opening input stream" << endl;
return false;
}
if( access(sServiceDefOutputFileName.c_str(), 04 ) ==0 )
{
cout<<sServiceDefOutputFileName.c_str()<<" has existed, skip~~~~~"<<endl;
return false;
}
ofstream out(sServiceDefOutputFileName.c_str());
char pcBuf[32*1024];
memset(pcBuf, 0, sizeof(pcBuf) );
in.read(pcBuf, sizeof(pcBuf));
string sBuf = pcBuf;
boost::algorithm::replace_all(sBuf, "__t__", sFileBaseName);
boost::algorithm::replace_all(sBuf, "__T__", sServiceName);
string sRcfMethods;
for( int j=0; j<sd->method_count(); j++ )
{
const MethodDescriptor *md = sd->method(j);
sRcfMethods += "\tRCF_METHOD_R2(int, "+string(md->name())+", const "+md->input_type()->name()+"&, std::string&);";
if( j != sd->method_count()-1)
{
sRcfMethods+="\n\n";
}
printf("method %d , name %s, input_type %s, output_type %s\n",
j, md->name().c_str(), md->input_type()->name().c_str(),
md->output_type()->name().c_str());
}
boost::algorithm::replace_all(sBuf, "__T_MOTHOD_P__", sRcfMethods);
cout<<__func__<<endl;
out.write( sBuf.c_str(), sBuf.size() );
return true;
}
bool GeneratorRcfMakefile( const string& sFileBaseName, const string& sServiceName, const ServiceDescriptor* sd )
{
string sServiceTemplateFileName = PROJ_ROOT"/t/tserver/makefile";
string sServiceOutputFileName = "makefile";
boost::algorithm::replace_all(sServiceOutputFileName, "__t__", sFileBaseName);
ifstream in(sServiceTemplateFileName.c_str());
if( !in )
{
cerr << sServiceTemplateFileName<< " Error opening input stream" << endl;
return false;
}
if( access(sServiceOutputFileName.c_str(), 04 ) ==0 )
{
cout<<sServiceOutputFileName.c_str()<<" has existed, skip~~~~~"<<endl;
return false;
}
ofstream out(sServiceOutputFileName.c_str());
char pcBuf[32*1024];
memset(pcBuf, 0, sizeof(pcBuf) );
in.read(pcBuf, sizeof(pcBuf));
string sBuf = pcBuf;
boost::algorithm::replace_all(sBuf, "__t__", sFileBaseName);
boost::algorithm::replace_all(sBuf, "__T__", sServiceName);
cout<<__func__<<endl;
out.write( sBuf.c_str(), sBuf.size() );
return true;
}
bool GeneratorRcfSimpleFile( const string& sTFilePath, const string& sOutputFilePath,
const string& sFileBaseName, const string& sServiceName, const ServiceDescriptor* sd )
{
string sServiceTemplateFileName = sTFilePath;
string sServiceOutputFileName = sOutputFilePath;
boost::algorithm::replace_all(sServiceOutputFileName, "__t__", sFileBaseName);
ifstream in(sServiceTemplateFileName.c_str());
if( !in )
{
cerr << "Error opening input stream" << endl;
return false;
}
if( access(sServiceOutputFileName.c_str(), 04 ) ==0 )
{
cout<<sServiceOutputFileName.c_str()<<" has existed, skip~~~~~"<<endl;
return false;
}
ofstream out(sServiceOutputFileName.c_str());
char pcBuf[32*1024];
memset(pcBuf, 0, sizeof(pcBuf) );
in.read(pcBuf, sizeof(pcBuf));
string sBuf = pcBuf;
boost::algorithm::replace_all(sBuf, "__t__", sFileBaseName);
boost::algorithm::replace_all(sBuf, "__T__", sServiceName);
cout<<__func__<<endl;
out.write( sBuf.c_str(), sBuf.size() );
return true;
}
}}}
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef FLUXCRYPTO_BYTECIPHER_H
#define FLUXCRYPTO_BYTECIPHER_H
#include <stdint.h>
#include <flux/Object>
namespace flux {
namespace crypto {
class ByteCipher: public Object
{
public:
virtual uint8_t encode(uint8_t p) = 0;
virtual uint8_t decode(uint8_t c) = 0;
};
}} // namespace flux::crypto
#endif // FLUXCRYPTO_BYTECIPHER_H
|
#include<cstdio>
#include<iostream>
using namespace std;
int main()
{
long long n;
while(~scanf("%lld",&n))
cout << n/2+1 << endl;
return 0;
}
|
#pragma once
class GenjiboState
{
public:
GenjiboState();
~GenjiboState();
};
|
#include<bits/stdc++.h>
using namespace std;
const int N=10000010;
int prime[N],cnt;
bool vis[N];
int m,n,tmp;
void getprime(int n)
{
vis[1]=true;
for(int i=2;i<=n;i++)
{
if(!vis[i])
{
prime[++cnt]=i;
}
for(int j=1;j<=cnt;j++)
{
int v=i*prime[j];
if(v>n) break;
vis[v]=true;
}
}
}
int main()
{
scanf("%d",&n);
getprime(n);
scanf("%d",&m);
while(m--)
{
scanf("%d",&tmp);
if(vis[tmp]) puts("No");
else puts("Yes");
}
}
|
#include <iostream>
using namespace std;
void main()
{
double N, r, area;
cin >> N;
r = N / 2 / 3.14;
area = r*r*3.14;
cout << fixed;
cout.precision(0);
cout << area;
}
|
#pragma once
/* Common */
#pragma region Common
#include <vector>
#include <cassert>
#include <stdexcept>
#include <chrono>
#include <string>
#pragma endregion
/* Core */
#pragma region Core
#include <windows.h>
#include <wrl.h> //for ComPtr smart pointers for DXGI and D3D12 "objects
#include "Debuger.h"
#pragma endregion
/* Graphics */
#pragma region Graphics
#include <d3d12.h> //D3D12 header
#include <dxgi1_4.h> //DXGI interfaces "fundemental D3D12 Objects"
#include <D3Dcompiler.h> //for runtime shader compilation
#include <DirectXMath.h>
#include "d3dx12.h"
#pragma endregion
/* Audio */
#pragma region Audio
#include <dsound.h>
#pragma endregion
/* Physics */
#pragma region Physics
#include "RigidBody.h"
#pragma endregion
/* Resources */
#pragma region Resources
#include "resource.h"
#pragma endregion
|
#include "MCEnergySmearing.h"
#include "base/Detector_t.h"
#include "tree/TCluster.h"
#include "TRandom.h"
using namespace std;
using namespace ant;
using namespace ant::calibration;
MCEnergySmearing::MCEnergySmearing(Detector_t::Type_t det, double scale, double smear):
ReconstructHook::Clusters (), detector(det), scale_factor(scale), smearing(smear)
{}
MCEnergySmearing::~MCEnergySmearing()
{}
void MCEnergySmearing::ApplyTo(ReconstructHook::Base::clusters_t& clusters)
{
auto myclusters = clusters.find(detector);
if(myclusters == clusters.end())
return;
for(auto& cluster : myclusters->second) {
Smear(cluster);
}
}
void MCEnergySmearing::Smear(TCluster& cluster) const
{
cluster.Energy = gRandom->Gaus(cluster.Energy*scale_factor, smearing);
}
|
#include <bits/stdc++.h>
#include <cassert>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define ok() puts(ok?"Yes":"No");
#define chmax(x,y) x = max(x,y)
#define chmin(x,y) x = min(x,y)
using namespace std;
using ll = long long;
using vi = vector<int>;
using vll = vector<ll>;
using ii = pair<int, int>;
using vvi = vector<vi>;
using vii = vector<ii>;
using gt = greater<int>;
using minq = priority_queue<int, vector<int>, gt>;
using P = pair<ll,ll>;
const ll LINF = 1e18L + 1;
const int INF = 1e9 + 1;
//clang++ -std=c++11 -stdlib=libc++
// abc106d
int main() {
int n, m, q; cin >> n >> m >> q;
vvi a(n+1, vi(n+1));
rep(i, m) {
int l,r; cin >> l >> r;
a[l][r]++;
}
vvi sum(n+1, vi(n+1, 0));
rep(l, n+1) {
rep(r, n) {
sum[l][r+1] += sum[l][r] + a[l][r+1];
}
}
// for (int i = 1; i <= n; i++) {
// for (int j = 1; j <= n; j++) sum[i][j] = sum[i][j - 1] + a[i][j];
// }
auto solve = [&] {
int l,r; cin >> l >> r;
int ans = 0;
for (int i=l; i<=r; i++) ans += sum[i][r] - sum[i][l-1];
cout << ans << endl;
};
rep(i,q) solve();
return 0;
}
|
#pragma once
#ifdef DLLEXPORT
#define EMAIL_DLL __declspec(dllexport)
#else
#define EMAIL_DLL __declspec(dllimport)
#endif
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <experimental/filesystem>
#include "Data.h"
namespace fs = std::experimental::filesystem;
using namespace std;
class EMAIL_DLL EmailDLL
{
public:
EmailDLL();
~EmailDLL();
public:
void run(string dir);
string print();
void save();
bool check_mail_validation(string s, Data* D);
private:
vector<Data> Result;
};
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long int a[40];
a[0] = 1;
for(int i=1; i<40; i++) a[i] = a[i-1]*2;
long long int t;
cin>>t;
int j;
for(int i=0; i<40; i++)
{
long long int v = 3*(a[i+1]-1);
if(v>=t)
{
j = i;
break;
}
}
long long int ans = 3*a[j+1]-t-2;
cout<<ans<<endl;
}
|
class Solution {
public:
bool buddyStrings(string A, string B) {
if(A.size()!=B.size())
return false;
int count_diff=0;
int loc_1=-1;
int loc_2=-1;
int mem[26]={0};
for (int i=0;i<A.size();i++)
{
mem[A[i]-97]++;
if (A[i]!=B[i])
{
count_diff++;
if(count_diff>2)
return false;
if(loc_1 == -1 && loc_2 == -1)
loc_1 = i;
else if(loc_1 != -1 && loc_2 == -1)
loc_2=i;
}
}
if (count_diff!=2)
{
if(count_diff==0)
{
for (int i = 0; i<26;i++)
{
if(mem[i]>=2)
return true;
}
return false;
}
else
return false;
}
else
{
string temp = A;
temp[loc_1] = A[loc_2];
temp[loc_2] = A[loc_1];
if(temp==B)
return true;
else
return false;
}
}
};
|
//===-- MICmnStreamStdinLinux.cpp --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//++
// File: MIUtilStreamStdin.cpp
//
// Overview: CMICmnStreamStdinLinux implementation.
//
// Environment: Compilers: Visual C++ 12.
// gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
// Libraries: See MIReadmetxt.
//
// Copyright: None.
//--
// Third Party Headers:
#if !defined(_MSC_VER)
#include <sys/select.h>
#include <unistd.h>
#include <termios.h>
#include <sys/ioctl.h>
#endif // !defined( _MSC_VER )
#include <string.h> // For std::strerror()
// In-house headers:
#include "MICmnStreamStdinLinux.h"
#include "MICmnLog.h"
#include "MICmnResources.h"
#include "MIUtilSingletonHelper.h"
//++ ------------------------------------------------------------------------------------
// Details: CMICmnStreamStdinLinux constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
CMICmnStreamStdinLinux::CMICmnStreamStdinLinux(void)
: m_constBufferSize(1024)
, m_pStdin(nullptr)
, m_pCmdBuffer(nullptr)
{
}
//++ ------------------------------------------------------------------------------------
// Details: CMICmnStreamStdinLinux destructor.
// Type: Overridable.
// Args: None.
// Return: None.
// Throws: None.
//--
CMICmnStreamStdinLinux::~CMICmnStreamStdinLinux(void)
{
Shutdown();
}
//++ ------------------------------------------------------------------------------------
// Details: Initialize resources for *this Stdin stream.
// Type: Method.
// Args: None.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
bool
CMICmnStreamStdinLinux::Initialize(void)
{
if (m_bInitialized)
return MIstatus::success;
bool bOk = MIstatus::success;
CMIUtilString errMsg;
// Note initialisation order is important here as some resources depend on previous
MI::ModuleInit<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
MI::ModuleInit<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
// Other resources required
if (bOk)
{
m_pCmdBuffer = new MIchar[m_constBufferSize];
m_pStdin = stdin;
}
// Clear error indicators for std input
::clearerr(stdin);
m_bInitialized = bOk;
if (!bOk)
{
CMIUtilString strInitError(CMIUtilString::Format(MIRSRC(IDS_MI_INIT_ERR_OS_STDIN_HANDLER), errMsg.c_str()));
SetErrorDescription(strInitError);
return MIstatus::failure;
}
return MIstatus::success;
}
//++ ------------------------------------------------------------------------------------
// Details: Release resources for *this Stdin stream.
// Type: Method.
// Args: None.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
bool
CMICmnStreamStdinLinux::Shutdown(void)
{
if (!m_bInitialized)
return MIstatus::success;
m_bInitialized = false;
ClrErrorDescription();
bool bOk = MIstatus::success;
CMIUtilString errMsg;
// Tidy up
if (m_pCmdBuffer != nullptr)
{
delete[] m_pCmdBuffer;
m_pCmdBuffer = nullptr;
}
m_pStdin = nullptr;
// Note shutdown order is important here
MI::ModuleShutdown<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
MI::ModuleShutdown<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
if (!bOk)
{
SetErrorDescriptionn(MIRSRC(IDS_MI_SHTDWN_ERR_OS_STDIN_HANDLER), errMsg.c_str());
}
return MIstatus::success;
}
//++ ------------------------------------------------------------------------------------
// Details: Determine if stdin has any characters present in its buffer.
// Type: Method.
// Args: vwbAvail - (W) True = There is chars available, false = nothing there.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
bool
CMICmnStreamStdinLinux::InputAvailable(bool &vwbAvail)
{
#if !defined(_WIN32)
// The code below is needed on OSX where lldb-mi hangs when doing -exec-run.
// The hang seems to come from calling fgets and fileno from different thread.
// Although this problem was not observed on Linux.
// A solution based on 'select' was also proposed but it seems to slow things down
// a lot.
int nBytesWaiting;
if (::ioctl(STDIN_FILENO, FIONREAD, &nBytesWaiting) == -1)
{
vwbAvail = false;
return MIstatus::failure;;
}
vwbAvail = (nBytesWaiting > 0);
#endif // !defined( _WIN32 )
return MIstatus::success;
}
//++ ------------------------------------------------------------------------------------
// Details: Wait on new line of data from stdin stream (completed by '\n' or '\r').
// Type: Method.
// Args: vwErrMsg - (W) Empty string ok or error description.
// Return: MIchar * - text buffer pointer or NULL on failure.
// Throws: None.
//--
const MIchar *
CMICmnStreamStdinLinux::ReadLine(CMIUtilString &vwErrMsg)
{
vwErrMsg.clear();
// Read user input
const MIchar *pText = ::fgets(&m_pCmdBuffer[0], m_constBufferSize, stdin);
if (pText == nullptr)
{
if (::ferror(m_pStdin) != 0)
vwErrMsg = ::strerror(errno);
return nullptr;
}
// Strip off new line characters
for (MIchar *pI = m_pCmdBuffer; *pI != '\0'; pI++)
{
if ((*pI == '\n') || (*pI == '\r'))
{
*pI = '\0';
break;
}
}
return pText;
}
|
#pragma once
//MouseMovingToRight.h
#ifndef _MOUSEMOVINGTORIGHT_H
#define _MOUSEMOVINGTORIGHT_H
#include "MouseAction.h"
using namespace std;
class Form;
class MouseMovingToRight : public MouseAction {
public:
MouseMovingToRight(Form *form = 0);
MouseMovingToRight(const MouseMovingToRight& source);
~MouseMovingToRight();
MouseMovingToRight& operator=(const MouseMovingToRight& source);
virtual void OnMouseAction(UINT nFlags, CPoint point);
virtual void OnMouseAction(int x, int y);
virtual void OnMouseAction(UINT nSide, LPRECT lpRect);
};
#endif //_MOUSEMOVINGTORIGHT_H
|
/*
* SPDX-FileCopyrightText: 2020 Rolf Eike Beer <eike@sf-mail.de>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <osm_api.h>
#include <osm_api_p.h>
#include <settings.h>
#include <osm2go_annotations.h>
#include "osm2go_i18n.h"
#define COLOR_ERR "red"
#define COLOR_OK "darkgreen"
void
osm_upload_dialog(appdata_t &, const osm_t::dirty_t &)
{
abort();
}
osm_upload_context_t::osm_upload_context_t(appdata_t &a, project_t::ref p, const char *c, const char *s)
: appdata(a)
, osm(p->osm)
, project(p)
, urlbasestr(p->server(settings_t::instance()->server) + "/")
, comment(c)
, src(s == nullptr ? s : std::string())
{
}
void
osm_upload_context_t::append_str(const char *msg, const char *colorname)
{
append(trstring(msg), colorname);
}
void
osm_upload_context_t::append(const trstring &, const char *)
{
abort();
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Devices.Usb.1.h"
#include "Windows.Foundation.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_ef60385f_be78_584b_aaef_7829ada2b0de
#define WINRT_GENERIC_ef60385f_be78_584b_aaef_7829ada2b0de
template <> struct __declspec(uuid("ef60385f-be78-584b-aaef-7829ada2b0de")) __declspec(novtable) IAsyncOperation<uint32_t> : impl_IAsyncOperation<uint32_t> {};
#endif
#ifndef WINRT_GENERIC_3bee8834_b9a7_5a80_a746_5ef097227878
#define WINRT_GENERIC_3bee8834_b9a7_5a80_a746_5ef097227878
template <> struct __declspec(uuid("3bee8834-b9a7-5a80-a746-5ef097227878")) __declspec(novtable) IAsyncOperation<Windows::Storage::Streams::IBuffer> : impl_IAsyncOperation<Windows::Storage::Streams::IBuffer> {};
#endif
#ifndef WINRT_GENERIC_e5198cc8_2873_55f5_b0a1_84ff9e4aad62
#define WINRT_GENERIC_e5198cc8_2873_55f5_b0a1_84ff9e4aad62
template <> struct __declspec(uuid("e5198cc8-2873-55f5-b0a1-84ff9e4aad62")) __declspec(novtable) IReference<uint8_t> : impl_IReference<uint8_t> {};
#endif
#ifndef WINRT_GENERIC_2138c5ed_b71a_5166_9948_d55792748f5c
#define WINRT_GENERIC_2138c5ed_b71a_5166_9948_d55792748f5c
template <> struct __declspec(uuid("2138c5ed-b71a-5166-9948-d55792748f5c")) __declspec(novtable) IAsyncOperation<Windows::Devices::Usb::UsbDevice> : impl_IAsyncOperation<Windows::Devices::Usb::UsbDevice> {};
#endif
#ifndef WINRT_GENERIC_e6db9449_f36a_50f2_926c_2afd85c49f01
#define WINRT_GENERIC_e6db9449_f36a_50f2_926c_2afd85c49f01
template <> struct __declspec(uuid("e6db9449-f36a-50f2-926c-2afd85c49f01")) __declspec(novtable) TypedEventHandler<Windows::Devices::Usb::UsbInterruptInPipe, Windows::Devices::Usb::UsbInterruptInEventArgs> : impl_TypedEventHandler<Windows::Devices::Usb::UsbInterruptInPipe, Windows::Devices::Usb::UsbInterruptInEventArgs> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_9c69ec7f_2e42_58cd_a74a_f4974811134d
#define WINRT_GENERIC_9c69ec7f_2e42_58cd_a74a_f4974811134d
template <> struct __declspec(uuid("9c69ec7f-2e42-58cd-a74a-f4974811134d")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbInterface> : impl_IVectorView<Windows::Devices::Usb::UsbInterface> {};
#endif
#ifndef WINRT_GENERIC_5408baa2_291e_537a_b61f_137062f7ff7d
#define WINRT_GENERIC_5408baa2_291e_537a_b61f_137062f7ff7d
template <> struct __declspec(uuid("5408baa2-291e-537a-b61f-137062f7ff7d")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbDescriptor> : impl_IVectorView<Windows::Devices::Usb::UsbDescriptor> {};
#endif
#ifndef WINRT_GENERIC_a93c84bc_6484_5959_b61a_703cc7115f6f
#define WINRT_GENERIC_a93c84bc_6484_5959_b61a_703cc7115f6f
template <> struct __declspec(uuid("a93c84bc-6484-5959-b61a-703cc7115f6f")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbBulkInPipe> : impl_IVectorView<Windows::Devices::Usb::UsbBulkInPipe> {};
#endif
#ifndef WINRT_GENERIC_37469574_b4c5_5ba0_9616_894dd822ff5b
#define WINRT_GENERIC_37469574_b4c5_5ba0_9616_894dd822ff5b
template <> struct __declspec(uuid("37469574-b4c5-5ba0-9616-894dd822ff5b")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbInterruptInPipe> : impl_IVectorView<Windows::Devices::Usb::UsbInterruptInPipe> {};
#endif
#ifndef WINRT_GENERIC_0a873512_15f1_5e8e_a72a_045cfd7a5e83
#define WINRT_GENERIC_0a873512_15f1_5e8e_a72a_045cfd7a5e83
template <> struct __declspec(uuid("0a873512-15f1-5e8e-a72a-045cfd7a5e83")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbBulkOutPipe> : impl_IVectorView<Windows::Devices::Usb::UsbBulkOutPipe> {};
#endif
#ifndef WINRT_GENERIC_748196c8_83bf_5ec3_8d28_a3112b3ee3cc
#define WINRT_GENERIC_748196c8_83bf_5ec3_8d28_a3112b3ee3cc
template <> struct __declspec(uuid("748196c8-83bf-5ec3-8d28-a3112b3ee3cc")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbInterruptOutPipe> : impl_IVectorView<Windows::Devices::Usb::UsbInterruptOutPipe> {};
#endif
#ifndef WINRT_GENERIC_71194af7_77c2_54d5_a116_287f0b7fd53f
#define WINRT_GENERIC_71194af7_77c2_54d5_a116_287f0b7fd53f
template <> struct __declspec(uuid("71194af7-77c2-54d5-a116-287f0b7fd53f")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbInterfaceSetting> : impl_IVectorView<Windows::Devices::Usb::UsbInterfaceSetting> {};
#endif
#ifndef WINRT_GENERIC_9c69ac78_309e_5763_af26_9706ffa47ec0
#define WINRT_GENERIC_9c69ac78_309e_5763_af26_9706ffa47ec0
template <> struct __declspec(uuid("9c69ac78-309e-5763-af26-9706ffa47ec0")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbBulkInEndpointDescriptor> : impl_IVectorView<Windows::Devices::Usb::UsbBulkInEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_3fc7f890_218e_5057_904d_6387c591cc93
#define WINRT_GENERIC_3fc7f890_218e_5057_904d_6387c591cc93
template <> struct __declspec(uuid("3fc7f890-218e-5057-904d-6387c591cc93")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbInterruptInEndpointDescriptor> : impl_IVectorView<Windows::Devices::Usb::UsbInterruptInEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_22a53676_a3ea_5dcd_bb39_b28a5327c4a3
#define WINRT_GENERIC_22a53676_a3ea_5dcd_bb39_b28a5327c4a3
template <> struct __declspec(uuid("22a53676-a3ea-5dcd-bb39-b28a5327c4a3")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbBulkOutEndpointDescriptor> : impl_IVectorView<Windows::Devices::Usb::UsbBulkOutEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_984e7e15_c5ac_5140_a3c0_b583190085d7
#define WINRT_GENERIC_984e7e15_c5ac_5140_a3c0_b583190085d7
template <> struct __declspec(uuid("984e7e15-c5ac-5140-a3c0-b583190085d7")) __declspec(novtable) IVectorView<Windows::Devices::Usb::UsbInterruptOutEndpointDescriptor> : impl_IVectorView<Windows::Devices::Usb::UsbInterruptOutEndpointDescriptor> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_9343b6e7_e3d2_5e4a_ab2d_2bce4919a6a4
#define WINRT_GENERIC_9343b6e7_e3d2_5e4a_ab2d_2bce4919a6a4
template <> struct __declspec(uuid("9343b6e7-e3d2-5e4a-ab2d-2bce4919a6a4")) __declspec(novtable) AsyncOperationCompletedHandler<uint32_t> : impl_AsyncOperationCompletedHandler<uint32_t> {};
#endif
#ifndef WINRT_GENERIC_51c3d2fd_b8a1_5620_b746_7ee6d533aca3
#define WINRT_GENERIC_51c3d2fd_b8a1_5620_b746_7ee6d533aca3
template <> struct __declspec(uuid("51c3d2fd-b8a1-5620-b746-7ee6d533aca3")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Storage::Streams::IBuffer> : impl_AsyncOperationCompletedHandler<Windows::Storage::Streams::IBuffer> {};
#endif
#ifndef WINRT_GENERIC_7331254f_6caf_587d_9c2a_018c66d312db
#define WINRT_GENERIC_7331254f_6caf_587d_9c2a_018c66d312db
template <> struct __declspec(uuid("7331254f-6caf-587d-9c2a-018c66d312db")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Usb::UsbDevice> : impl_AsyncOperationCompletedHandler<Windows::Devices::Usb::UsbDevice> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_b11604f9_311d_5d64_8d83_9f1156bdcc53
#define WINRT_GENERIC_b11604f9_311d_5d64_8d83_9f1156bdcc53
template <> struct __declspec(uuid("b11604f9-311d-5d64-8d83-9f1156bdcc53")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbInterface> : impl_IVector<Windows::Devices::Usb::UsbInterface> {};
#endif
#ifndef WINRT_GENERIC_216b5a5f_63e3_5a9b_9c99_b09cbc0ff3b1
#define WINRT_GENERIC_216b5a5f_63e3_5a9b_9c99_b09cbc0ff3b1
template <> struct __declspec(uuid("216b5a5f-63e3-5a9b-9c99-b09cbc0ff3b1")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbInterface> : impl_IIterator<Windows::Devices::Usb::UsbInterface> {};
#endif
#ifndef WINRT_GENERIC_f54037ed_92e9_590d_b904_3ad7bfa9a621
#define WINRT_GENERIC_f54037ed_92e9_590d_b904_3ad7bfa9a621
template <> struct __declspec(uuid("f54037ed-92e9-590d-b904-3ad7bfa9a621")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbInterface> : impl_IIterable<Windows::Devices::Usb::UsbInterface> {};
#endif
#ifndef WINRT_GENERIC_35e50c94_ae54_53ac_b667_1c60e79ce168
#define WINRT_GENERIC_35e50c94_ae54_53ac_b667_1c60e79ce168
template <> struct __declspec(uuid("35e50c94-ae54-53ac-b667-1c60e79ce168")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbDescriptor> : impl_IVector<Windows::Devices::Usb::UsbDescriptor> {};
#endif
#ifndef WINRT_GENERIC_521598ed_0167_528e_990d_52abb712f072
#define WINRT_GENERIC_521598ed_0167_528e_990d_52abb712f072
template <> struct __declspec(uuid("521598ed-0167-528e-990d-52abb712f072")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbDescriptor> : impl_IIterator<Windows::Devices::Usb::UsbDescriptor> {};
#endif
#ifndef WINRT_GENERIC_989909a5_5a03_51fb_bd94_84da7bda8819
#define WINRT_GENERIC_989909a5_5a03_51fb_bd94_84da7bda8819
template <> struct __declspec(uuid("989909a5-5a03-51fb-bd94-84da7bda8819")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbDescriptor> : impl_IIterable<Windows::Devices::Usb::UsbDescriptor> {};
#endif
#ifndef WINRT_GENERIC_5df81263_bfc2_5836_8158_60ac127dde57
#define WINRT_GENERIC_5df81263_bfc2_5836_8158_60ac127dde57
template <> struct __declspec(uuid("5df81263-bfc2-5836-8158-60ac127dde57")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbBulkInPipe> : impl_IVector<Windows::Devices::Usb::UsbBulkInPipe> {};
#endif
#ifndef WINRT_GENERIC_d7af2c5b_528d_5cbb_a997_d830ade704c7
#define WINRT_GENERIC_d7af2c5b_528d_5cbb_a997_d830ade704c7
template <> struct __declspec(uuid("d7af2c5b-528d-5cbb-a997-d830ade704c7")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbBulkInPipe> : impl_IIterator<Windows::Devices::Usb::UsbBulkInPipe> {};
#endif
#ifndef WINRT_GENERIC_2201a671_42d2_508d_a848_64b5447083c8
#define WINRT_GENERIC_2201a671_42d2_508d_a848_64b5447083c8
template <> struct __declspec(uuid("2201a671-42d2-508d-a848-64b5447083c8")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbBulkInPipe> : impl_IIterable<Windows::Devices::Usb::UsbBulkInPipe> {};
#endif
#ifndef WINRT_GENERIC_789d3470_2d41_57fe_8cfd_4529adf1a15b
#define WINRT_GENERIC_789d3470_2d41_57fe_8cfd_4529adf1a15b
template <> struct __declspec(uuid("789d3470-2d41-57fe-8cfd-4529adf1a15b")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbInterruptInPipe> : impl_IVector<Windows::Devices::Usb::UsbInterruptInPipe> {};
#endif
#ifndef WINRT_GENERIC_e3a7b1c0_74f6_5292_a22a_672aa2b49985
#define WINRT_GENERIC_e3a7b1c0_74f6_5292_a22a_672aa2b49985
template <> struct __declspec(uuid("e3a7b1c0-74f6-5292-a22a-672aa2b49985")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbInterruptInPipe> : impl_IIterator<Windows::Devices::Usb::UsbInterruptInPipe> {};
#endif
#ifndef WINRT_GENERIC_39aef336_18aa_5be4_86d9_e332fe2632f3
#define WINRT_GENERIC_39aef336_18aa_5be4_86d9_e332fe2632f3
template <> struct __declspec(uuid("39aef336-18aa-5be4-86d9-e332fe2632f3")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbInterruptInPipe> : impl_IIterable<Windows::Devices::Usb::UsbInterruptInPipe> {};
#endif
#ifndef WINRT_GENERIC_abd12a19_bca3_5a8e_badb_1ec177fc7683
#define WINRT_GENERIC_abd12a19_bca3_5a8e_badb_1ec177fc7683
template <> struct __declspec(uuid("abd12a19-bca3-5a8e-badb-1ec177fc7683")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbBulkOutPipe> : impl_IVector<Windows::Devices::Usb::UsbBulkOutPipe> {};
#endif
#ifndef WINRT_GENERIC_46dd2f6a_573b_5c45_b168_9223038491dd
#define WINRT_GENERIC_46dd2f6a_573b_5c45_b168_9223038491dd
template <> struct __declspec(uuid("46dd2f6a-573b-5c45-b168-9223038491dd")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbBulkOutPipe> : impl_IIterator<Windows::Devices::Usb::UsbBulkOutPipe> {};
#endif
#ifndef WINRT_GENERIC_9824caba_5ca6_5c2d_80cf_1949026d7857
#define WINRT_GENERIC_9824caba_5ca6_5c2d_80cf_1949026d7857
template <> struct __declspec(uuid("9824caba-5ca6-5c2d-80cf-1949026d7857")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbBulkOutPipe> : impl_IIterable<Windows::Devices::Usb::UsbBulkOutPipe> {};
#endif
#ifndef WINRT_GENERIC_e0c87662_93f3_5215_a566_906f9ba7c399
#define WINRT_GENERIC_e0c87662_93f3_5215_a566_906f9ba7c399
template <> struct __declspec(uuid("e0c87662-93f3-5215-a566-906f9ba7c399")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbInterruptOutPipe> : impl_IVector<Windows::Devices::Usb::UsbInterruptOutPipe> {};
#endif
#ifndef WINRT_GENERIC_cbd8d8a8_2286_5cbd_a6e4_962742ffd91a
#define WINRT_GENERIC_cbd8d8a8_2286_5cbd_a6e4_962742ffd91a
template <> struct __declspec(uuid("cbd8d8a8-2286-5cbd-a6e4-962742ffd91a")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbInterruptOutPipe> : impl_IIterator<Windows::Devices::Usb::UsbInterruptOutPipe> {};
#endif
#ifndef WINRT_GENERIC_e61a011e_4abe_53f2_83b3_ed4a949d2e3f
#define WINRT_GENERIC_e61a011e_4abe_53f2_83b3_ed4a949d2e3f
template <> struct __declspec(uuid("e61a011e-4abe-53f2-83b3-ed4a949d2e3f")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbInterruptOutPipe> : impl_IIterable<Windows::Devices::Usb::UsbInterruptOutPipe> {};
#endif
#ifndef WINRT_GENERIC_03594a06_d2d3_5450_9c08_668ab65475ab
#define WINRT_GENERIC_03594a06_d2d3_5450_9c08_668ab65475ab
template <> struct __declspec(uuid("03594a06-d2d3-5450-9c08-668ab65475ab")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbInterfaceSetting> : impl_IVector<Windows::Devices::Usb::UsbInterfaceSetting> {};
#endif
#ifndef WINRT_GENERIC_71267ec7_5697_5dea_b2f8_14cf698ec0ad
#define WINRT_GENERIC_71267ec7_5697_5dea_b2f8_14cf698ec0ad
template <> struct __declspec(uuid("71267ec7-5697-5dea-b2f8-14cf698ec0ad")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbInterfaceSetting> : impl_IIterator<Windows::Devices::Usb::UsbInterfaceSetting> {};
#endif
#ifndef WINRT_GENERIC_1aaf5739_9c2c_533e_a0e9_d53fdb45d15d
#define WINRT_GENERIC_1aaf5739_9c2c_533e_a0e9_d53fdb45d15d
template <> struct __declspec(uuid("1aaf5739-9c2c-533e-a0e9-d53fdb45d15d")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbInterfaceSetting> : impl_IIterable<Windows::Devices::Usb::UsbInterfaceSetting> {};
#endif
#ifndef WINRT_GENERIC_fc953884_3db0_55ef_a0a9_28682dacb5e0
#define WINRT_GENERIC_fc953884_3db0_55ef_a0a9_28682dacb5e0
template <> struct __declspec(uuid("fc953884-3db0-55ef-a0a9-28682dacb5e0")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbBulkInEndpointDescriptor> : impl_IVector<Windows::Devices::Usb::UsbBulkInEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_ea511030_89c4_503d_8caf_667f4230d2a9
#define WINRT_GENERIC_ea511030_89c4_503d_8caf_667f4230d2a9
template <> struct __declspec(uuid("ea511030-89c4-503d-8caf-667f4230d2a9")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbBulkInEndpointDescriptor> : impl_IIterator<Windows::Devices::Usb::UsbBulkInEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_101b1fd9_f1c9_5dda_9ad4_71176fa839b2
#define WINRT_GENERIC_101b1fd9_f1c9_5dda_9ad4_71176fa839b2
template <> struct __declspec(uuid("101b1fd9-f1c9-5dda-9ad4-71176fa839b2")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbBulkInEndpointDescriptor> : impl_IIterable<Windows::Devices::Usb::UsbBulkInEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_6d8fdb3a_ca37_5658_a756_815e267f5e2e
#define WINRT_GENERIC_6d8fdb3a_ca37_5658_a756_815e267f5e2e
template <> struct __declspec(uuid("6d8fdb3a-ca37-5658-a756-815e267f5e2e")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbInterruptInEndpointDescriptor> : impl_IVector<Windows::Devices::Usb::UsbInterruptInEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_6717500f_ec1c_5b12_bf33_0e3e3d244587
#define WINRT_GENERIC_6717500f_ec1c_5b12_bf33_0e3e3d244587
template <> struct __declspec(uuid("6717500f-ec1c-5b12-bf33-0e3e3d244587")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbInterruptInEndpointDescriptor> : impl_IIterator<Windows::Devices::Usb::UsbInterruptInEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_8a7bac69_1f10_59c7_9837_72cfed7154a4
#define WINRT_GENERIC_8a7bac69_1f10_59c7_9837_72cfed7154a4
template <> struct __declspec(uuid("8a7bac69-1f10-59c7-9837-72cfed7154a4")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbInterruptInEndpointDescriptor> : impl_IIterable<Windows::Devices::Usb::UsbInterruptInEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_e0087bb6_6012_50a7_8a18_c48eb8858f26
#define WINRT_GENERIC_e0087bb6_6012_50a7_8a18_c48eb8858f26
template <> struct __declspec(uuid("e0087bb6-6012-50a7-8a18-c48eb8858f26")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbBulkOutEndpointDescriptor> : impl_IVector<Windows::Devices::Usb::UsbBulkOutEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_a8b89ab3_883d_5361_9903_f489cc62bea5
#define WINRT_GENERIC_a8b89ab3_883d_5361_9903_f489cc62bea5
template <> struct __declspec(uuid("a8b89ab3-883d-5361-9903-f489cc62bea5")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbBulkOutEndpointDescriptor> : impl_IIterator<Windows::Devices::Usb::UsbBulkOutEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_b80beb39_62b3_5f59_b3e7_882cc9c5b0c0
#define WINRT_GENERIC_b80beb39_62b3_5f59_b3e7_882cc9c5b0c0
template <> struct __declspec(uuid("b80beb39-62b3-5f59-b3e7-882cc9c5b0c0")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbBulkOutEndpointDescriptor> : impl_IIterable<Windows::Devices::Usb::UsbBulkOutEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_386b792a_6b7b_580a_8e7e_9ef9838c0e6f
#define WINRT_GENERIC_386b792a_6b7b_580a_8e7e_9ef9838c0e6f
template <> struct __declspec(uuid("386b792a-6b7b-580a-8e7e-9ef9838c0e6f")) __declspec(novtable) IVector<Windows::Devices::Usb::UsbInterruptOutEndpointDescriptor> : impl_IVector<Windows::Devices::Usb::UsbInterruptOutEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_4b6426db_db32_5b51_adad_04532ea94acd
#define WINRT_GENERIC_4b6426db_db32_5b51_adad_04532ea94acd
template <> struct __declspec(uuid("4b6426db-db32-5b51-adad-04532ea94acd")) __declspec(novtable) IIterator<Windows::Devices::Usb::UsbInterruptOutEndpointDescriptor> : impl_IIterator<Windows::Devices::Usb::UsbInterruptOutEndpointDescriptor> {};
#endif
#ifndef WINRT_GENERIC_09393d62_2316_536b_8a10_7038884ab2a7
#define WINRT_GENERIC_09393d62_2316_536b_8a10_7038884ab2a7
template <> struct __declspec(uuid("09393d62-2316-536b-8a10-7038884ab2a7")) __declspec(novtable) IIterable<Windows::Devices::Usb::UsbInterruptOutEndpointDescriptor> : impl_IIterable<Windows::Devices::Usb::UsbInterruptOutEndpointDescriptor> {};
#endif
}
namespace Windows::Devices::Usb {
struct IUsbBulkInEndpointDescriptor :
Windows::Foundation::IInspectable,
impl::consume<IUsbBulkInEndpointDescriptor>
{
IUsbBulkInEndpointDescriptor(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbBulkInPipe :
Windows::Foundation::IInspectable,
impl::consume<IUsbBulkInPipe>
{
IUsbBulkInPipe(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbBulkOutEndpointDescriptor :
Windows::Foundation::IInspectable,
impl::consume<IUsbBulkOutEndpointDescriptor>
{
IUsbBulkOutEndpointDescriptor(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbBulkOutPipe :
Windows::Foundation::IInspectable,
impl::consume<IUsbBulkOutPipe>
{
IUsbBulkOutPipe(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbConfiguration :
Windows::Foundation::IInspectable,
impl::consume<IUsbConfiguration>
{
IUsbConfiguration(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbConfigurationDescriptor :
Windows::Foundation::IInspectable,
impl::consume<IUsbConfigurationDescriptor>
{
IUsbConfigurationDescriptor(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbConfigurationDescriptorStatics :
Windows::Foundation::IInspectable,
impl::consume<IUsbConfigurationDescriptorStatics>
{
IUsbConfigurationDescriptorStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbControlRequestType :
Windows::Foundation::IInspectable,
impl::consume<IUsbControlRequestType>
{
IUsbControlRequestType(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbDescriptor :
Windows::Foundation::IInspectable,
impl::consume<IUsbDescriptor>
{
IUsbDescriptor(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbDevice :
Windows::Foundation::IInspectable,
impl::consume<IUsbDevice>,
impl::require<IUsbDevice, Windows::Foundation::IClosable>
{
IUsbDevice(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbDeviceClass :
Windows::Foundation::IInspectable,
impl::consume<IUsbDeviceClass>
{
IUsbDeviceClass(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbDeviceClasses :
Windows::Foundation::IInspectable,
impl::consume<IUsbDeviceClasses>
{
IUsbDeviceClasses(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbDeviceClassesStatics :
Windows::Foundation::IInspectable,
impl::consume<IUsbDeviceClassesStatics>
{
IUsbDeviceClassesStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbDeviceDescriptor :
Windows::Foundation::IInspectable,
impl::consume<IUsbDeviceDescriptor>
{
IUsbDeviceDescriptor(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbDeviceStatics :
Windows::Foundation::IInspectable,
impl::consume<IUsbDeviceStatics>
{
IUsbDeviceStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbEndpointDescriptor :
Windows::Foundation::IInspectable,
impl::consume<IUsbEndpointDescriptor>
{
IUsbEndpointDescriptor(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbEndpointDescriptorStatics :
Windows::Foundation::IInspectable,
impl::consume<IUsbEndpointDescriptorStatics>
{
IUsbEndpointDescriptorStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbInterface :
Windows::Foundation::IInspectable,
impl::consume<IUsbInterface>
{
IUsbInterface(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbInterfaceDescriptor :
Windows::Foundation::IInspectable,
impl::consume<IUsbInterfaceDescriptor>
{
IUsbInterfaceDescriptor(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbInterfaceDescriptorStatics :
Windows::Foundation::IInspectable,
impl::consume<IUsbInterfaceDescriptorStatics>
{
IUsbInterfaceDescriptorStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbInterfaceSetting :
Windows::Foundation::IInspectable,
impl::consume<IUsbInterfaceSetting>
{
IUsbInterfaceSetting(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbInterruptInEndpointDescriptor :
Windows::Foundation::IInspectable,
impl::consume<IUsbInterruptInEndpointDescriptor>
{
IUsbInterruptInEndpointDescriptor(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbInterruptInEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IUsbInterruptInEventArgs>
{
IUsbInterruptInEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbInterruptInPipe :
Windows::Foundation::IInspectable,
impl::consume<IUsbInterruptInPipe>
{
IUsbInterruptInPipe(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbInterruptOutEndpointDescriptor :
Windows::Foundation::IInspectable,
impl::consume<IUsbInterruptOutEndpointDescriptor>
{
IUsbInterruptOutEndpointDescriptor(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbInterruptOutPipe :
Windows::Foundation::IInspectable,
impl::consume<IUsbInterruptOutPipe>
{
IUsbInterruptOutPipe(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbSetupPacket :
Windows::Foundation::IInspectable,
impl::consume<IUsbSetupPacket>
{
IUsbSetupPacket(std::nullptr_t = nullptr) noexcept {}
};
struct IUsbSetupPacketFactory :
Windows::Foundation::IInspectable,
impl::consume<IUsbSetupPacketFactory>
{
IUsbSetupPacketFactory(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
#include <bits/stdc++.h>
using namespace std;
vector<int> d(int);
int main()
{
int n;
cin>>n;
vector<int> dp[1000];
dp[1].push_back(1);
dp[2].push_back(2);
dp[2].push_back(1);
for(int i=3; i<1000; i++)
{
vector<int> ret;
ret.push_back(i);
ret.push_back(1);
for(int j=i/2; j>1; j--)
{
if(i%j==0)
{
vector<int> temp;
ret.push_back(j);
temp = dp[j];
ret.insert(ret.end(), temp.begin(), temp.end());
//break;
}
}
dp[i] = ret;
}
for(int i=0; i<dp[n].size(); i++) cout<<dp[n][i]<<endl;
}
vector<int> d(int n)
{
vector<int> ret, ret1;
for(int i=n/2; i>1; i--)
{
if(n%i==0)
{
vector<int> temp;
ret.push_back(i);
temp = d(i);
ret.insert(ret.end(), temp.begin(), temp.end());
//break;
}
}
//if(ret[0]>1) ret1 = d(n/ret[0]);
//ret.insert(ret.end(), ret1.begin(), ret1.end());
//ret.push_back(n);
return ret;
}
|
//µÝ¹éËã·¨
#include<stdio.h>
long long int fun (long long int a,long long int b,long long int c);
int main(void)
{
long long int a,b,c;
scanf("%lld%lld%lld",&a,&b,&c);
printf("%lld\n",fun(a,b,c));
return 0;
}
long long int fun(long long int a,long long int b,long long int c)
{
long long int ans;
ans = 1;
if (b == 0) return 1 % c;
if (b == 1) return a % c;
ans = fun(a,b/2,c);
ans = ans * ans % c;
if (b % 2 == 1) ans = ans * a % c;
return ans;
}
//Ñ»·Ëã·¨£º
#include <stdio.h>
int fun(long long int a,long long int b,long long int c);
int main(void)
{
long long int a,b,c;
scanf("%lld%lld%lld",&a,&b,&c);
printf("%d\n",fun(a,b,c));
return 0;
}
int fun(long long int a,long long int b,long long int c)
{
int ans = 1;
a = a % c;
while (b > 0)
{
if (b % 2 == 1)
ans =ans * a % c;
a =a * a % c;
b /= 2;
}
return ans;
}
|
#include<stdio.h>
#include<stdlib.h>
#define MAXDEPTH 10
struct BinaryTree{
int node;
BinaryTree *left;
BinaryTree *right;
};
BinaryTree * buildTree(){
BinaryTree *tr;
int value;
scanf("%d",&value);
if(value == -1)
return NULL;
tr = (BinaryTree *)malloc(sizeof(BinaryTree));
tr->node = value;
tr->left = buildTree();
tr->right = buildTree();
return tr;
}
void printPath(int path[],int count){
for (int i=0; i< count; i++)
printf("%d",path[i]);
printf("\n");
}
void find(BinaryTree *tr,int path[],int sum,int count){
path[count++] = tr->node;
sum -= tr->node;
// printf("%d",sum);
// printf("\n");
if( tr->left == NULL && tr->right == NULL ){
if( sum == 0) printPath(path,count);
}
else{//注意递归过程要紧接着而不是用else分开
if( tr->left != NULL) find(tr->left,path,sum,count);
if( tr->right !=NULL) find(tr->right,path,sum,count);
}
count--;
sum += tr->node;
}
void search( BinaryTree *tr, int sum ){
int path[MAXDEPTH];
find(tr,path,sum,0);
}
void inOrderTree(BinaryTree *root){
if(root ==NULL)
return ;
inOrderTree(root->left);
printf("%d",root->node);
inOrderTree(root->right);
}
int main(){
BinaryTree *root = buildTree();
search( root,22);
// inOrderTree(root);
return 0;
}
|
#include "header.h"
//extern char **environ;
/******Global variables******/
int fd1[2], fd2[2];
int main()
{
string ip_comm;
pid_t pid;
int status;
unordered_map<string, string> alias_map;
//////////////////////////////////////////////////////////////////////
/* Trie variables */
trieNode **root = NULL;
char *path = getenv("PATH");
int numOfTrees;
trie_init(&root, numOfTrees);
/* Termios variables */
FILE *fp;
struct termios ots;
//termios_init(&fp, &ots);
/* Environment initialisation */
unordered_map<string, string> rc_map;
env_init(rc_map);
cout<<getenv("USER")<<":"<<getenv("PWD")<<getenv("PS1")<<" ";
while(getline(cin, ip_comm))//getline(cin, ip_comm)) //1
{
//////////////////////////////////////////////////////////////
/*char buf[MAX_BUF_LEN];
char *ptr;
ptr = buf;
int c;
bool firsttab = false;
time_t time1;
double seconds;
//int fd = open(ctermid(NULL), O_CREAT | O_RDONLY, 644); // "/dev/pts/3"
if ((fp = fopen(ctermid(NULL), "r+")) == NULL)
{
cerr<<"Cannot open terminal file... Exiting"<<ctermid(NULL);
return -1 ;
}
dup2(fd, STDIN_FILENO);
close(fd);
while ((c = getchar()) != EOF && (c != '\n'))
{
if((c == 9) && !firsttab)
{
time(&time1);
fseek(fp, -1, SEEK_END);
firsttab = true;
}
else if((c == 9) && firsttab)
{
time_t time2;
time(&time2);
fseek(fp, -1, SEEK_END);
seconds = difftime(time2,time1);
cerr<<seconds;
if(seconds < 1.0)
{
*ptr = 0;
string searchstr(buf);
int comp = printAutoSuggestions(&root, searchstr, numOfTrees);
cout<<getenv("PS1")<<" "<<buf;
}
firsttab = false;
}
else if (ptr < &buf[MAX_BUF_LEN])
*ptr++ = c;
}
*ptr = 0;
putc('\n', fp);
ip_comm = buf;
*/
////////////////////////////////////////////////////////////////////////////////
vector<string> ip_args;
vector<int> pipePos;
vector<int> redirectPos;
bool pipeflag = false;
bool redirectflag[3] = {false, false,false};
bool aliasflag = false;
bool cdflag = false;
bool openflag = false;
bool pidflag = false;
bool tabflag = false;
bool lastprocflag = false;
string alias_str;
istringstream ss(ip_comm);
while(!ss.eof())
{
string tmpstr;
ss>>tmpstr;
if(ss.eof())
{
if(tmpstr[tmpstr.size()-1] == '`')
{
tmpstr.erase(tmpstr.size()-1, 1);
int comp = printAutoSuggestions(&root, tmpstr, numOfTrees);
tabflag = true;
cout<<endl;
cout<<getenv("USER")<<":"<<getenv("PWD")<<getenv("PS1")<<" ";
break;
}
}
size_t pos;// = tmpstr.find('$');
if(((pos = tmpstr.find('$')) != string::npos) && (tmpstr.compare("$$") != 0) && (tmpstr.compare("$?") != 0))
{
if(pos == 0)
{
char var[100];
size_t len = tmpstr.copy(var,(tmpstr.length()-pos-1),pos+1);
var[len] = '\0';
char *val = getenv(var);
if(val != NULL)
tmpstr.replace(pos,string::npos, val);
}
else if(tmpstr[pos-1] != '\\')
{
char var[100];
size_t len = tmpstr.copy(var,(tmpstr.length()-pos-1),pos+1);
var[len] = '\0';
char *val = getenv(var);
if(val != NULL)
tmpstr.replace(pos, string::npos, val);
}
else
tmpstr.erase(pos-1, 1);
}
else if(tmpstr.compare("|") == 0)
{
pipeflag = true;
pipePos.push_back(ip_args.size()); // Position of pipe w.r.t 0
}
else if((tmpstr.compare(">") == 0) || (tmpstr.compare("<") == 0) || (tmpstr.compare(">>") == 0))
{
if((tmpstr.compare(">") == 0))
redirectflag[0] = true;
if((tmpstr.compare("<") == 0))
redirectflag[1] = true;
if((tmpstr.compare(">>") == 0))
redirectflag[2] = true;
if(pipePos.empty())
redirectPos.push_back(ip_args.size());
else
redirectPos.push_back(ip_args.size() - pipePos[pipePos.size()-1] - 1);
}
else if((tmpstr.compare("alias") == 0))
{
aliasflag = true;
char *ptr=&ip_comm[0];
while(*ptr != ' ')
ptr++;
ptr++;
alias_str = ptr;
alias_str.pop_back();
ip_args.push_back(tmpstr);
ip_args.push_back(alias_str);
break;
}
else if((tmpstr.compare("cd") == 0))
{
cdflag = true;
}
else if((tmpstr.compare("open") == 0))
{
openflag = true;
}
else if((tmpstr.compare("$$") == 0))
{
pidflag = true;
pid_t proc_pid = getpid();
int tmp = proc_pid;
tmpstr.replace(0, string::npos, to_string(tmp));
}
else if((tmpstr.compare("$?") == 0))
{
lastprocflag = true;
}
//cout<<tmpstr<<endl;
ip_args.push_back(tmpstr);
}
if(pipeflag)
{
pipedCommand(ip_args, pipePos, redirectflag, redirectPos);
}
else if(tabflag)
{
tabflag = false;
continue;
}
else if(aliasflag)
{
alias(alias_map, ip_args);
aliasflag=false;
cout<<getenv("USER")<<":"<<getenv("PWD")<<getenv("PS1")<<" ";
continue;
}
else if(cdflag)
{
cdflag = false;
changedir(ip_args, rc_map);
}
else if(openflag)
{
openflag = false;
open_comm(ip_args,rc_map);
}
else if(lastprocflag)
{
lastprocflag = false;
cout<<status<<endl;
}
else if(pidflag)
{
cout<<getpid()<<endl;
}
else
{
char **args;
unordered_map<string, string>::iterator itr = alias_map.find(ip_args[0]);
if(itr != alias_map.end())
{
string tmpstr;
vector<string> alias_comm;
istringstream alias_ss(itr->second);
while(!alias_ss.eof())
{
alias_ss>>tmpstr;
alias_comm.push_back(tmpstr);
}
args = new char* [alias_comm.size() + (ip_args.size()-1)+1];
int j=0;
for(int i=0; i<alias_comm.size(); ++i)
{
args[i] = new char [alias_comm[i].size()+1];
strcpy(args[i],alias_comm[i].c_str());
j++;
//args[i][alias_comm[i].size()] = '\0';
}
for(int i=1; i<ip_args.size(); ++i)
{
args[i+j] = new char [ip_args[i].size()+1];
strcpy(args[i+j],ip_args[i].c_str());
//args[i][ip_args[i].size()] = '\0';
}
args[alias_comm.size() + (ip_args.size()-1)] = NULL;
}
else
{
args = new char* [ip_args.size()+1];
for(int i=0; i<ip_args.size(); ++i)
{
args[i] = new char [ip_args[i].size()+1];
strcpy(args[i],ip_args[i].c_str());
//lsargs[i][ip_args[i].size()] = '\0';
}
args[ip_args.size()] = NULL;
}
if((pid = fork()) < 0)
{
cerr<<"fork() error...exiting.\n";
exit(-1);
}
else if(pid == 0)
{
if(redirectflag[0] || redirectflag[1] || redirectflag[2])
{
redirection(args, redirectPos);
}
else
{
execvp(args[0], args);
cerr<<"Command "<<args[0]<<" couldn't be executed!\n";
}
}
if((pid = waitpid(pid, &status, 0) < 0))
{
cerr<<"waitpid() error...exiting.\n";
exit(-1);
}
for(int i=0; i<ip_args.size(); ++i)
{
delete[] args[i];
}
delete[] args;
}
cout<<getenv("USER")<<":"<<getenv("PWD")<<getenv("PS1")<<" ";
}
tcsetattr(fileno(fp), TCSAFLUSH, &ots);
fclose(fp);
return 0;
}
void pipedCommand(vector<string> ip_args, vector<int> pipePos, bool *redirectflag, vector<int> &redirectPos)
{
pid_t pid;
int status;
int comm_count = pipePos.size() + 1;
pipePos.push_back(ip_args.size());
char ***args;
args = new char** [comm_count];
int argc=0;
for(int i=0; i<comm_count; ++i)
{
args[i] = new char* [pipePos[i] - argc +1];
args[i][pipePos[i] - argc] = NULL;
for(int j=argc, k=0; j<pipePos[i]; ++j, k++)
{
args[i][k] = new char [ip_args[argc].size()+1];
strcpy(args[i][k],ip_args[argc].c_str());
//cout<<args[i][k]<<endl;
argc++;
}
argc++; // For the pipe '|'
}
if((pipe(fd1) < 0) || (pipe(fd2) < 0))
{
cerr<<"pipe() error...exiting.\n";
exit(-1);
}
int comm_num = 0;
int count = comm_count;
while(count)
{
if((comm_num > 1) && (comm_num%2 != 0))
{
close(fd2[0]);
close(fd2[1]);
if((pipe(fd2) < 0))
{
cerr<<"pipe() error...exiting.\n";
exit(-1);
}
}
else if((comm_num > 1) && (comm_num%2 == 0))
{
close(fd1[0]);
close(fd1[1]);
if((pipe(fd1) < 0))
{
cerr<<"pipe() error...exiting.\n";
exit(-1);
}
}
if((pid = fork()) < 0)
{
cerr<<"fork() error...exiting.\n";
exit(-1);
}
else if(pid == 0)
{
if(comm_num == 0) // if it is first command
{
close(fd1[0]);
close(fd2[0]);
close(fd2[1]);
close(STDOUT_FILENO);
if(fd1[1] != STDOUT_FILENO)
{
if(dup2(fd1[1], STDOUT_FILENO) != STDOUT_FILENO)
{
cerr<<"dup2() error to stdout";
exit(-1);
}
//close(fd1[1]);
}
if(redirectflag[1])
{
redirectflag[1] = false;
redirection(args[comm_num], redirectPos);
}
else
{
execvp(args[comm_num][0], args[comm_num]);
cerr<<"Command "<<args[comm_num][0]<<" couldn't be executed!\n";
}
}
else if(comm_num == (comm_count - 1)) // if it is last command
{
if(comm_num%2 != 0)
{
close(fd1[1]);
close(fd2[0]);
close(fd2[1]);
close(STDIN_FILENO);
if(fd1[0] != STDIN_FILENO)
{
if(dup2(fd1[0], STDIN_FILENO) != STDIN_FILENO)
{
cerr<<"dup2() error to stdin";
exit(-1);
}
//close(fd1[0]);
}
if(redirectflag[0])
{
redirectflag[0] = false;
redirection(args[comm_num], redirectPos);
}
else if(redirectflag[2])
{
redirectflag[2] = false;
redirection(args[comm_num], redirectPos);
}
else
{
execvp(args[comm_num][0], args[comm_num]);
cerr<<"Command "<<args[comm_num][0]<<" couldn't be executed!\n";
}
}
else
{
close(fd1[1]);
close(fd1[0]);
close(fd2[1]);
close(STDIN_FILENO);
if(fd2[0] != STDIN_FILENO)
{
if(dup2(fd2[0], STDIN_FILENO) != STDIN_FILENO)
{
cerr<<"dup2() error to stdin";
exit(-1);
}
//close(fd2[0]);
}
if(redirectflag[0])
{
redirectflag[0] = false;
redirection(args[comm_num], redirectPos);
}
else if(redirectflag[2])
{
redirectflag[2] = false;
redirection(args[comm_num], redirectPos);
}
else
{
execvp(args[comm_num][0], args[comm_num]);
cerr<<"Command "<<args[comm_num][0]<<" couldn't be executed!\n";
}
}
}
else
{
if(comm_num%2 != 0)
{
close(fd1[1]);
close(fd2[0]);
close(STDIN_FILENO);
if(fd1[0] != STDIN_FILENO)
{
if(dup2(fd1[0], STDIN_FILENO) != STDIN_FILENO)
{
cerr<<"dup2() error to stdin";
exit(-1);
}
//close(fd1[0]);
}
close(STDOUT_FILENO);
if(fd2[1] != STDOUT_FILENO)
{
if(dup2(fd2[1], STDOUT_FILENO) != STDOUT_FILENO)
{
cerr<<"dup2() error to stdout";
exit(-1);
}
//close(fd2[1]);
}
execvp(args[comm_num][0], args[comm_num]);
cerr<<"Command "<<args[comm_num][0]<<" couldn't be executed!\n";
}
else
{
close(fd1[0]);
close(fd2[1]);
close(STDIN_FILENO);
if(fd2[0] != STDIN_FILENO)
{
if(dup2(fd2[0], STDIN_FILENO) != STDIN_FILENO)
{
cerr<<"dup2() error to stdin";
exit(-1);
}
//close(fd2[0]);
}
close(STDOUT_FILENO);
if(fd1[1] != STDOUT_FILENO)
{
if(dup2(fd1[1], STDOUT_FILENO) != STDOUT_FILENO)
{
cerr<<"dup2() error to stdout";
exit(-1);
}
//close(fd1[1]);
}
execvp(args[comm_num][0], args[comm_num]);
cerr<<"Command "<<args[comm_num][0]<<" couldn't be executed!\n";
}
}
}
if(comm_num == 0)
{
close(fd1[1]);
}
else if(comm_num == (comm_count - 1))
{
if(comm_num%2 != 0)
close(fd2[1]);
else
close(fd1[1]);
}
else
{
if(comm_num%2 != 0)
close(fd2[1]);
else
close(fd1[1]);
}
comm_num++;
count--;
if((pid = waitpid(pid, &status, 0) < 0))
{
cerr<<"waitpid() error...exiting.\n";
exit(-1);
}
}
close(fd1[0]);
close(fd1[1]);
close(fd2[0]);
close(fd2[1]);
argc=0;
for(int i=0; i<comm_count; ++i)
{
for(int j=argc, k=0; j<=pipePos[i]; ++j, k++)
{
delete[] args[i][k];
argc++;
}
argc++;
delete[] args[i];
}
delete[] args;
}
void redirection(char** ip_comm, vector<int> &redirectPos)
{
pid_t pid;
int k=0;
char **args = new char* [redirectPos[0]+1];
for(int k=0; k<redirectPos[0]; ++k)
{
args[k] = new char [strlen(ip_comm[k])];
strcpy(args[k], ip_comm[k]);
}
args[redirectPos[0]] = NULL;
//if((pid = fork()) < 0)
//{
// cerr<<"fork() error...exiting.\n";
// exit(-1);
//}
//else if(pid == 0)
//{
if(strcmp(ip_comm[redirectPos[0]], ">") == 0)
{
//cout<<ip_comm[0]<<ip_comm[1]<<ip_comm[2]<<ip_comm[3]<<endl;
int fd = open(ip_comm[redirectPos[0]+1], O_CREAT | O_WRONLY, 644);
if(fd < 0)
{
cerr<<"Could not open file. Redirection failed";
exit(-1);
}
if(dup2(fd, STDOUT_FILENO) != STDOUT_FILENO)
{
cerr<<"dup2() error to stdout";
exit(-1);
}
close(fd);
execvp(args[0], args);
cerr<<"Command "<<args[0]<<" couldn't be executed!\n";
}
else if(strcmp(ip_comm[redirectPos[0]], "<") == 0)
{
int fd = open(ip_comm[redirectPos[0]+1], O_CREAT | O_RDONLY, 644);
if(fd < 0)
{
cerr<<"Could not open file. Redirection failed";
exit(-1);
}
if(dup2(fd, STDIN_FILENO) != STDIN_FILENO)
{
cerr<<"dup2() error to stdout";
exit(-1);
}
close(fd);
execvp(args[0], args);
cerr<<"Command "<<args[0]<<" couldn't be executed!\n";
}
else if(strcmp(ip_comm[redirectPos[0]], ">>") == 0)
{
int fd = open(ip_comm[redirectPos[0]+1], O_CREAT | O_WRONLY | O_APPEND, 644);
if(fd < 0)
{
cerr<<"Could not open file. Redirection failed";
exit(-1);
}
if(dup2(fd, STDOUT_FILENO) != STDOUT_FILENO)
{
cerr<<"dup2() error to stdout";
exit(-1);
}
close(fd);
execvp(args[0], args);
cerr<<"Command "<<args[0]<<" couldn't be executed!\n";
}
redirectPos.erase(redirectPos.begin());
//}
}
|
#include <iostream>
bool isEven(int number) {
return (number % 2) == 0;
}
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
// Classes:
//
// FieldOffsetReduction
//-----------------------------------------------------------------------------
#ifndef POOMA_FIELD_DIFFOPS_FIELDOFFSETREDUCTION_H
#define POOMA_FIELD_DIFFOPS_FIELDOFFSETREDUCTION_H
//-----------------------------------------------------------------------------
// Overview:
//
// Support for reductions that take the result of a nearest neighbor
// calculation. For example:
//
// sum(f, nearestNeighbor(f.centering(), centering2), centering2);
//
// results in a field with centering2, where values from f at the closest
// centering points are summed onto each centering point in the resulting
// field.
//
// Note that this function isn't really that general, because the nearest
// neighbor computation must use the input fields centering for the input
// centering and same output centering as the centering handed to sum.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Typedefs:
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes:
//-----------------------------------------------------------------------------
#include "Field/DiffOps/FieldStencil.h"
//-----------------------------------------------------------------------------
// Forward Declarations:
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
//
// FieldOffsetReduction<T, Dim, Accumulate>
//
// This class is a functor object used to create a field stencil engine that
// accumulates values from a FieldOffsetList. The functor is constructed with
// a neighbor list, output centering, input centering and a binary function.
//
// Applying the functor to a field and location will accumulate the neighbors
// of the field at the location using the neighbor list.
//
// ----------------------------------------------------------------------------
template<class T, int Dim, class Accumulate>
class FieldOffsetReduction
{
public:
//
// Interface required to create a field stencil object:
//
typedef T OutputElement_t;
const Centering<Dim> &outputCentering() const
{
return outputCentering_m;
}
const Centering<Dim> &inputCentering() const
{
return inputCentering_m;
}
int lowerExtent(int d) const { return lower_m[d]; }
int upperExtent(int d) const { return upper_m[d]; }
//
// Constructors.
//
FieldOffsetReduction()
{
}
FieldOffsetReduction(const FieldOffsetList<Dim> &neighbors,
const Centering<Dim> &outputCentering,
const Centering<Dim> &inputCentering,
Accumulate accumulate = Accumulate())
: neighbors_m(neighbors),
outputCentering_m(outputCentering),
inputCentering_m(inputCentering),
accumulate_m(accumulate)
{
PInsist(neighbors.size() > 0, "no support for empty accumulation");
PAssert(outputCentering.size() == 1);
int d, i;
for (d = 0; d < Dim; ++d)
{
upper_m[d] = 0;
lower_m[d] = 0;
}
for (i = 0; i < neighbors_m.size(); ++i)
{
for (d = 0; d < Dim; ++d)
{
if (-neighbors_m[i].cellOffset()[d].first() > lower_m[d])
{
lower_m[d] = -neighbors_m[i].cellOffset()[d].first();
}
if (neighbors_m[i].cellOffset()[d].first() > upper_m[d])
{
upper_m[d] = neighbors_m[i].cellOffset()[d].first();
}
}
}
}
//
// Stencil operations.
//
template<class F>
inline OutputElement_t
operator()(const F &f, int i1) const
{
T ret = f(neighbors_m[0], Loc<1>(i1));
for (int i = 1; i < neighbors_m.size(); ++i)
{
ret = accumulate_m(ret, f(neighbors_m[i], Loc<1>(i1)));
}
return ret;
}
template<class F>
inline OutputElement_t
operator()(const F &f, int i1, int i2) const
{
T ret = f(neighbors_m[0], Loc<2>(i1, i2));
for (int i = 1; i < neighbors_m.size(); ++i)
{
ret = accumulate_m(ret, f(neighbors_m[i], Loc<2>(i1, i2)));
}
return ret;
}
template<class F>
inline OutputElement_t
operator()(const F &f, int i1, int i2, int i3) const
{
T ret = f(neighbors_m[0], Loc<3>(i1, i2, i3));
for (int i = 1; i < neighbors_m.size(); ++i)
{
ret = accumulate_m(ret, f(neighbors_m[i], Loc<3>(i1, i2, i3)));
}
return ret;
}
private:
FieldOffsetList<Dim> neighbors_m;
Centering<Dim> outputCentering_m;
Centering<Dim> inputCentering_m;
Accumulate accumulate_m;
int lower_m[Dim];
int upper_m[Dim];
};
// ----------------------------------------------------------------------------
// Overloaded functions to perform reductions.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Sum up the results from a nearest neighbor computation
// ----------------------------------------------------------------------------
template<class GeometryTag, class T, class EngineTag, int Dim>
typename FieldStencilSimple<FieldOffsetReduction<T, Dim, OpAdd>,
Field<GeometryTag, T, EngineTag> >::Type_t
sum(const Field<GeometryTag, T, EngineTag> &f,
const std::vector<FieldOffsetList<Dim> > &nn,
const Centering<Dim> &outputCentering)
{
typedef FieldOffsetReduction<T, Dim, OpAdd> Functor_t;
typedef Field<GeometryTag, T, EngineTag> Field_t;
return FieldStencilSimple<Functor_t, Field_t>::make(f, nn, outputCentering,
OpAdd());
}
#endif // POOMA_FIELD_DIFFOPS_FIELDOFFSETREDUCTION_H
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: FieldOffsetReduction.h,v $ $Author: richard $
// $Revision: 1.3 $ $Date: 2004/11/01 18:16:44 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
#ifndef _LED_PLUGIN_H_
#define _LED_PLUGIN_H_
#include <QtUiPlugin/QDesignerCustomWidgetInterface>
//Designeer plugin class.
class LEDPlugin : public QObject, public QDesignerCustomWidgetInterface
{
Q_OBJECT
Q_INTERFACES(QDesignerCustomWidgetInterface)
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
Q_PLUGIN_METADATA(IID "com.ics.Qt.CustomWidgets")
#endif
public:
LEDPlugin(QObject* parent=0);
QString name() const;
QString group() const;
QString toolTip() const;
QString whatsThis() const;
QString includeFile() const;
QIcon icon() const;
QString domXml() const; //load custom properties
bool isContainer() const;
QWidget *createWidget(QWidget *parent);
private:
bool initialized;
};
#endif
|
#pragma once
#include <vector>
#include <math.h>
using namespace std;
struct Point2D
{
float x;
float y;
};
typedef vector<Point2D> PT2DVEC;
class ConvexHull2D
{
public:
ConvexHull2D(void);
ConvexHull2D(PT2DVEC pts);
~ConvexHull2D(void);
void BuildConvexHull(PT2DVEC pts);
bool IfInConvexHull(float x, float y);
PT2DVEC& GetConvexHullPoints();
void GetBoundingBox(float& xMin, float& xMax, float& yMin, float& yMax);
private:
//返回(P1-P0)*(P2-P0)的叉积。
int Multiply(Point2D p1,Point2D p2,Point2D p0);
//返回(P1-P0)*(P2-P0)的点积
int Dot(Point2D p1,Point2D p2,Point2D p0);
//求平面上两点之间的距离
float Distance(Point2D p1,Point2D p2);
private:
PT2DVEC m_cvPoint;
Point2D ur;
Point2D ll;
};
|
#ifndef __GAME_SCENE_H__
#define __GAME_SCENE_H__
#include "cocos2d.h"
#include "Box2D/Box2D.h"
#define DIS_PIPE 900
USING_NS_CC;
class GameWorld : public Layer
{
public:
virtual bool init();
CREATE_FUNC(GameWorld);
static Scene* createScene();
virtual void update(float delta);
void setPhyWorld(PhysicsWorld* m_world);
private:
void loadingCallBack(Texture2D *texture);
void initWithAtlas();
void beforeStart();
void startGame();
void initNumber();
bool onContactBegin(const PhysicsContact& contact);
//bool onTouchBegan(Touch *touch, Event *event);
PhysicsWorld* m_world;
Sprite* bird, *spGorund, *spGorund2, *getReady, *spTutorial, *scorePanel, *gameOver, *reStart, *scoreBoard;
Node* pipes[2], *numbers[10], *numbers2[10];
float speed, pipeheight;
Size pipeSize, visibleSize;
//1 bef 2 gaming 3 die
int GameState;
int m_iScore;
};
#endif
|
#include <fstream>
#include <map>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
map<char, std::string> plChar;
void loadPolChar(){
plChar['Ą'] = "\\k{A}";
plChar['ą'] = "\\k{a}";
plChar['Ć'] = "\\'A";
plChar['ć'] = "\\'c";
plChar['Ę'] = "\\k{E}";
plChar['ę'] = "\\k{e}";
plChar['Ł'] = "\\L{}";
plChar['ł'] = "\\l{}";
plChar['Ń'] = "\\'N";
plChar['ń'] = "\\'n";
plChar['Ó'] = "\\'O";
plChar['ó'] = "\\'o";
plChar['Ś'] = "\\'S";
plChar['ś'] = "\\'s";
plChar['Ź'] = "\\'Z";
plChar['ź'] = "\\'z";
plChar['Ż'] = "\\.Z";
plChar['ż'] = "\\.z";
}
std::string convertPolishChar(std::string word) {
string newString = "";
for(int i = 0; i < word.length(); i++) {
if(plChar.find( word[i] ) != plChar.end()) {
//cout << "Znalazlem " << word[i] << endl;
newString.append(plChar[word[i]]);
}else{
string s(1, word[i]);
newString.append(s);
}
}
//for( map<char, string>::iterator ii=.begin(); ii!=Employees.end(); ++ii) {
// cout << (*ii).first << ": " << (*ii).second << endl;
//}
return newString;
}
int main() {
setlocale(LC_ALL,"");
loadPolChar();
ifstream infile("osoby.txt", ifstream::in);
//sprawdzamy, czy plik1.txt się otworzył
if(!infile.is_open()) {
cerr << "Unable to open osoby.txt" << endl;
return 1;
}
ofstream outfile("out.tex", ofstream::out);
//sprawdzamy, czy plik2.txt się otworzył
if(!outfile.is_open()) {
cerr << "Unable to open plik2.tex" << endl;
return 1;
}
//w tej zmiennej będziemy przechowywali linie
//odczytane z plik1.txt
string line;
//wczytujemy dane z plik1.txt
int index = 0;
outfile << "\\documentclass[a4paper,11pt]{article}" << endl;
outfile << "\\usepackage{polski}";
outfile << "\\begin{document}" << endl;
outfile << "\\begin{tabular}{|r|l|} \\hline" << endl;
//outfile << "\\pard\\intbl 1." << endl;
//outfile << "1.wawd \\cell" << endl;
//outfile << "\\pard\\intbl 2.\\cell" << endl;
//outfile << "\\row" << endl;
while(getline(infile, line)) {
//przerzuc linie do 2 pliku
//outfile << line << endl;
//wypisujemy odczytaną linię na standardowe wyjście
//cout << line << endl;
if( index == 2){
//outfile << "\\hline" << endl;
outfile << "\\end{tabular} \\\\" <<endl;
index = 1;
}else if(index == 1){
outfile << "\\end{tabular} \\\\" <<endl;
outfile << "&" <<endl;
//outfile << "\\hline" << endl;
index++;
}
outfile << "\\begin{tabular}{l}" << endl;
vector<string> data = split(line, ';');
outfile << "" << convertPolishChar(data[0])<<"\\\\" << endl;
outfile << "Urodziny: " << convertPolishChar(data[1]) << ", ";
outfile << convertPolishChar("Płeć: ")<< convertPolishChar(data[2]) << endl;
outfile << "\\\\" << endl;
outfile << "Wzrost: " << convertPolishChar(data[3]) << " m" << " " << endl;
outfile << "\\\\" << endl;
outfile << "E-mail: " << " \\\\ "
<< "" << convertPolishChar(data[4]) << "\\\\" << endl;
outfile << "Telefony: " << endl;
outfile << "\\\\" << endl;
for(int i = 5; i < data.size(); i++) {
vector<string> phoneNumbers = split(data[i], ',');
//cout <<"Ilosc numerow: "<< phoneNumbers.size();
for(int j = 0; j < phoneNumbers.size(); j ++){
vector<string> number = split(phoneNumbers[j], ':');
outfile << "" << convertPolishChar(number[0]) << ": " << convertPolishChar(number[1]) << endl;
outfile << "\\\\" << endl;
}
//cout << phoneNumbers[0] << ": " << phoneNumbers[1] << endl;
}
}
outfile << "\\end{tabular}" <<endl;
outfile << "\\end{document}" <<endl;
cin.get();
infile.close();
outfile.close();
return 0;
}
|
/* NO WARRANTY
*
* BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO
* WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
* LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS
* AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
* THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD
* THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
* NECESSARY SERVICING, REPAIR OR CORRECTION.
*
* IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
* WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY
* AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES,
* INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
* DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
* (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
* RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES
* OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
* PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#ifndef _DRAGDROPAREA_H_
#define _DRAGDROPAREA_H_
#include "DragDropobject.h"
class DragDropArea : public DragDropObject{
typedef DragDropObject inherited;
public:
DragDropArea();
virtual ~DragDropArea();
virtual BOOL paint(CDC* pDC);
virtual DragDropObject* PickInArea(CClientDC* pDC, CPoint ptToCheckLP, BOOL bSelectableOnly);
virtual void SetGrabChildSelection(BOOL bFlag) {m_bGrabChildSelection = bFlag;}
virtual BOOL GetGrabChildSelection() {return m_bGrabChildSelection;}
virtual POSITION AddChildAtHead(DragDropObject* pObject, BOOL bForceFirstDraw = TRUE);
virtual POSITION AddChildAtTail(DragDropObject* pObject, BOOL bForceFirstDraw = TRUE);
virtual POSITION GetFirstChildPos() const;
virtual DragDropObject* GetNextChild(POSITION& pos) const;
virtual void SendObjectToBack(DragDropObject* pObject);
virtual void BringObjectToFront(DragDropObject* pObject);
virtual BOOL ShrinkToFit();
virtual void Serialize(CArchive& ar);
CObList m_oblistObjects;
virtual DragDropObject* Clone() const;
protected:
virtual void GeometryChange(CRect* pRectPrevious);
virtual void GeometryChangeChild(DragDropObject* pChildObject);
virtual void SetDocument(DragDropDocument* pDocument);
virtual BOOL ValidateChildRect(DragDropObject* pChildObject);
BOOL m_bGrabChildSelection;
BOOL m_bShrinkToFitPending;
DECLARE_SERIAL(DragDropArea)
};
#endif
|
#include "Universe.h"
Universe::Universe() {
setStudentData();
}
void Universe::setStudentData() {
in.open("midtest.txt");
if(in.is_open()) {
for(int i = 0; i < 10; i++) {
Student *st = new Student();
in >> st->id;
in >> st->name;
in >> st->school;
in >> st->score;
st->showInfo();
studentList.push_back(st);
}
}
}
|
#include<iostream.h>
#include<conio.h>
class bank
{
public:
int ba,acc_no;
char name[20],type[20];
void get()
{
cout<<"\n enter the name:";
cin>>name;
cout<<"\n enter the accno;";
cin>>acc_no;
cout<<"\n enter the balance amount:";
cin>>ba;
cout<<"\n enter the type of acc:";
cin>>type;
}
void depo()
{
int amt,depo1=0;
cout<<"\n enter the deposite:";
cin>>amt;
depo1=amt;
depo1=depo1+ba;
cout<<"\n the balance is:"<<depo1;
ba=depo1;
}
void with()
{
int wa;
cout<<"\n enter the withdraw amt:";
cin>>wa;
if(wa>ba)
{
cout<<"\n not enough bal:";
}
else
{
ba=ba-wa;
cout<<"\n balance is:"<<ba;
}
}
void disp()
{
cout<<"\n the balnce is:"<<ba;
cout<<"\n the name is:"<<name;
}
};
void main()
{
int a,n,i;
clrscr();
bank b[5];
cout<<"\n enter the no:";
cin>>n;
for(i=0;i<n;i++)
b[i].get();
cout<<"\n MENU:";
cout<<"\n 1.deposite:";
cout<<"\n 2.withdraw:";
cout<<"\n 3.exit:";
do
{
cout<<"\n enter the choise:";
cin>>a;
switch(a)
{
case 1:
for(i=0;i<n;i++)
b[i].depo();
break;
case 2:
for(i=0;i<n;i++)
b[i].with();
break;
case 3:
break;
}
}while(a!=3);
for(i=0;i<n;i++)
b[i].disp();
getch();
}
|
//---------------------------------------------------------------------------
//#include "stdafx.h"
#pragma hdrstop
#include <math.h>
#include <fcntl.h>
#include <io.h>
#include <sys\stat.h>
#include <share.h>
#include "..\..\util\WorkStr.h"
#include "HandsGroup.h"
//---------------------------------------------------------------------------
void clGroupHands::operator +=(clGroupHands &gh)
{
for(unsigned i=0;i<gh.size();i++)
if(!this->Include(gh[i]))
this->push_back(gh[i]);
}
//---------------------------------------------------------------------------
void clGroupHands::operator =(tpListHand &list)
{
resize(CN_HAND);
for(int i=0;i<CN_HAND;i++)
(*this)[i]=list._nbH[i];
}
//---------------------------------------------------------------------------
void clGroupHands::WriteFile(int handle)
{
int cn=size();
_write(handle,&cn,sizeof(int));
_write(handle,&this[0],cn*sizeof(short));
}
//---------------------------------------------------------------------------
void clGroupHands::ReadFile(int handle)
{
int cn;
_read(handle,&cn,sizeof(int));
resize(cn);
_read(handle, &this[0], cn*sizeof(short));
}
//---------------------------------------------------------------------------
bool clGroupHands::AddHand(clHand hand)
{
short nbH=hand.NbHand();
if(Include(nbH))
return false;
this->push_back(nbH);
return true;
}
//---------------------------------------------------------------------------
bool clGroupHands::Include(clCard *card)
{
clHand *hand=(clHand *)card;
return Include(hand->NbHand());
}
//---------------------------------------------------------------------------
bool clGroupHands::Include(short nbH169)
{
for(unsigned i=0;i<size();i++)
if((*this)[i]==nbH169)
return true;
return false;
}
//---------------------------------------------------------------------------
void clGroupHands::FillBest(tpListHand *list,double ur)
{
clear();
for(int i=0;i<CN_HAND;i++)
if(list->_ur[i]>ur)
break;
else
this->push_back(list->_nbH[i]);
}
//---------------------------------------------------------------------------
void clGroupHands::FillBest(tpListHand *list,int cn)
{
resize(cn);
for(int i=0;i<cn;i++)
(*this)[i]=list->_nbH[i];
}
//---------------------------------------------------------------------------
void clGroupHands::FillFromGroup(clGroupHands *list,double ur)
{
clear();
for(unsigned i=0;i<list->size();i++)
{
ur-=HandWeight((*list)[i]);
if(ur<0)
break;
else
this->push_back((*list)[i]);
}
}
//---------------------------------------------------------------------------
void clGroupHands::FillFromGroup(clGroupHands *list,int cn)
{
resize(cn);
for(int i=0;i<cn;i++)
(*this)[i]=(*list)[i];
}
//---------------------------------------------------------------------------
void clGroupHands::FillAllHands()
{
resize(CN_HAND);
for(int i=0;i<CN_HAND;i++)
(*this)[i]=i;
}
//---------------------------------------------------------------------------
double clGroupHands::Weight()
{
double res=0;
for(unsigned i=0;i<size();i++)
res+=HandWeight((*this)[i]);
return res;
}
//---------------------------------------------------------------------------
void clGroupHands::Skip(clGroupHands *gh)
{
for(unsigned i=0;i<gh->size();i++)
Skip((*gh)[i]);
}
//---------------------------------------------------------------------------
void clGroupHands::Skip(short nbH)
{
for(unsigned i=0;i<size();i++)
if((*this)[i]==nbH)
erase(begin()+i);
}
//---------------------------------------------------------------------------
//***************************************************************************
//---------------------------------------------------------------------------
void clVGroupHands::WriteFile(int handle)
{
int cn=size();
_write(handle,&cn,sizeof(int));
for(int i=0;i<cn;i++)
(*this)[i].WriteFile(handle);
}
//---------------------------------------------------------------------------
void clVGroupHands::ReadFile(int handle)
{
int cn;
_read(handle,&cn,sizeof(int));
resize(cn);
for(int i=0;i<cn;i++)
(*this)[i].ReadFile(handle);
}
//---------------------------------------------------------------------------
int clVGroupHands::NbGroupForHand(short nbH)
{
for(unsigned i=0;i<size();i++)
{
clGroupHands &gh=(*this)[i];
for(unsigned j=0;j<gh.size();j++)
if(gh[j]==nbH)
return i;
}
return -1;
}
//---------------------------------------------------------------------------
//***************************************************************************
//---------------------------------------------------------------------------
void clGH0::operator -=(clGH0 &gh)
{
for(int i=0;i<gh._cnH;i++)
{
for(int j=0;j<_cnH;j++)
{
if(_nbH[j]==gh._nbH[i])
{
if(_weightH[j]<=gh._weightH[i])
{
DelRecord(j);
}
else
_weightH[j]-=gh._weightH[i];
break;
}
}
}
}
//---------------------------------------------------------------------------
bool clGH0::operator ==(clGH0 &gh)
{
if(_cnH != gh._cnH) return false;
for(int i=0;i<_cnH;i++)
if(fabs(_weightH[i]-gh._weightH[i])>DOUBLE_0)
return false;
return true;
}
//---------------------------------------------------------------------------
bool clGH0::operator !=(clGH0 &gh)
{
return !(*this==gh);
}
//---------------------------------------------------------------------------
int clGH0::CheckRecord(int nbHand)
{
for(int i=0;i<_cnH;i++)
if(_nbH[i]==nbHand)
return(i);
return(-1);
}
//---------------------------------------------------------------------------
bool clGH0::AddHand(int nbHand,int weightPerCent)
{
if(CheckRecord(nbHand)!=-1)
return(false);
_nbH[_cnH]=nbHand;
_weightH[_cnH]=weightPerCent*HandWeight(nbHand)/100;
_cnH++;
return(true);
}
//---------------------------------------------------------------------------
bool clGH0::DelRecord(int nbRecord)
{
#ifdef ERR_MESSAGE
if(!ErrCheck("clImproveGroupHands::DelRecord",nbRecord,0,_cnH-1))
return(false);
#endif
for(int i=nbRecord;i<_cnH-1;i++)
{
_nbH[i]=_nbH[i+1];
_weightH[i]=_weightH[i+1];
}
_cnH--;
return(true);
}
//---------------------------------------------------------------------------
clGH0::clGH0()
{
_cnH=0;
for(int i=0;i<CN_HAND;i++)
{
_nbH[i]=0;
_weightH[i]=0;
}
}
//---------------------------------------------------------------------------
double clGH0::Weight() const
{
double sum=0;
for(int i=0;i<_cnH;i++)
sum+=_weightH[i];
return(sum);
}
//---------------------------------------------------------------------------
void clGH0::ChangeWeight(int perCent,int nbRecord)
{
_weightH[nbRecord]=perCent*HandWeight(_nbH[nbRecord])/100;
}
//---------------------------------------------------------------------------
double clGH0::WeightHand(int nbH)
{
for(int i=0;i<_cnH;i++)
if(_nbH[i]==nbH)
return _weightH[i];
return(0);
}
//---------------------------------------------------------------------------
int clGH0::WeightInPerCent(int nbHand)
{
if(!ErrCheck("clGH0::WeightInPerCent",nbHand,0,CN_HAND-1))
return 0;
for(int i=0;i<_cnH;i++)
if(_nbH[i]==nbHand)
return(WeightInPerCentInArr(i));
return(0);
}
//---------------------------------------------------------------------------
/*int clGH0::WeightForAutoPlay(int nbHand)
{
if(!ErrCheck("clGH0::WeightForAutoPlay",nbHand,0,CN_HAND-1))
return 0;
for(int i=0;i<_cnH;i++)
if(_nbH[i]==nbHand)
return(WeightForAutoPlayInArr(i));
return(0);
} */
//---------------------------------------------------------------------------
void clGH0::AddOneToOneWithoutLess(clGH0 &gh)
{
for(int i=0;i<gh._cnH;i++)
{
int nbR=CheckRecord(gh._nbH[i]);
if(nbR==-1)
{
AddHand(gh._nbH[i],gh._weightH[i]);
}
else
{
_weightH[nbR]+=gh._weightH[i];
}
}
}
//---------------------------------------------------------------------------
int clGH0::WeightInPerCentInArr(int nb)
{
#ifdef ERR_MESSAGE
if(!ErrCheck("clImproveGroupHands::DelRecord",nb,0,_cnH-1))
return(0);
#endif
return(_weightH[nb]/HandWeight(_nbH[nb])*100+0.5);
}
//---------------------------------------------------------------------------
/*int clGH0::WeightForAutoPlayInArr(int nb)
{
#ifdef ERR_MESSAGE
if(!ErrCheck("clImproveGroupHands::DelRecord",nb,0,_cnH-1))
return(0);
#endif
return(_weightH[nb]/HandWeight(_nbH[nb])*10000+0.5);
} */
//---------------------------------------------------------------------------
double clGH0::CorrectWeight(double weightToCor)
{
for(int i=0;i<_cnH;i++)
{
if(WeightInPerCentInArr(i)>=100)
_weightH[i]=HandWeight(_nbH[i]);
}
double wHNew;
if(Weight()<weightToCor)
{
wHNew=CorrectStep();
while(wHNew<weightToCor)
{
wHNew=CorrectStep();
}
}
else
{
wHNew=CorrectStepLess();
while(wHNew>weightToCor)
{
wHNew=CorrectStepLess();
}
}
return(wHNew);
}
//---------------------------------------------------------------------------
void clGH0::CorrectFinal()
{
for(int i=_cnH-1;i>=0;i--)
{
if(WeightInPerCentInArr(i)>=100)
_weightH[i]=HandWeight(_nbH[i]);
if(WeightInPerCentInArr(i)<0)
DelRecord(i);
}
}
//---------------------------------------------------------------------------
void clGH0::CorrectWeightFaster(double weightToCor)
{
double sum=0,sum100=0;
for(int i=0;i<_cnH;i++)
{
if(WeightInPerCentInArr(i)<100)
sum+=_weightH[i];
else
sum100+=_weightH[i];
}
double cof=(weightToCor-sum100)/sum;
for(int i=0;i<_cnH;i++)
{
if(WeightInPerCentInArr(i)<100)
_weightH[i]*=cof;
if(WeightInPerCentInArr(i)>=100)
_weightH[i]=HandWeight(_nbH[i]);
}
}
void clGH0::CorrectWeightFasterWithoutAnyLess100(double weightToCor)
{
double sum=0;
for(int i=0;i<_cnH;i++)
{
sum+=_weightH[i];
}
double cof=(weightToCor)/sum;
for(int i=0;i<_cnH;i++)
{
_weightH[i]*=cof;
}
}
double clGH0::CorrectStep()
{
double sum=0;
for(int i=0;i<_cnH;i++)
{
double wH=HandWeight(_nbH[i]);
_weightH[i]*=1.01;
if(_weightH[i]>wH)
_weightH[i]=wH;
sum+=_weightH[i];
}
return(sum);
}
//---------------------------------------------------------------------------
double clGH0::CorrectStepLess()
{
double sum=0;
for(int i=0;i<_cnH;i++)
{
int perCent=WeightInPerCentInArr(i);
if(perCent<100)
_weightH[i]*=0.99;
sum+=_weightH[i];
}
return(sum);
}
//---------------------------------------------------------------------------
void clGH0::ReMake(double weightGroup)
{
if(weightGroup<=0) return;
double sum=Weight();
double x=sum/weightGroup;
for(int i=0;i<_cnH;i++)
_weightH[i]/=x;
}
//---------------------------------------------------------------------------
void clGH0::ReMake()
{
}
//---------------------------------------------------------------------------
void clGH0::AddOneHand(int nbHand)
{
int nb=CheckRecord(nbHand);
if(nb==-1)
{
_nbH[_cnH]=nbHand;
_weightH[_cnH]=1;
_cnH++;
}
else
_weightH[nb]++;
}
//---------------------------------------------------------------------------
void clGH0::ReadFilePack(int handle)
{
_read(handle,&_cnH,sizeof(_cnH));
_read(handle,_nbH,_cnH*sizeof(int));
_read(handle,_weightH,_cnH*sizeof(double));
}
//---------------------------------------------------------------------------
void clGH0::WriteFilePack(int handle)
{
_write(handle,&_cnH,sizeof(_cnH));
_write(handle,_nbH,_cnH*sizeof(int));
_write(handle,_weightH,_cnH*sizeof(double));
}
//---------------------------------------------------------------------------
int clGH0::SizeInFilePack()
{
return sizeof(_cnH)+_cnH*(sizeof(int)+sizeof(double));
}
//---------------------------------------------------------------------------
void clGH0::WriteFile(char *path)
{
int handle; _sopen_s(&handle, path, O_BINARY | O_CREAT | O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE);
WriteFile(handle);
_close(handle);
}
void clGH0::WriteFile(int handle)
{
_write(handle,&_cnH,sizeof(int));
_write(handle,&_nbH,CN_HAND*sizeof(int));
_write(handle,&_weightH,CN_HAND*sizeof(double));
}
void clGH0::ReadFile(char *path)
{
int handle; _sopen_s(&handle, path, O_BINARY | O_CREAT | O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE);
ReadFile(handle);
_close(handle);
}
void clGH0::ReadFile(int handle)
{
_read(handle,&_cnH,sizeof(int));
_read(handle,&_nbH,CN_HAND*sizeof(int));
_read(handle,&_weightH,CN_HAND*sizeof(double));
}
//---------------------------------------------------------------------------
bool clGH0::AddHand(int nbHand,double weight)
{
int nb=CheckRecord(nbHand);
if(nb==-1)
{
_nbH[_cnH]=nbHand;
_weightH[_cnH]=weight;
_cnH++;
}
else
_weightH[nb]+=weight;
return(true);
}
//---------------------------------------------------------------------------
void clGH0::operator +=(clGH0 &gh)
{
for(int i=0;i<gh._cnH;i++)
{
int nbR=CheckRecord(gh._nbH[i]);
if(nbR==-1)
AddHand(gh._nbH[i],gh._weightH[i]);
else
{
_weightH[nbR]+=gh._weightH[i];
if(WeightInPerCentInArr(nbR)>=100)
_weightH[nbR]=HandWeight(_nbH[nbR]);
}
}
}
//---------------------------------------------------------------------------
void clGH0::MultWeight(double mult) // умножаем все веса на mult
{
for(int i=0;i<_cnH;i++)
_weightH[i]*=mult;
}
//---------------------------------------------------------------------------
void clGH0::FillBestHands(tpListHand *gr,int cn)
{
_cnH=cn;
for(int i=0;i<_cnH;i++)
{
int nb=gr->_nbH[i];
double w=HandWeight(nb);
_nbH[i]=nb;
_weightH[i]=w;
}
}
//---------------------------------------------------------------------------
void clGH0::FillBestHands(tpListHand *gr,double weight)
{
for(_cnH=0;_cnH<CN_HAND;_cnH++)
{
int nb=gr->_nbH[_cnH];
double w=HandWeight(nb);
_nbH[_cnH]=nb;
if(weight>w)
{
weight-=w;
_weightH[_cnH]=w;
}
else
{
_weightH[_cnH]=weight;
_cnH++;
break;
}
}
}
//---------------------------------------------------------------------------
void clGH0::FillBestHands(tpListHand *gr,double w0,double w1)
{
double sum=0;
int i,nb;
for(i=0;i<CN_HAND;i++)
{
nb=gr->_nbH[i];
double w=HandWeight(nb);
sum+=w;
if(sum>w0)
break;
}
sum-=w0;
_cnH=1;
_nbH[0]=nb;
double weight=w1-w0;
if(weight>sum)
_weightH[0]=sum;
else
{
_weightH[0]=weight;
return;
}
for(i++;i<CN_HAND;i++)
{
int nb=gr->_nbH[i];
double w=HandWeight(nb);
_nbH[_cnH]=nb;
if(w<weight)
{
weight-=w;
_weightH[_cnH++]=w;
}
else
{
_weightH[_cnH]=weight;
_cnH++;
break;
}
}
}
//---------------------------------------------------------------------------
void clGH0::BuildFrom(clGH0 *gr,double weight)
{
#ifdef ERR_MESSAGE
if(!ErrCheck("clGH0::BuildFrom",gr->_cnH,0,CN_HAND)) return;
#endif
double sumAll=0;
for(int i=0;i<gr->_cnH;i++)
{
_nbH[i]=gr->_nbH[i];
if(sumAll+gr->_weightH[i]>weight)
{
_weightH[i]=(weight-sumAll)/gr->_weightH[i]*HandWeight(_nbH[i]);
_cnH=i+1;
return;
}
_weightH[i]=HandWeight(_nbH[i]);
sumAll+=gr->_weightH[i];
}
_cnH=gr->_cnH;
}
//---------------------------------------------------------------------------
void clGH0::FillBestHands(clGH0 *gr,double weight)
{
#ifdef ERR_MESSAGE
if(!ErrCheck("clGH0::FillBestHands",gr->_cnH,0,CN_HAND)) return;
#endif
double sumAll=0;
for(int i=0;i<gr->_cnH;i++)
{
_nbH[i]=gr->_nbH[i];
if(sumAll+gr->_weightH[i]>weight)
{
_weightH[i]=weight-sumAll;
_cnH=i+1;
return;
}
_weightH[i]=gr->_weightH[i];
sumAll+=gr->_weightH[i];
}
_cnH=gr->_cnH;
}
//---------------------------------------------------------------------------
void clGH0::RemoveBestHands(clGH0 *gr,double weight)
{
for(int i=0;i<gr->_cnH;i++)
{
int nb=CheckRecord(gr->_nbH[i]);
if(nb==-1)
{
nb=_cnH;
this->AddHand(gr->_nbH[i],0.);
}
if(gr->_weightH[i]>weight)
{
_weightH[nb]+=weight;
gr->_weightH[nb]-=weight;
return;
}
weight-=gr->_weightH[i];
_weightH[nb]+=gr->_weightH[i];
gr->_weightH[i]=0;
}
}
//---------------------------------------------------------------------------
void clGH0::FillBestHands(clGH0 *gr,double w0,double w1)
{
double sum=0;
int i,nb;
for(i=0;i<gr->_cnH;i++)
{
nb=gr->_nbH[i];
double w=gr->_weightH[i];
sum+=w;
if(sum>w0)
break;
}
sum-=w0;
_cnH=1;
_nbH[0]=nb;
double weight=w1-w0;
if(weight>sum)
{
_weightH[0]=sum;
weight-=sum;
}
else
{
_weightH[0]=weight;
return;
}
for(i++;i<gr->_cnH;i++)
{
int nb=gr->_nbH[i];
double w=gr->_weightH[i];
_nbH[_cnH]=nb;
if(w<weight)
{
weight-=w;
_weightH[_cnH++]=w;
}
else
{
_weightH[_cnH]=weight;
_cnH++;
break;
}
}
}
//---------------------------------------------------------------------------
void clGH0::ClearNullRec()
{
int nb=0;
for(int i=0;i<_cnH;i++)
if(_weightH[i]>DOUBLE_0)
{
_nbH[nb]=_nbH[i];
_weightH[nb++]=_weightH[i];
}
_cnH=nb;
}
//---------------------------------------------------------------------------
void clGH0::FillAllHands()
{
for(int i=0;i<CN_HAND;i++)
{
_nbH[i]=i;
_weightH[i]=HandWeight(i);
}
_cnH=CN_HAND;
}
//---------------------------------------------------------------------------
void clGH0::Cut(double w0,double weight)
{
int i=0;
for(;i<_cnH;i++)
if(_weightH[i]<w0)
w0-=_weightH[i];
else break;
if(i==_cnH)
{
_cnH=0;
return;
}
_weightH[i]-=w0;
int j=0,cn=_cnH-i;
for(;j<cn;j++,i++)
{
_nbH[j]=_nbH[i];
if(_weightH[i]<weight)
{
_weightH[j]=_weightH[i];
weight-=_weightH[i];
if(weight<DOUBLE_0)
break;
}
else
{
_weightH[j]=weight;
break;
}
}
_cnH=j+1;
}
//---------------------------------------------------------------------------
void clGH0::Skip(clGH0 *gh)
{
for(int i=0;i<gh->_cnH;i++)
{
int nbR=CheckRecord(gh->_nbH[i]);
if(nbR==-1) continue;
_weightH[nbR]-=gh->_weightH[i];
if(_weightH[nbR]<=0)
DelRecord(nbR);
}
}
//---------------------------------------------------------------------------
void clGH0::SkipHand(int nbH,double weight)
{
for(int i=0;i<_cnH;i++)
if(_nbH[i]==nbH)
{
_weightH[i]-=weight;
if(_weightH[i]<DOUBLE_0)
DelRecord(i);
break;
}
}
//---------------------------------------------------------------------------
void clGH0::SkipHandInArr(int nb,double weight)
{
_weightH[nb]-=weight;
if(_weightH[nb]<DOUBLE_0)
DelRecord(nb);
}
//---------------------------------------------------------------------------
void clGH0::operator =(tpListHand &list)
{
for(int i=0;i<CN_HAND;i++)
{
_nbH[i]=list._nbH[i];
_weightH[i]=HandWeight(_nbH[i]);
}
_cnH=CN_HAND;
}
//---------------------------------------------------------------------------
void clGH0::operator =(clGroupHands &gh)
{
for(unsigned i=0;i<gh.size();i++)
{
_nbH[i]=gh[i];
_weightH[i]=HandWeight(_nbH[i]);
}
_cnH=gh.size();
}
//---------------------------------------------------------------------------
void clGH0::operator =(int nbHand)
{
_nbH[0]=nbHand;
_weightH[0]=1;
_cnH=1;
}
//---------------------------------------------------------------------------
bool clGH0::IsFull()
{
return(_cnH==CN_HAND && fabs(Weight()-1)<DOUBLE_0);
// return _cnH==CN_HAND;
}
//---------------------------------------------------------------------------
void clGH0::ChangeGH(clGH0 *gh,double ch)
{
for(int i=0;i<_cnH;i++)
{
double w=gh->WeightHand(_nbH[i]);
_weightH[i]+=(w-_weightH[i])*ch;
}
for(int i=0;i<gh->_cnH;i++)
if(!IsHand(gh->_nbH[i]))
AddHand(gh->_nbH[i],gh->_weightH[i]*ch);
}
//---------------------------------------------------------------------------
bool clGH0::IsHand(int nbH)
{
for(int i=0;i<_cnH;i++)
if(_nbH[i]==nbH)
return true;
return false;
}
//---------------------------------------------------------------------------
void clGH0::ReStraight(tpListHand &list)
{
int cn=0;
for(int i=0;i<CN_HAND;i++)
{
if(cn==_cnH) break;
int nb=CheckRecord(list._nbH[i]);
if(nb != -1)
{
int a=_nbH[nb];
_nbH[nb]=_nbH[cn];
_nbH[cn]=a;
double d=_weightH[nb];
_weightH[nb]=_weightH[cn];
_weightH[cn]=d;
cn++;
}
}
}
//---------------------------------------------------------------------------
void clGH0::operator =(clShortGroupHands &gh)
{
_cnH=0;
for(unsigned i=0;i<gh.size();i++)
{
_nbH[_cnH]=gh[i]._nbHand;
_weightH[_cnH++]=gh[i]._cn;
}
}
//---------------------------------------------------------------------------
double clGH0::Norm(double sum)
{
double w=Weight();
if(w<DOUBLE_0) return w;
sum/=w;
for(int i=0;i<_cnH;i++)
_weightH[i]*=sum;
return w;
}
//---------------------------------------------------------------------------
clAnsiString clGH0::GetString(int nb)
{
char str[12];
clAnsiString as=clHand::NameHand(_nbH[nb],str);
as+=(clAnsiString)" "+WSDoubleToAS(_weightH[nb],6);
return as;
}
//---------------------------------------------------------------------------
//***************************************************************************
//***************************************************************************
//---------------------------------------------------------------------------
void clGH1::ReCalc()
{
_wGr=0;
for(int i=0;i<_cnH;i++)
{
if(_weightH[i]<0)
ErrMessage("отрицательный вес","clImproveGroupHands(clGH1::ReCalc)");
_wGr+=_weightH[i];
_info[i]._wProc=WeightInPerCentInArr(i);
clHand::NameHand(_nbH[i],_info[i]._nameH);
}
}
//---------------------------------------------------------------------------
void clGH1::FillAllHands()
{
for(int i=0;i<CN_HAND;i++)
{
_nbH[i]=i;
_weightH[i]=HandWeight(i);
}
_cnH=CN_HAND;
ReCalc();
}
//---------------------------------------------------------------------------
void clGH1::operator =(tpListHand &list)
{
*(clGH0 *)this=list;
ReCalc();
}
//---------------------------------------------------------------------------
void clGH1::operator =(int nbHand)
{
_nbH[0]=nbHand;
_weightH[0]=HandWeight(nbHand);
_cnH=1;
_info[0]._wProc=100;
clHand::NameHand(nbHand,_info[0]._nameH);
}
//---------------------------------------------------------------------------
void clGH1::operator +=(clGH1 &gh)
{
*(clGH0 *)this+=gh;
ReCalc();
}
//---------------------------------------------------------------------------
void clGH1::Skip(clGH1 *gh)
{
clGH0::Skip((clGH0 *)gh);
ReCalc();
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
clImproveGroupHands HGBuildGroup(int cn)
{
clImproveGroupHands gh;
for(int i=0;i<cn;i++)
{
gh._nbH[i]=glListHand._nbH[i];
gh._weightH[i]=HandWeight(gh._nbH[i]);
}
int cnH=4*cn;
#ifdef ERR_MESSAGE
if(cnH==cn)
{
ErrMessage("Error","HGBuildGroup");
return gh;
}
#endif
double step=1./(cnH-cn);
if(cnH>CN_HAND)
{
cnH=CN_HAND;
if(step>0.01)
step=0.01;
}
gh._cnH=cnH;
for(int i=cn;i<cnH;i++)
{
gh._nbH[i]=glListHand._nbH[i];
gh._weightH[i]=(1-(i+1-cn)*step)*HandWeight(gh._nbH[i]);
}
return gh;
}
//---------------------------------------------------------------------------
void HGLineApr(clImproveGroupHands *gh1,clImproveGroupHands *gh2,double dw)
{
for(int i=0;i<gh2->_cnH;i++)
{
gh2->_weightH[i]*=dw;
if(i<gh1->_cnH)
gh2->_weightH[i]+=gh1->_weightH[i]*(1-dw);
}
}
//---------------------------------------------------------------------------
#define OLD_HANDGROUP
clImproveGroupHands HGGet3BetGroup(double weightGr)
{
#ifdef OLD_HANDGROUP
clImproveGroupHands gh0,gh;
gh0=glListHand;
gh.FillBestHands(&gh0,weightGr);
#ifdef GH_TEST
gh.ReCalc();
#endif
return gh;
#else
clImproveGroupHands gh1,gh2;
double weight1=HandWeight(glListHand._nbH[0]);
gh1._cnH=1;
gh1._nbH[0]=glListHand._nbH[0];
gh1._weightH[0]=weight1;
if(weightGr<weight1)
{
gh1._weightH[0]=weightGr;
return gh1;
}
for(int i=0;i<CN_HAND;i++)
{
gh2=HGBuildGroup(i+1);
double weight2=gh2.Weight();
if(weightGr<weight2)
{
double dw=(weightGr-weight1)/(weight2-weight1);
HGLineApr(&gh1,&gh2,dw);
#ifdef ERR_MESSAGE
dw=gh2.Weight();
if(fabs(dw-weightGr)>DOUBLE_0)
ErrMessage("Не правильно определили вес","HGGet3BetGroup");
ErrCheck("HGGet3BetGroup",gh2._cnH,0,CN_HAND);
#endif
break;
}
weight1=weight2;
gh1=gh2;
}
#ifdef GH_TEST
gh2.ReCalc();
#endif
return gh2;
#endif
}
//---------------------------------------------------------------------------
clImproveGroupHands HGGetCall3BetGroup(double weightGr)
{
return HGGet3BetGroup(weightGr);
}
//---------------------------------------------------------------------------
//***************************************************************************
//---------------------------------------------------------------------------
void clShortGroupHands::WriteFile(int handle)
{
unsigned cn=size();
_write(handle,&cn,sizeof(cn));
_write(handle,&this[0],cn*sizeof(stUnitGH));
}
//---------------------------------------------------------------------------
void clShortGroupHands::ReadFile(int handle)
{
unsigned cn;
_read(handle,&cn,sizeof(cn));
resize(cn);
_read(handle,&this[0],cn*sizeof(stUnitGH));
}
//---------------------------------------------------------------------------
void clShortGroupHands::operator = (clImproveGroupHands &gh)
{
clear();
for(int i=0;i<gh._cnH;i++)
if(gh._weightH[i]>0.5)
{
stUnitGH val;
val._nbHand=gh._nbH[i];
val._cn=gh._weightH[i]+0.5;
this->push_back(val);
}
}
//---------------------------------------------------------------------------
void clShortGroupHands::operator +=(clShortGroupHands &val)
{
for(unsigned i=0;i<val.size();i++)
{
int nb=FindNbHand(val[i]._nbHand);
if(nb==-1)
this->push_back(val[i]);
else
(*this)[nb]._cn+=val[i]._cn;
}
}
//---------------------------------------------------------------------------
int clShortGroupHands::FindNbHand(int nbHand)
{
for(unsigned i=0;i<size();i++)
if((*this)[i]._nbHand==nbHand)
return i;
return -1;
}
//---------------------------------------------------------------------------
unsigned clShortGroupHands::CnHands() const
{
unsigned cn=0;
for(unsigned i=0;i<size();i++)
cn+=(*this)[i]._cn;
return cn;
}
//---------------------------------------------------------------------------
//***************************************************************************
//***************************************************************************
//---------------------------------------------------------------------------
void GHTransformGH(clVGroupHands *vgh,clImproveGroupHands &gr,clImproveGroupHands &source)
{
gr.Clear();
for(int i=0;i<source.CnHand();i++)
{
int nbH=source.NbHandInArr(i);
// char str[6];
// clHand::NameHand(nbH,str);
int nb=vgh->NbGroupForHand(nbH);
gr.AddHand(nb,source.WeightHandInArr(i));
}
}
//---------------------------------------------------------------------------
void GHTransformGH(clVGroupHands *vgh,clImproveGroupHands &gr,const clShortGroupHands &source)
{
gr.Clear();
for(unsigned i=0;i<source.size();i++)
{
int nb=vgh->NbGroupForHand(source[i]._nbHand);
gr.AddHand(nb,(double)source[i]._cn);
}
}
//---------------------------------------------------------------------------
void GHTransformGHToHands(clVGroupHands *vgh,clImproveGroupHands &gr,clImproveGroupHands &source)
{
gr.Clear();
for(int i=0;i<source.CnHand();i++)
{
int nbGr=source.NbHandInArr(i);
double wGr=0;
clGroupHands &gh0=(*vgh)[nbGr];
for(unsigned j=0;j<gh0.size();j++)
wGr+=HandWeight(gh0[j]);
double k=source.WeightHandInArr(i)/wGr;
for(unsigned j=0;j<gh0.size();j++)
gr.AddHand(gh0[j],HandWeight(gh0[j])*k);
}
}
//---------------------------------------------------------------------------
#pragma package(smart_init)
|
#include <boost/program_options.hpp>
#include <iostream>
using namespace boost::program_options;
using namespace std;
#include "metis.hpp"
int main(int argc, char *argv[])
{
MetisContext c;
string input_file;
options_description desc("Allowed options");
desc.add_options()
("help,h", "print usage message")
("assemble,a", value<string>(&input_file), "assemble <filename>")
("run,r", value<string>(&input_file), "run <filename>");
uint8_t buf[10000];
uint8_t glbuf[10000];
uint64_t stack[500];
GLFWwindow *win = c.create_window(0,"title");
win=c.current_window(0);
win=c.current_window(0);
variables_map args;
try {
store(parse_command_line(argc, argv, desc), args);
if (args.count("help")) {
cout << desc << endl;
return 0;
}
} catch(required_option& e) {
cerr << "ERROR: " << e.what() << endl << endl;
return 1;
} catch(invalid_command_line_syntax &e) {
cerr << "ERROR: " << e.what() << endl << endl;
return 1;
}
if (args.count("assemble")) {
MetisVM m(buf,10000, stack, 5, glbuf, 10000);
MetisASM a;
a.assemble(args["assemble"].as<string>(),m);
m.save(args["assemble"].as<string>() + ".metis");
}
if (args.count("run")) {
//cout << args["run"].as<string>() << endl;
MetisVM m(buf,10000, stack, 5, glbuf, 10000);
m.load(args["run"].as<string>());
m.eval("init");
while(!glfwWindowShouldClose(win)) {
m.eval("mainloop");
glfwSwapBuffers(win);
glfwPollEvents();
}
}
}
|
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> left(n);
vector<int> right(n);
left[0] = 1;
right[n-1] = 1;
for(int i = 1; i < n; i++)
{
left[i] = left[i-1]*nums[i-1];
}
for(int i = n-2; i >=0; i--)
{
right[i] = right[i+1]*nums[i+1];
}
vector<int> result(n);
for(int i = 0; i < n; i++)
{
result[i] = left[i]*right[i];
}
return result;
}
};
|
#include <iostream>
#include "Log.h"
int main()
{
namespace clog = common::log;
clog::Error( clog::ERROR_CRITICAL, 1, "error1" );
clog::Error( clog::ERROR_CRITICAL, 2, "error2 %d %d", 10, 100 );
clog::Log( clog::LOG_F_N_O, clog::LOG_PACKET, 1, "log1" );
clog::Log( clog::LOG_F_N_O, clog::LOG_PACKET, 2, "log2", 11, 22 );
return 0;
}
|
#ifndef MODIFIERS_MODIFIERBASE_H
#define MODIFIERS_MODIFIERBASE_H
#include <boost/shared_ptr.hpp>
#include "Value.h"
namespace modifiers{
class ModifierBase{
public:
Value get();
protected:
virtual Value calculate()=0;
private:
unsigned long long int m_lastFrame;
Value m_value;
};
typedef boost::shared_ptr<ModifierBase> Modifier;
}
#endif // MODIFIERS_MODIFIERBASE_H
|
#include <sstream>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <argparser/test/mock/argparser.h>
#include <compressor/test/mock/compressor.h>
#include <compressor/cli.h>
class CLITests : public ::testing::Test {
protected:
void SetUp() override
{
argparser_ = std::make_unique<MockIArgparser>();
compressor_ = std::make_unique<MockICompressor>();
}
std::unique_ptr<MockIArgparser> argparser_;
std::unique_ptr<MockICompressor> compressor_;
std::string input_file_ = "input.txt";
std::string output_file_ = "output.txt";
argparser::IArgparser::container_type options_ = {
{"input", std::make_shared<argparser::Arg<std::string>>("input", "desc", input_file_)},
{"output", std::make_shared<argparser::Arg<std::string>>("output", "desc", output_file_)}
};
};
TEST_F(CLITests, Encoding)
{
EXPECT_CALL(*argparser_, add_argument(::testing::_)).Times(testing::AtLeast(4));
options_["encode"] = std::make_shared<argparser::Arg<bool>>("encode", "desc", true);
EXPECT_CALL(*argparser_, parse()).WillOnce(testing::Return(options_));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("input"))).WillOnce(testing::Return(true));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("output"))).WillOnce(testing::Return(true));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("encode"))).WillOnce(testing::Return(true));
EXPECT_CALL(*compressor_, encode(testing::_)).Times(testing::AtLeast(1));
auto cli = compressor::CLI(std::move(argparser_), std::move(compressor_));
cli.run();
}
TEST_F(CLITests, Decoding)
{
EXPECT_CALL(*argparser_, add_argument(::testing::_)).Times(testing::AtLeast(4));
options_["decode"] = std::make_shared<argparser::Arg<bool>>("decode", "desc", true);
EXPECT_CALL(*argparser_, parse()).WillOnce(testing::Return(options_));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("input"))).WillOnce(testing::Return(true));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("output"))).WillOnce(testing::Return(true));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("encode"))).WillOnce(testing::Return(false));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("decode"))).WillOnce(testing::Return(true));
EXPECT_CALL(*compressor_, decode(testing::_)).Times(testing::AtLeast(1));
auto cli = compressor::CLI(std::move(argparser_), std::move(compressor_));
cli.run();
}
TEST_F(CLITests, EmptyCommand)
{
EXPECT_CALL(*argparser_, add_argument(::testing::_)).Times(testing::AtLeast(4));
EXPECT_CALL(*argparser_, parse()).WillOnce(testing::Return(options_));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("input"))).WillOnce(testing::Return(true));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("output"))).WillOnce(testing::Return(true));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("encode"))).WillOnce(testing::Return(false));
EXPECT_CALL(*argparser_, has_argument(testing::StrEq("decode"))).WillOnce(testing::Return(false));
EXPECT_CALL(*compressor_, encode(testing::_)).Times(testing::AtLeast(0));
EXPECT_CALL(*compressor_, decode(testing::_)).Times(testing::AtLeast(0));
auto cli = compressor::CLI(std::move(argparser_), std::move(compressor_));
cli.run();
}
TEST_F(CLITests, EmptyFiles)
{
}
|
#include <iostream>
int main(){
float a,b;
char kt; // kt:ky tu
float kq;
std::cout << "Nhap gia tri 2 a va b : ";
std::cin >> a >> b;
std::cout << "\n Chuong trinh thuc hien 4 phep toan so hoc";
std::cout << "\n 1.Go dau + de thuc hien phep cong";
std::cout << "\n 2.Go dau - de thuc hien phep tru";
std::cout << "\n 3.go dau * de thuc hien phep tich";
std::cout << "\n 4.go dau / de thuc hien phep chia";
std::cout << "\n Hay nhap vao lua chon: " << std::endl;
std::cin >> kt;
if (kt=='+')
std::cout << "ket qua la: " << a+b << std::endl;
else if (kt=='-')
std::cout << "ket qua la: " << a-b << std::endl;
else if(kt=='*')
std::cout << "ket qua la: " << a*b << std::endl;
else if (kt=='/')
std::cout << "ket qua la: "<< (float)a/b << std::endl;
else
std::cout << "ban da chon khong dung phep toan ";
return 0;
}
|
#include <iostream>
#include <stack>
#include <stdint.h>
#include <vector>
// Register operations:
// PRIMITIVES:
// push i32
// push should check if the next stack index is greater than the
// stack size; if it is, the stack should first be extended by 10 items.
// Then set the next stack index to the pushed value.
// Finally increment the next stack index.
// pop
// pop should check if the next stack index is greater than 0; if it's not,
// skip the pop command.
// Otherwise, decrement the next stack index by 1 and return the value at
// the new index.
//
// COMPOUNDS:
// add
// Validation: next stack index > 1
// pop + pop + push
// subtract
// Validation: next stack index > 1
// multiply
// Validation: next stack index > 1
// divide
// Validation: next stack index > 1
// mod
// Validation: next stack index > 1
// not
// Validation: next stack index > 0
// greater
// Validation: next stack index > 1
// roll
// Validation: next stack index > 2 and stack[-2] >= 0
// Roll pops the stack and uses the stack value as the number of rolls.
// Then the stack is popped again and the stack value is used as the depth.
// Select the first n top values of the stack, where n is the absolute
// number of rolls. If the number of rolls is greater than 0, move the
// selected values down the stack by the depth.
// If the number of rolls is less than 0, move the selected values up the
// stack, starting from the bottom, by the depth.
// If the number of rolls is 0, do nothing.
//
// CONTROL FLOW:
// pointer
// Validation: next stack index > 0
// Pop the top value. If the value is 0 mod 4, then take the branch
// matching the current direction. If the value is 1 mod 4, then take the
// branch matching the next direction with a matching CC but the next DP.
// And so forth.
// switch
// Validation: next stack index > 0
// Pop the top value. If the value is 0 mod 2, then take the branch
// matching the current direction. If the value is 1 mod 2, then take the
// branch matching the next direction with matching DP but the next CC.
//
// INPUT:
// in (char), in (number)
// out (char), out (number)
typedef uint32_t piet_int;
std::stack<piet_int> stack;
std::stack<piet_int> &mondriaan_dump_stack() { return stack; }
extern "C" {
void mondriaan_runtime_push(piet_int value) { stack.push(value); }
void mondriaan_runtime_duplicate() {
if (stack.empty()) {
return;
}
stack.push(stack.top());
}
void mondriaan_runtime_out_char() {
if (stack.empty()) {
return;
}
std::cout << (char)stack.top();
stack.pop();
}
void mondriaan_runtime_out_number() {
if (stack.empty()) {
return;
}
std::cout << stack.top();
stack.pop();
}
uint8_t mondriaan_runtime_pointer() {
if (stack.empty()) {
return 0;
}
auto top = stack.top();
stack.pop();
return (uint8_t)(top % 4);
}
void mondriaan_runtime_in_number() {
std::string line;
std::getline(std::cin, line);
try {
stack.push((piet_int)std::stoul(line));
} catch (...) {
// Ignore
return;
}
}
void mondriaan_runtime_multiply() {
if (stack.size() < 2) {
return;
}
auto op1 = stack.top();
stack.pop();
auto op2 = stack.top();
stack.pop();
stack.push(op1 * op2);
}
void mondriaan_runtime_divide() {
if (stack.size() < 2) {
return;
}
auto divisor = stack.top();
stack.pop();
auto dividend = stack.top();
stack.pop();
stack.push(dividend / divisor);
}
void mondriaan_runtime_roll() {
// A roll is only useful if there exists:
// 1st = number of rolls
// 2nd = depth of rolls
// 3rd and more = values to roll. A single value is rolled to itself.
if (stack.size() < 3) {
return;
}
auto rolls = stack.top();
stack.pop();
auto depth = stack.top();
stack.pop();
// A roll can have no effect at all.
if (rolls > depth) {
rolls %= depth;
}
if (rolls == 0) {
std::cout << "Zero rolls!" << std::endl;
return;
}
if (depth > stack.size()) {
std::cout << "Greater than stack size?" << std::endl;
return;
}
// Apply the roll by collecting the relevant values, rearranging them
// and then reinserting them.
std::vector<piet_int> rollValues{};
for (uint32_t valuePop = 0; valuePop < depth; valuePop++) {
rollValues.push_back(stack.top());
stack.pop();
}
for (uint32_t roll = 0; roll < rolls; roll++) {
piet_int top = rollValues[0];
rollValues.erase(rollValues.begin());
rollValues.push_back(top);
}
for (uint32_t insertIndex = depth; insertIndex > 0; insertIndex--) {
stack.push(rollValues[insertIndex - 1]);
}
}
}
|
#pragma once
#include "cbullet.h"
class cEnemyBullet :
public cBullet
{
public:
virtual void Init();
public:
cEnemyBullet(void);
~cEnemyBullet(void);
};
|
#include <gtest/gtest.h>
#include "Common.h"
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
#ifndef _WIN32
::testing::GTEST_FLAG(catch_exceptions) = false;
::testing::GTEST_FLAG(throw_on_failure) = true;
#endif
int exitCode = RUN_ALL_TESTS();
// on windows don't close the console window immediately
#ifdef _WIN32
fflush(stdout);
getchar();
#endif
return exitCode;
}
|
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *next;
Node *random;
Node(int _val)
{
val = _val;
next = NULL;
random = NULL;
}
};
Node *copyRandomList(Node *head)
{
if (head == NULL)
return head;
unordered_map<Node *, Node *> mp;
Node *curr = head, *newNode;
while (curr != NULL)
{
newNode = new Node(curr->val);
mp[curr] = newNode;
curr = curr->next;
}
Node *output;
curr = head;
while (curr != NULL)
{
output = mp[curr];
output->next = mp[curr->next];
output->random = mp[curr->random];
curr = curr->next;
}
return mp[head];
}
|
#pragma once
#include <QString>
#include <functional>
/// отвечает за подключение к бд, инициализирует глобальный QSQL контекст
class DbConnector
{
public:
DbConnector();
// проверить, является ли пользователь админом
bool checkAdmin(const QString& name,const QString& password);
/// Попытка входа в систему
/// @param ifAdmin должна вернуть строку с именем пользователя, от лица которого заходит администратор
QString login(QString name, const QString& password, std::function<QString()> ifAdmin);
QString registration(const QString& name,const QString& password);
QStringList getProfessorNameList();
};
|
#ifndef QTL_NET_HTTP_HEADER_H_
#define QTL_NET_HTTP_HEADER_H_
#include <map>
#include <string>
#include <vector>
#include <boost/asio/streambuf.hpp>
namespace qtl {
namespace net {
namespace http {
struct Header {
typedef std::string string;
std::map< string, std::vector<string> > fields;
void Add(const string& key, const string& val);
string Get(const string& key) const;
void Set(const string& key, const string& val);
void Write(boost::asio::streambuf& buf) const;
};
} // namespace http
} // namespace net
} // namespace qtl
#endif // QTL_NET_HTTP_HEADER_H_
|
/*
* File: main.cpp
* Author: Vidya
*
* Created on March 30, 2013, 12:40 AM
*/
#include <cstdlib>
#include <iostream>
#include "Rover.h"
#include "Grid.h"
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
char command[100];
Rover rover;
int dimension;
Location final_pos;
cout << "Enter the dimension of the grid" << endl;
cin >> dimension;
Grid grid(dimension);
grid.inject_obstacles(2,3);
/*Location* obstacles = grid.get_obstacles();
int length = sizeof(obstacles)/sizeof(Location);
for(int k =0; k<length; k++) {
cout << "Obstacles " << k << " is: " << obstacles[k].x << " & " << obstacles[k].y << endl;
} */
cout << "Enter the commands for the rover" << endl;
cin >> command;
final_pos = rover.move(command, grid);
cout << "The rover is at (" << final_pos.y << "," << final_pos.x << ")" << endl;
}
|
// $Id: DLOAD.h,v 1.2 2013/02/12 18:56:13 david Exp $
#ifndef __PF2ASM_NODE_loadstore_DLOAD_H__
#define __PF2ASM_NODE_loadstore_DLOAD_H__
#include <cdk/nodes/Node.h>
#include "semantics/SemanticProcessor.h"
namespace pf2asm {
namespace node {
namespace loadstore {
class DLOAD: public cdk::node::Node {
public:
inline DLOAD(int lineno) :
cdk::node::Node(lineno) {
}
inline const char *name() const { return "DLOAD"; }
inline void accept(SemanticProcessor *sp, int level) {
sp->processDLOAD(this, level);
}
};
} // namespace nodes/loadstore
} // namespace node
} // namespace pf2asm
#endif
/*
* $Log: DLOAD.h,v $
* Revision 1.2 2013/02/12 18:56:13 david
* Major code cleanup and simplification. Uses CDK8. C++11 is required.
*
* Revision 1.1 2012/02/19 20:30:15 david
* Updated to support the new CDK7. Removed STRold, LOAD2, STORE2, EXTRN, GLOBL.
* Added DDUP, DLOAD, DSTORE, EXTERN, GLOBAL.
*
* Revision 1.2 2009/05/09 17:36:55 david
* Major node cleanup. Parser simplification.
*
* Revision 1.1 2009/02/25 07:31:57 david
* First working version of pf2asm. This version still uses
* byacc.
*
*
*/
|
/*
Copyright (C) 2011 Tal Pupko TalP@tauex.tau.ac.il.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ___computeCorrelations___GL
#define ___computeCorrelations___GL
#include "definitions.h"
#include "replacementModel.h"
#include "Parameters.h"
#include "gainLoss.h"
#include "extremeValDistribution.h"
/********************************************************************************************
rate4siteGL
*********************************************************************************************/
class computeCorrelations{
public:
explicit computeCorrelations(tree& tr, string& outDir, VVVVdouble* expChanges_PosNodeXY, VVVVdouble* expChanges_PosNodeXY_B=NULL);
virtual ~computeCorrelations() ;
computeCorrelations(const computeCorrelations& other) {*this = other;}
computeCorrelations& operator=(const computeCorrelations &other);
void runComputeCorrelations(const Vint& selectedPositions, const Vint& numOfGapsTillSite, const bool isNormalizeForBranch = false);
void printComputedCorrelations(const Vint& selectedPositions,const Vint& evolvingSites, const bool isNormalizeForBranch = false, const bool correlationForZscore = false, VVVdouble* correlationsVec=NULL, string* valType=NULL);
//void computeMeanAndSdPerBranch(Vdouble& meanEventsPerBranch01, Vdouble& meanEventsPerBranch10, Vdouble& sdEventsPerBranch01,Vdouble& sdEventsPerBranch10);
void fillMapValPerPosPerBranch(VVdouble& expEventsPerPosPerBranch,const string type, VVVVdouble& expChanges_PosNodeXY,const bool isNormalizeForBranch = true, MDOUBLE* cutOff_p =NULL);
void fillCorrPerSelectedSites(Vdouble& correlationPerPos,VVdouble& expEventsPerPosPerBranch,VVdouble& expEventsPerPosPerBranch_B,const int selectedSite, const bool isPearson=true);
void sumExpectationPerBranch(VVVVdouble& expChanges_PosNodeXY, VVVdouble& map_NodeXY);
MDOUBLE computeNminPerPair(const int site_A, const int site_B, const int typeIndex, const VVVdouble& exp_PosXY);
void computedCorrelationsRankBasedOnSimulatedData(const Vint& selectedPositions, VVVdouble& correlationPerSitePerPos, VVVdouble& correlationPerSitePerPos_B, VVVdouble& correlationPerSitePerPos_Pval);
void computedCorrelationsPValBasedOnSimulatedDataCoMap(VVVdouble& correlationPerSitePerPosReal,VVVVdouble& expChanges_PosXYReal, VVVdouble& correlationPerSitePerPos_Pval);
int computedCorrelationsPValBasedOnSimulatedDataCoMapBins(VVVdouble& correlationPerSitePerPosReal,vector<vector<bool> >& isComputePairWithRateAboveNim,VVVVdouble& expChanges_PosXYReal, VVVdouble& correlationPerSitePerPos_Pval
,map<int, map<int, map<string, map<string, MDOUBLE > > > >& correlationsData, Vdouble& rate4siteReal, Vint& selectedSites, Vint& numOfGapsTillSite, Vint& evolvingSites, bool isLastIteration);
void printComputedCorrelationsData(const bool isNormalizeForBranch, const bool correlationForZscore
,map<int, map<int, map<string, map<string, MDOUBLE > > > >& correlationsData, Vdouble& T_BH, bool isPairsAboveBH = false);
void printCorrelationsFrequencies(Vdouble& correlationsVecSorted, ofstream* simCorrelStream=NULL);
int produceSortedVectorsOfCorrelationsBinedByRate(MDOUBLE medianNminOfRealData, ofstream* simCorrelStream);
void produceSortedVectorsOfAllCorrelations(Vdouble& rate4siteSim);
VVVdouble pVals2qVals(VVVdouble& correlationsVec,map<int, map<int, map<string, map<string, MDOUBLE > > > >& correlationsData
, vector<vector<bool> >& isComputePairWithRateAboveNim, Vdouble& T_BH, Vint& selectedSites, Vint& evolvingSites);
void produceSymeticMatrix(VVVdouble& correlationPerSitePerPos_Pval, bool isMin=true);
void produceSortedVectorsOfAllCorrelations(const VVVdouble& correlationPerSitePerPos, Vdouble& pairWiseCorrelations, Vdouble& NminForPairsInPairWiseCorrelations);
VVVdouble getcorrelationPerSitePerPosVec(){return _correlationsPerSitePerPosVec;};
protected:
//members
int _alphabetSize;
tree _tr;
//sequenceContainer _sc;
sequence* _refSeq; // the reference sequence
string _outDir;
bool _isSilent;
VVVVdouble _expChanges_PosNodeXY; // Input, expChanges_PosNodeXY[pos][nodeID][fatherState][sonState] - after simulations and postProb
VVVdouble _expChanges_NodeXY; // Summed from _expChanges_PosNodeXY - to expChanges_NodeXY[nodeID][fatherState][sonState]
VVVdouble _exp_PosXY; // Summed from _expChanges_PosNodeXY - to expChanges_PosXY[Pos][fatherState][sonState]
bool _isTwoSetsOfInputForCorrelation; // when B is given
VVVVdouble _expChanges_PosNodeXY_B; // Input B (optional), expChanges_PosNodeXY[pos][nodeID][fatherState][sonState] - after simulations and postProb
VVVdouble _expChanges_NodeXY_B; // Summed from _expChanges_PosNodeXY - to expChanges_NodeXY[nodeID][fatherState][sonState]
// V required for correlation analysis
VVVdouble _expPerPosPerBranchVec; // expChanges_PosNodeXY[type][pos][nodeID], for specific type of event (from, to), may be adjusted for branch expectation
VVVdouble _expPerPosPerBranchVec_B;
// correlation vectors
VVVdouble _correlationsPerSitePerPosVec;
vector<bool> _isPearson; // [true, false]
vector<string> _EventTypes; // ['gain', 'loss', 'both']
map<string, int> _EventTypesMap;
map<string, map<string, int> > _EventTypesFromTo;
//vector< vector< map<string, MDOUBLE> > > _pairWiseCorrelationsAndNminSim; // pairWiseCorrelationsAndNmin[corrIndex][pairIndex][CorOrNmin][val], if CorOrNmin=0, val=correlation, if =1, val=Nmin
VVVdouble _pairWiseCorrelationsAndNminSim; // pairWiseCorrelationsAndNmin[corrIndex][0/1][pairIndex][val], if CorOrNmin=0, val=correlation, if =1, val=Nmin
VVdouble _corrVector;
VVdouble _NminSortedSim; // _NminSortedSim[CorType][], vector of all Nmins = Rates
vector<vector<extremeValDistribution > > _extremeValDistributions; // _NminSortedSim[CorType][], vector of all distributions, per bin
VVVdouble _correlationsSubSets; // to be filled by produceSortedVectorsOfCorrelationsBinedByRate
VVdouble _correlationSubSetsNminLimitValues; // to be filled by produceSortedVectorsOfCorrelationsBinedByRate
Vint _selectedSites;
int _numOfSamplesInLowRateFirstBin; // thus, the lowest p-value for correlations with low rate (below simulations) is limited
};
#endif
|
/*
--------------------------
Console.cpp
Ilya Bobkov KZ 2017 (c)
--------------------------*/
#include "Console.h"
void Console::Render(void) {
}
|
#pragma once
#include <SFML/Graphics.hpp>
#include <string>
class Button
{
private:
short unsigned buttonState;
sf::RectangleShape shape;
sf::Text text;
sf::Font font;
sf::Color idleColor, hoverColor, activeColor;
public:
Button(float x, float y, float width, float height,
std::string text, float size, sf::Font,
sf::Color idleColor, sf::Color hoverColor, sf::Color activeColor);
void checkClick(const sf::Vector2f mousePos);
const bool isPressed() const;
void render(sf::RenderTarget* target);
};
|
/*********************************************************************
Matt Marchant 2014 - 2016
http://trederia.blogspot.com
xygine - Zlib license.
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
*********************************************************************/
//allows classes to report data to a single point
#ifndef XY_REPORTS_HPP_
#define XY_REPORTS_HPP_
#ifdef _DEBUG_
#define REPORT(name, value) xy::Stats::report(name, value)
#else
#define REPORT(name, value)
#endif //_DEBUG_
#include <xygine/Config.hpp>
#include <SFML/System/Mutex.hpp>
#include <SFML/System/Lock.hpp>
#include <string>
#include <map>
namespace xy
{
namespace Stats
{
/*!
\brief Global access to stats information string
when using REPORT macro
*/
XY_EXPORT_API const std::string& getString();
/*!
\brief Used for global stat reporting
*/
XY_EXPORT_API void report(const std::string&, const std::string&);
/*!
\brief Clears the global stats report string
*/
XY_EXPORT_API void clear();
}
/*!
\brief Utility class for reporting statistics
Useful for reporting data such as message bus statistics or
frame rate and printing it on screen
*/
class XY_EXPORT_API StatsReporter final
{
friend class App;
public:
StatsReporter();
~StatsReporter() = default;
StatsReporter(const StatsReporter&) = delete;
StatsReporter& operator = (const StatsReporter&) = delete;
/*!
\brief Reports a name/value pair
\param name Name of the value to report
\param value Value to report
Normally used to report information such as frame rate or key bindings
report("FPS", std::to_string(framerate));
report("Space", "Jump");
Once a name/value pair has been reported it will remain in the output
even if the value is not updated. To update a value simply report
the same name with a new value.
*/
void report(const std::string& name, const std::string& value);
/*!
\brief Removes a report
Should a name/value pair no longer need to be displayed use this
passing the name of the report to remove to remove it from the output
*/
void remove(const std::string& name);
/*!
\brief Returns a string containing all the reported data
This returns the output of all the reported data as a string
so that it may be displayed via any string supporting output
eg sf::Text
*/
const std::string& getString();
/*!
\brief Clears the current report string
*/
void clear();
/*!
\brief Toggles displaying the stats window
*/
static void show();
private:
std::map<std::string, std::string> m_data;
std::string m_string;
bool m_rebuildString;
sf::Mutex m_mutex;
static void draw();
};
}
#endif //XY_REPORTS_HPP_
|
#include <iostream>
using namespace std;
int Wire(int rate[], int n)
{
int * array = new int[n + 1];
array[0] = 0;
for (int i = 1; i <= n; i++)
{
int maxi = -99999;
for (int j = 0; j < i; j++)
{
maxi = max(maxi, array[i - j - 1]+ rate[j]);
}
array[i] = maxi;
}
return array[n];
}
int main()
{
int n1;
cout << "Enter Size of array: ";
cin >> n1;
int * input = new int[n1+1];
cout << "Enter the Rates " << endl;
for (int i =0; i < n1; i++) {
cout << "Enter Rate " << i << " : ";
cin >> input[i];
}
int a= Wire(input, n1);
cout << "Expected Result="<< a;
return 0;
}
|
#pragma once
namespace табуляция {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Summary for MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::TextBox^ textBox1;
protected:
private: System::Windows::Forms::TextBox^ textBox2;
private: System::Windows::Forms::TextBox^ textBox3;
private: System::Windows::Forms::ListBox^ listBox1;
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::ComboBox^ comboBox1;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::Label^ label4;
private: System::Windows::Forms::Button^ button2;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->textBox2 = (gcnew System::Windows::Forms::TextBox());
this->textBox3 = (gcnew System::Windows::Forms::TextBox());
this->listBox1 = (gcnew System::Windows::Forms::ListBox());
this->button1 = (gcnew System::Windows::Forms::Button());
this->comboBox1 = (gcnew System::Windows::Forms::ComboBox());
this->label1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label3 = (gcnew System::Windows::Forms::Label());
this->label4 = (gcnew System::Windows::Forms::Label());
this->button2 = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// textBox1
//
this->textBox1->Location = System::Drawing::Point(12, 28);
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(100, 20);
this->textBox1->TabIndex = 0;
//
// textBox2
//
this->textBox2->Location = System::Drawing::Point(12, 70);
this->textBox2->Name = L"textBox2";
this->textBox2->Size = System::Drawing::Size(100, 20);
this->textBox2->TabIndex = 1;
//
// textBox3
//
this->textBox3->Location = System::Drawing::Point(12, 110);
this->textBox3->Name = L"textBox3";
this->textBox3->Size = System::Drawing::Size(100, 20);
this->textBox3->TabIndex = 2;
//
// listBox1
//
this->listBox1->FormattingEnabled = true;
this->listBox1->Location = System::Drawing::Point(12, 136);
this->listBox1->Name = L"listBox1";
this->listBox1->Size = System::Drawing::Size(177, 95);
this->listBox1->TabIndex = 3;
//
// button1
//
this->button1->Location = System::Drawing::Point(242, 136);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(105, 23);
this->button1->TabIndex = 4;
this->button1->Text = L"Протабулировать";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
//
// comboBox1
//
this->comboBox1->FormattingEnabled = true;
this->comboBox1->Items->AddRange(gcnew cli::array< System::Object^ >(3) {L"(ln^3x + x^2)/sqrt(x+t)", L"sqrt(x+t) + 1/x",
L"cosx + tsin^2x"});
this->comboBox1->Location = System::Drawing::Point(226, 27);
this->comboBox1->Name = L"comboBox1";
this->comboBox1->Size = System::Drawing::Size(121, 21);
this->comboBox1->TabIndex = 5;
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(9, 12);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(62, 13);
this->label1->TabIndex = 6;
this->label1->Text = L"Введите A:";
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(9, 54);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(62, 13);
this->label2->TabIndex = 7;
this->label2->Text = L"Введите B:";
//
// label3
//
this->label3->AutoSize = true;
this->label3->Location = System::Drawing::Point(9, 94);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(66, 13);
this->label3->TabIndex = 8;
this->label3->Text = L"Введите dx:";
//
// label4
//
this->label4->AutoSize = true;
this->label4->Location = System::Drawing::Point(223, 12);
this->label4->Name = L"label4";
this->label4->Size = System::Drawing::Size(116, 13);
this->label4->TabIndex = 9;
this->label4->Text = L"Выберите уравнение:";
//
// button2
//
this->button2->Location = System::Drawing::Point(242, 208);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(105, 23);
this->button2->TabIndex = 10;
this->button2->Text = L"Выйти";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click);
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(359, 245);
this->Controls->Add(this->button2);
this->Controls->Add(this->label4);
this->Controls->Add(this->label3);
this->Controls->Add(this->label2);
this->Controls->Add(this->label1);
this->Controls->Add(this->comboBox1);
this->Controls->Add(this->button1);
this->Controls->Add(this->listBox1);
this->Controls->Add(this->textBox3);
this->Controls->Add(this->textBox2);
this->Controls->Add(this->textBox1);
this->Name = L"MyForm";
this->Text = L"MyForm";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
listBox1->Items->Clear();
double a, b, dx, result, x, t = 2.2;
String ^str1,^str2,^str3;
str1 = textBox1->Text;
str2 = textBox2->Text;
str3 = textBox3->Text;
a = Double::Parse(str1);
b = Double::Parse(str2);
dx = Double::Parse(str3);
for (x = a; x <= b; x+=dx) {
if (comboBox1->SelectedIndex == 0){
double one = Math::Log(x);
double two = Math::Pow(one, 3);
result = (two + Math::Pow(x, 2))/Math::Sqrt(x+t);
}
if (comboBox1->SelectedIndex == 1){
result = Math::Sqrt(x+t) + 1/x;
}
if (comboBox1->SelectedIndex == 2){
double one = Math::Sin(x);
result = Math::Cos(x) + t*Math::Pow(one, 2);
}
listBox1->Items->Add("При X=" + x.ToString("F3") + " y=" + result.ToString("F4"));
}
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
this->Close();
}
};
}
|
#include<iostream>
#include<math.h>
using namespace std;
void nonzero_element(int a[10][10],int n)
{
int c=0,i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if (a[i][j]!=0)
c++;
}
}
cout<<"Number of non-zero elements : "<<c<<endl;
}
void minor_diagonal(int a[10][10],int n)
{
cout<<"Elements below minor diagonal : ";
int i,j;
for(i=1;i<n;i++)
{
for(j=n-1;j>=n-i;j--)
{
cout<<" "<<a[i][j];
}
}
cout<<endl;
}
void sum_of_leading_diagonal(int a[10][10],int n)
{
int sum =0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
sum +=a[i][j];
}
}
cout<<"Sum of elements above leading diagonal : "<<sum<<endl;
}
void diagonal_product(int a[10][10],int n)
{
int diag1=1,diag2=1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
{
diag1 *=a[i][j];
}
}
}
int j=n-1;
for(int i=0;i<n;i++)
{
diag2 *=a[i][j];
j--;
}
cout<<"the product of diagonal left to right -> "<<diag1<<endl;
cout<<"the product of diagonal right to left -> "<<diag2<<endl;
}
int main()
{
int a[10][10],i,j,n;
cout<<"Enter order of the square matrix -> "<<endl;
cin>>n;
cout<<"Enter the elements of matrix -> "<<endl;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
cin>>a[i][j];
nonzero_element(a,n);
minor_diagonal(a,n);
sum_of_leading_diagonal(a,n);
diagonal_product(a,n);
return 0;
}
|
/**
* Copyright (C) 2017 Alibaba Group Holding Limited. 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 <string.h>
#include "multimedia/mmparam.h"
#include "multimedia/mm_debug.h"
namespace YUNOS_MM {
#define DATA_INIT_SIZE 32*1024
DEFINE_LOGTAG(MMParam)
MMParam::MMParam() : mDataSize(DATA_INIT_SIZE),
mDataWritePos(0),
mDataReadPos(0),
mStringReadPos(0),
mPointersReadPos(0)
{
mData = new uint8_t[DATA_INIT_SIZE];
}
MMParam::MMParam(const MMParam & another)
{
mData = NULL;
copy(&another);
}
MMParam::MMParam(const MMParam * another)
{
mData = NULL;
copy(another);
}
MMParam::~MMParam()
{
MM_RELEASE_ARRAY(mData);
}
template<class T>
mm_status_t MMParam::writeFixed(T val)
{
size_t valSize = sizeof(T);
MMLOGV("valSize: %d\n", valSize);
if ( (mDataWritePos + valSize) > mDataSize ) {
MMLOGE("no mem\n");
return MM_ERROR_NO_MEM;
}
*reinterpret_cast<T*>(mData + mDataWritePos) = val;
mDataWritePos += valSize;
return MM_ERROR_SUCCESS;
}
mm_status_t MMParam::writeInt32(int32_t val)
{
MMLOGV("val: %d", val);
return writeFixed(val);
}
mm_status_t MMParam::writeInt64(int64_t val)
{
MMLOGV("val: %" PRId64 "\n", val);
return writeFixed(val);
}
mm_status_t MMParam::writeFloat(float val)
{
MMLOGV("val: %f", val);
return writeFixed(val);
}
mm_status_t MMParam::writeDouble(double val)
{
MMLOGV("val: %f", val);
return writeFixed(val);
}
mm_status_t MMParam::writeCString(const char * val)
{
MMLOGV("val: %s", val);
mStrings.push_back(std::string(val));
return MM_ERROR_SUCCESS;
}
mm_status_t MMParam::writePointer(const MMRefBaseSP & pointer)
{
mPointers.push_back(pointer);
return MM_ERROR_SUCCESS;
}
mm_status_t MMParam::writeRawPointer(uint8_t *val)
{
MMLOGV("val: %p", val);
return writeFixed(val);
}
mm_status_t MMParam::readInt32(int32_t * val) const
{
MMLOGV("\n");
return readFixed(val);
}
mm_status_t MMParam::readInt64(int64_t * val) const
{
MMLOGV("\n");
return readFixed(val);
}
mm_status_t MMParam::readFloat(float * val) const
{
MMLOGV("\n");
return readFixed(val);
}
mm_status_t MMParam::readDouble(double * val) const
{
MMLOGV("\n");
return readFixed(val);
}
mm_status_t MMParam::readRawPointer(uint8_t **val) const
{
MMLOGV("\n");
return readFixed(val);
}
int32_t MMParam::readInt32() const
{
int32_t val;
mm_status_t ret = readInt32(&val);
if ( MM_ERROR_SUCCESS == ret ) {
return val;
}
return 0;
}
int64_t MMParam::readInt64() const
{
int64_t val;
mm_status_t ret = readInt64(&val);
if ( MM_ERROR_SUCCESS == ret ) {
return val;
}
return 0;
}
float MMParam::readFloat() const
{
float val;
mm_status_t ret = readFloat(&val);
if ( MM_ERROR_SUCCESS == ret ) {
return val;
}
return 0;
}
double MMParam::readDouble() const
{
double val;
mm_status_t ret = readDouble(&val);
if ( MM_ERROR_SUCCESS == ret ) {
return val;
}
return 0;
}
uint8_t* MMParam::readRawPointer() const
{
uint8_t *val;
mm_status_t ret = readRawPointer(&val);
if ( MM_ERROR_SUCCESS == ret ) {
return val;
}
return NULL;
}
template<class T>
mm_status_t MMParam::readFixed(T * val) const
{
size_t valSize = sizeof(T);
MMLOGV("valSize: %d\n", valSize);
if ( mDataReadPos >= mDataWritePos ) {
MMLOGV("no more\n");
return MM_ERROR_NO_MORE;
}
*val = *reinterpret_cast<const T*>(mData + mDataReadPos);
mDataReadPos += valSize;
return MM_ERROR_SUCCESS;
}
const char * MMParam::readCString() const
{
MMLOGV("\n");
if ( mStringReadPos >= mStrings.size() ) {
MMLOGV("no more\n");
return NULL;
}
return mStrings[mStringReadPos++].c_str();
}
MMRefBaseSP MMParam::readPointer() const
{
if ( mPointersReadPos >= mPointers.size() ) {
MMLOGV("no more\n");
return MMRefBaseSP((MMRefBase*)NULL);
}
return (mPointers[mPointersReadPos++]);
}
const MMParam & MMParam::operator=(const MMParam & another)
{
copy(&another);
return *this;
}
void MMParam::copy(const MMParam * another)
{
MMLOGV("\n");
MM_RELEASE(mData);
mData = new uint8_t[another->mDataSize];
memcpy(mData , another->mData,another->mDataSize);
mDataSize = another->mDataSize;
mDataWritePos = another->mDataWritePos;
mDataReadPos = 0;
mStrings = another->mStrings;
MMLOGV("mStrings size =%zu \n",mStrings.size());
//mStringReadPos = another->mStringReadPos;
mStringReadPos = 0;
mPointers = another->mPointers;
mPointersReadPos = 0;
MMLOGV("over\n");
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2006-2010 MStar Semiconductor, Inc.
// All rights reserved.
//
// Unless otherwise stipulated in writing, any and all information contained
// herein regardless in any format shall remain the sole proprietary of
// MStar Semiconductor Inc. and be kept in strict confidence
// (''MStar Confidential Information'') by the recipient.
// Any unauthorized act including without limitation unauthorized disclosure,
// copying, use, reproduction, sale, distribution, modification, disassembling,
// reverse engineering and compiling of the contents of MStar Confidential
// Information is unlawful and strictly prohibited. MStar hereby reserves the
// rights to any and all damages, losses, costs and expenses resulting therefrom.
//
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// This file is automatically generated by SkinTool [Version:0.2.3][Build:Jun 14 2017 09:17:51]
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////
// MAINFRAME styles..
/////////////////////////////////////////////////////
// INSTALL_BACKGROUND_ATSC styles..
/////////////////////////////////////////////////////
// INSTALL_BACKGROUND_BG_L styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Background_Bg_L_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_123 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_BACKGROUND_BG_C styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Background_Bg_C_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_124 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_BACKGROUND_BG_R styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Background_Bg_R_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_125 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_BACKGROUND_MENU styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Background_Menu_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_33 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_BACKGROUND_OK styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Background_Ok_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_36 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_PAGE_ATSC styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_TITLE_ATSC styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Title_Atsc_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_888 },
{ CP_NOON, 0 },
};
#define _Zui_Install_Main_Title_Atsc_Focus_DrawStyle _Zui_Install_Main_Title_Atsc_Normal_DrawStyle
#define _Zui_Install_Main_Title_Atsc_Disabled_DrawStyle _Zui_Install_Main_Title_Atsc_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_PAGE_LANGUAGE styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_TITLE styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_TITLE_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Title_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_889 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_FOCUS_BG styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Focus_Bg_Focus_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_34 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_890 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Text_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_891 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Text_Disabled_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_892 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_OPTION styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Option_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_652 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Option_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_653 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Option_Disabled_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_654 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_LEFT_ARROW styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Left_Arrow_Focus_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_37 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_RIGHT_ARROW styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Right_Arrow_Focus_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_38 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_NEXT styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_NEXT_RIGHT_ARROW styles..
#define _Zui_Install_Main_Osd_Language_Next_Right_Arrow_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Focus_Bg_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_LANGUAGE_NEXT_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Next_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_893 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Next_Text_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_894 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Language_Next_Text_Disabled_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_895 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_PAGE_TIME styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_TITLE styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_TITLE_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Title_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_896 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_FOCUS_BG styles..
#define _Zui_Install_Main_Osd_Time_Focus_Bg_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Focus_Bg_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_198 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Text_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_199 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Text_Disabled_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_200 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_OPTION styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Option_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_897 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Option_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_898 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Option_Disabled_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_899 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_LEFT_ARROW styles..
#define _Zui_Install_Main_Osd_Time_Left_Arrow_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Left_Arrow_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_RIGHT_ARROW styles..
#define _Zui_Install_Main_Osd_Time_Right_Arrow_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Right_Arrow_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_NEXT styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_NEXT_RIGHT_ARROW styles..
#define _Zui_Install_Main_Osd_Time_Next_Right_Arrow_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Focus_Bg_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_NEXT_TEXT styles..
#define _Zui_Install_Main_Osd_Time_Next_Text_Normal_DrawStyle _Zui_Install_Main_Osd_Language_Next_Text_Normal_DrawStyle
#define _Zui_Install_Main_Osd_Time_Next_Text_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Next_Text_Focus_DrawStyle
#define _Zui_Install_Main_Osd_Time_Next_Text_Disabled_DrawStyle _Zui_Install_Main_Osd_Language_Next_Text_Disabled_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_FORMAT styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_FORMAT_FOCUS_BG styles..
#define _Zui_Install_Main_Osd_Time_Format_Focus_Bg_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Focus_Bg_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_FORMAT_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Format_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_190 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Format_Text_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_191 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Format_Text_Disabled_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_192 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_FORMAT_OPTION styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Format_Option_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_900 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Format_Option_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_901 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Time_Format_Option_Disabled_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_902 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_FORMAT_LEFT_ARROW styles..
#define _Zui_Install_Main_Osd_Time_Format_Left_Arrow_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Left_Arrow_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_TIME_FORMAT_RIGHT_ARROW styles..
#define _Zui_Install_Main_Osd_Time_Format_Right_Arrow_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Right_Arrow_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_PAGE_ANT styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_TITLE styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_TITLE_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Ant_Title_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_903 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_FOCUS_BG styles..
#define _Zui_Install_Main_Osd_Ant_Focus_Bg_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Focus_Bg_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Ant_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_5 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Ant_Text_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_6 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Ant_Text_Disabled_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_7 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_OPTION styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Ant_Option_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_904 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Ant_Option_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_905 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Main_Osd_Ant_Option_Disabled_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_906 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_LEFT_ARROW styles..
#define _Zui_Install_Main_Osd_Ant_Left_Arrow_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Left_Arrow_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_RIGHT_ARROW styles..
#define _Zui_Install_Main_Osd_Ant_Right_Arrow_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Right_Arrow_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_NEXT styles..
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_NEXT_RIGHT_ARROW styles..
#define _Zui_Install_Main_Osd_Ant_Next_Right_Arrow_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Focus_Bg_Focus_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_MAIN_OSD_ANT_NEXT_TEXT styles..
#define _Zui_Install_Main_Osd_Ant_Next_Text_Normal_DrawStyle _Zui_Install_Main_Osd_Language_Next_Text_Normal_DrawStyle
#define _Zui_Install_Main_Osd_Ant_Next_Text_Focus_DrawStyle _Zui_Install_Main_Osd_Language_Next_Text_Focus_DrawStyle
#define _Zui_Install_Main_Osd_Ant_Next_Text_Disabled_DrawStyle _Zui_Install_Main_Osd_Language_Next_Text_Disabled_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE styles..
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND styles..
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Found_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_620 },
{ CP_NOON, 0 },
};
#define _Zui_Install_Scan_Result_Sub_Page_Item_Found_Text_Focus_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Found_Text_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_VALUE styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Found_Value_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_907 },
{ CP_NOON, 0 },
};
#define _Zui_Install_Scan_Result_Sub_Page_Item_Found_Value_Focus_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Found_Value_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_PROGRAM styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Found_Program_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_621 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG styles..
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_622 },
{ CP_NOON, 0 },
};
#define _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Text_Focus_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Text_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_VALUE styles..
#define _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Value_Normal_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Found_Value_Normal_DrawStyle
#define _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Value_Focus_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Found_Value_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_PROGRAM styles..
#define _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Program_Normal_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Found_Program_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL styles..
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_623 },
{ CP_NOON, 0 },
};
#define _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Text_Focus_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Text_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_VALUE styles..
#define _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Value_Normal_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Found_Value_Normal_DrawStyle
#define _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Value_Focus_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Found_Value_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_PROGRAM styles..
#define _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Program_Normal_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Found_Program_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH styles..
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_PERCENT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Percent_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_908 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_PERCENT_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Percent_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_625 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_626 },
{ CP_NOON, 0 },
};
#define _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Text_Focus_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Text_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH_VALUE styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Value_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_52 },
{ CP_NOON, 0 },
};
#define _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Value_Focus_DrawStyle _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Value_Normal_DrawStyle
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_CH_TYPE styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Item_Ch_Type_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_909 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// INSTALL_SCAN_RESULT_SUB_PAGE_PROGRESSBAR styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Install_Scan_Result_Sub_Page_Progressbar_Normal_DrawStyle[] =
{
{ CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_2 },
{ CP_NOON, 0 },
};
//////////////////////////////////////////////////////
// Window Draw Style List (normal, focused, disable)
WINDOWDRAWSTYLEDATA _MP_TBLSEG _GUI_WindowsDrawStyleList_Zui_Install_Guide_Atsc[] =
{
// HWND_MAINFRAME
{ NULL, NULL, NULL },
// HWND_INSTALL_BACKGROUND_ATSC
{ NULL, NULL, NULL },
// HWND_INSTALL_BACKGROUND_BG_L
{ _Zui_Install_Background_Bg_L_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_BACKGROUND_BG_C
{ _Zui_Install_Background_Bg_C_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_BACKGROUND_BG_R
{ _Zui_Install_Background_Bg_R_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_BACKGROUND_MENU
{ _Zui_Install_Background_Menu_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_BACKGROUND_OK
{ _Zui_Install_Background_Ok_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_MAIN_PAGE_ATSC
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_TITLE_ATSC
{ _Zui_Install_Main_Title_Atsc_Normal_DrawStyle, _Zui_Install_Main_Title_Atsc_Focus_DrawStyle, _Zui_Install_Main_Title_Atsc_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_PAGE_LANGUAGE
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_TITLE
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_TITLE_TEXT
{ _Zui_Install_Main_Osd_Language_Title_Text_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_LANGUAGE
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_FOCUS_BG
{ NULL, _Zui_Install_Main_Osd_Language_Focus_Bg_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_TEXT
{ _Zui_Install_Main_Osd_Language_Text_Normal_DrawStyle, _Zui_Install_Main_Osd_Language_Text_Focus_DrawStyle, _Zui_Install_Main_Osd_Language_Text_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_OPTION
{ _Zui_Install_Main_Osd_Language_Option_Normal_DrawStyle, _Zui_Install_Main_Osd_Language_Option_Focus_DrawStyle, _Zui_Install_Main_Osd_Language_Option_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_LEFT_ARROW
{ NULL, _Zui_Install_Main_Osd_Language_Left_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_RIGHT_ARROW
{ NULL, _Zui_Install_Main_Osd_Language_Right_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT_RIGHT_ARROW
{ NULL, _Zui_Install_Main_Osd_Language_Next_Right_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT_TEXT
{ _Zui_Install_Main_Osd_Language_Next_Text_Normal_DrawStyle, _Zui_Install_Main_Osd_Language_Next_Text_Focus_DrawStyle, _Zui_Install_Main_Osd_Language_Next_Text_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_PAGE_TIME
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_TITLE
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_TITLE_TEXT
{ _Zui_Install_Main_Osd_Time_Title_Text_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_TIME
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_FOCUS_BG
{ NULL, _Zui_Install_Main_Osd_Time_Focus_Bg_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_TEXT
{ _Zui_Install_Main_Osd_Time_Text_Normal_DrawStyle, _Zui_Install_Main_Osd_Time_Text_Focus_DrawStyle, _Zui_Install_Main_Osd_Time_Text_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_OSD_TIME_OPTION
{ _Zui_Install_Main_Osd_Time_Option_Normal_DrawStyle, _Zui_Install_Main_Osd_Time_Option_Focus_DrawStyle, _Zui_Install_Main_Osd_Time_Option_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_OSD_TIME_LEFT_ARROW
{ NULL, _Zui_Install_Main_Osd_Time_Left_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_RIGHT_ARROW
{ NULL, _Zui_Install_Main_Osd_Time_Right_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_NEXT
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_NEXT_RIGHT_ARROW
{ NULL, _Zui_Install_Main_Osd_Time_Next_Right_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_NEXT_TEXT
{ _Zui_Install_Main_Osd_Time_Next_Text_Normal_DrawStyle, _Zui_Install_Main_Osd_Time_Next_Text_Focus_DrawStyle, _Zui_Install_Main_Osd_Time_Next_Text_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_FOCUS_BG
{ NULL, _Zui_Install_Main_Osd_Time_Format_Focus_Bg_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_TEXT
{ _Zui_Install_Main_Osd_Time_Format_Text_Normal_DrawStyle, _Zui_Install_Main_Osd_Time_Format_Text_Focus_DrawStyle, _Zui_Install_Main_Osd_Time_Format_Text_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_OPTION
{ _Zui_Install_Main_Osd_Time_Format_Option_Normal_DrawStyle, _Zui_Install_Main_Osd_Time_Format_Option_Focus_DrawStyle, _Zui_Install_Main_Osd_Time_Format_Option_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_LEFT_ARROW
{ NULL, _Zui_Install_Main_Osd_Time_Format_Left_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_RIGHT_ARROW
{ NULL, _Zui_Install_Main_Osd_Time_Format_Right_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_PAGE_ANT
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_ANT_TITLE
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_ANT_TITLE_TEXT
{ _Zui_Install_Main_Osd_Ant_Title_Text_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_ANT
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_ANT_FOCUS_BG
{ NULL, _Zui_Install_Main_Osd_Ant_Focus_Bg_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_ANT_TEXT
{ _Zui_Install_Main_Osd_Ant_Text_Normal_DrawStyle, _Zui_Install_Main_Osd_Ant_Text_Focus_DrawStyle, _Zui_Install_Main_Osd_Ant_Text_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_OSD_ANT_OPTION
{ _Zui_Install_Main_Osd_Ant_Option_Normal_DrawStyle, _Zui_Install_Main_Osd_Ant_Option_Focus_DrawStyle, _Zui_Install_Main_Osd_Ant_Option_Disabled_DrawStyle },
// HWND_INSTALL_MAIN_OSD_ANT_LEFT_ARROW
{ NULL, _Zui_Install_Main_Osd_Ant_Left_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_ANT_RIGHT_ARROW
{ NULL, _Zui_Install_Main_Osd_Ant_Right_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_ANT_NEXT
{ NULL, NULL, NULL },
// HWND_INSTALL_MAIN_OSD_ANT_NEXT_RIGHT_ARROW
{ NULL, _Zui_Install_Main_Osd_Ant_Next_Right_Arrow_Focus_DrawStyle, NULL },
// HWND_INSTALL_MAIN_OSD_ANT_NEXT_TEXT
{ _Zui_Install_Main_Osd_Ant_Next_Text_Normal_DrawStyle, _Zui_Install_Main_Osd_Ant_Next_Text_Focus_DrawStyle, _Zui_Install_Main_Osd_Ant_Next_Text_Disabled_DrawStyle },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE
{ NULL, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND
{ NULL, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_TEXT
{ _Zui_Install_Scan_Result_Sub_Page_Item_Found_Text_Normal_DrawStyle, _Zui_Install_Scan_Result_Sub_Page_Item_Found_Text_Focus_DrawStyle, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_VALUE
{ _Zui_Install_Scan_Result_Sub_Page_Item_Found_Value_Normal_DrawStyle, _Zui_Install_Scan_Result_Sub_Page_Item_Found_Value_Focus_DrawStyle, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_PROGRAM
{ _Zui_Install_Scan_Result_Sub_Page_Item_Found_Program_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG
{ NULL, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_TEXT
{ _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Text_Normal_DrawStyle, _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Text_Focus_DrawStyle, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_VALUE
{ _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Value_Normal_DrawStyle, _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Value_Focus_DrawStyle, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_PROGRAM
{ _Zui_Install_Scan_Result_Sub_Page_Item_Analog_Program_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL
{ NULL, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_TEXT
{ _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Text_Normal_DrawStyle, _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Text_Focus_DrawStyle, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_VALUE
{ _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Value_Normal_DrawStyle, _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Value_Focus_DrawStyle, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_PROGRAM
{ _Zui_Install_Scan_Result_Sub_Page_Item_Digital_Program_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH
{ NULL, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_PERCENT
{ _Zui_Install_Scan_Result_Sub_Page_Item_Percent_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_PERCENT_TEXT
{ _Zui_Install_Scan_Result_Sub_Page_Item_Percent_Text_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH_TEXT
{ _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Text_Normal_DrawStyle, _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Text_Focus_DrawStyle, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH_VALUE
{ _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Value_Normal_DrawStyle, _Zui_Install_Scan_Result_Sub_Page_Item_Rfch_Value_Focus_DrawStyle, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_CH_TYPE
{ _Zui_Install_Scan_Result_Sub_Page_Item_Ch_Type_Normal_DrawStyle, NULL, NULL },
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_PROGRESSBAR
{ _Zui_Install_Scan_Result_Sub_Page_Progressbar_Normal_DrawStyle, NULL, NULL },
};
|
// This file has been generated by Py++.
#ifndef ImageCodec_hpp__pyplusplus_wrapper
#define ImageCodec_hpp__pyplusplus_wrapper
void register_ImageCodec_class();
#endif//ImageCodec_hpp__pyplusplus_wrapper
|
// Copyright 2020 JD.com, Inc. Galileo Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ==============================================================================
#pragma once
#include <brpc/channel.h>
#include <brpc/controller.h>
#include <brpc/protocol.h>
#include <condition_variable>
#include <memory>
#include "client/dgraph_type.h"
#include "common/types.h"
#include "discovery/discoverer.h"
#include "discovery/serialize.h"
#include "proto/rpc.pb.h"
namespace galileo {
namespace rpc {
void HandleResponse(brpc::Controller* cntl,
galileo::proto::QueryResponse* response,
std::function<void(bool)> callback);
class Client {
public:
Client();
~Client();
public:
void Query(const galileo::proto::QueryRequest& request,
galileo::proto::QueryResponse* response,
std::function<void(bool)> callback);
public:
bool Init(uint32_t shard_id,
std::shared_ptr<galileo::discovery::Discoverer> discoverer,
const galileo::client::DGraphConfig& config);
brpc::Channel* GetChannel();
void AddChannel(const std::string& host_port);
void RemoveChannel(const std::string& host_port);
private:
uint32_t shard_index_;
std::shared_ptr<galileo::discovery::Discoverer> discoverer_;
brpc::Channel* channel_;
galileo::common::ShardCallbacks shard_callbacks_;
std::mutex mt_;
std::condition_variable cv_;
int64_t timeout_ms_;
};
} // namespace rpc
} // namespace galileo
|
#ifndef _MATERIALSINGLETON_H_
#define _MATERIALSINGLETON_H_
#include "MaterialAPI.h"
#include <QList>
#include "DataProperty/DataBase.h"
#include <QHash>
class QDomDocument;
class QDomElement;
class QFile;
namespace GUI
{
class MainWindow;
}
namespace Material
{
class Material;
class MATERIALAPI MaterialSingleton :public DataProperty::DataBase
{
public:
//获取单例指针
static MaterialSingleton* getInstance();
//清空数据
void clear();
//获取材料数量
int getMaterialCount();
//获取第i个材料
Material* getMaterialAt(const int i);
//根据ID获取材料
Material* getMaterialByID(const int id);
//添加材料
void appendMaterial(Material* m);
//根据ID移除材料
void removeMaterialByID(const int id);
//将ID为id的材料添加至材料库
void appendToMaterialLib(const int id);
//从材料库中加载
void loadFromMaterialLib(GUI::MainWindow* m);
//从材料库删除
void removeFromMAterialLib(GUI::MainWindow* m);
QDomElement& writeToProjectFile(QDomDocument* doc, QDomElement* e) override;
void readDataFromProjectFile(QDomElement* ele) override;
private:
MaterialSingleton() = default;
~MaterialSingleton() = default;
QHash<QString, Material*> loadMaterilLib();
void writeToMaterialLib(QHash<QString, Material*> ms);
private:
static MaterialSingleton* _instance;
QList<Material*> _materialList{};
};
}
#endif
|
#ifndef MPIFARM_H
#define MPIFARM_H
#include <boost/mpi.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <fstream>
// include headers that implement a archive in simple text format
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/mpi.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#define PR(D) cout << #D " = " << D << "\n"
namespace mpi = boost::mpi;
using namespace std;
template <class T>
class VectorSet;
class IntsetWrapper;
class Graph;
typedef VectorSet<int> intset;
typedef pair<double,double> boundary;
extern int wrank;
/*class InitMessage{
friend class boost::serialization::access;
public:
InitMessage(){}
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
}
};*/
class InputMessage{
friend class boost::serialization::access;
public:
char operation;
//1: apply function on string address
//2: generate random graph and apply functions to it
//3: apply metropolis hasting to a graph with boundaries
//4: give the mus
string* address;
Graph* graph;
double* param;
uint n;
vector<boundary>* boundaries;
uint mutate_func;
InputMessage(string* a):address(a){
operation = 1;
}
InputMessage(){
operation = 2;
}
InputMessage(Graph* g, double* param_i, uint n_i, vector<boundary>* b, uint mf): graph(g), param(param_i), n(n_i), boundaries(b), mutate_func(mf){
operation = 3;
}
InputMessage(uint n_i):n(n_i){
operation = 5;
}
InputMessage(Graph* g){
operation = 6;
}
InputMessage(string* a, Graph* g, vector<boundary>* b, double* param_i):address(a),graph(g),param(param_i),boundaries(b){ //called by receiver
operation = 0;
}
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & operation;
if(operation == 1){
ar & *address;
}else if (operation == 2){
}else if (operation == 3){
ar & *graph;
ar & n;
ar & *param;
ar & *boundaries;
ar & mutate_func;
}else if(operation == 5){
ar & n;
}else if(operation == 6){
ar & graph;
}
}
};
class OutputMessage{
friend class boost::serialization::access;
public:
char result;
//1: function outputs only
//2: a graph and its function outputs
Graph* graph;
vector<double>* functionOutputs;
double p;
double aratio;
OutputMessage(){
result = 0;
} //Dirty hack
OutputMessage(vector<double>* f):result(1),functionOutputs(f){}
OutputMessage(Graph* g): result(2),graph(g){}
OutputMessage(Graph* g, double p_i, double aratio_i):result(3),graph(g),p(p_i),aratio(aratio_i){}
void setRes(char res){result = res;}
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
if(result == 0){
//Blank Message
}else if(result == 1){
ar & *functionOutputs;
}else if (result ==2){
ar & *graph;
}else{
ar & *graph;
ar & p;
ar & aratio;
}
}
};
class Worker{
public:
mpi::communicator& world;
string dir;
vector<string> functions;
vector<uint> numbMoments;
Worker(mpi::communicator& w);
};
void emptyfunc(InputMessage& i, OutputMessage& o);
class ComputationStatus{
public:
InputMessage input;
OutputMessage output;
uint status; //0: not executed, 1:sent to a worker, 2:completed
int worker; //worker it is/was executed on, numbered from 0 to n-1, initially -1
ComputationStatus(InputMessage& i, OutputMessage& o):input(i),output(o),status(0),worker(-1) {}
};
class WorkerStatus{
public:
int functionIndex; //function the server is working on, -1 if it is not busy
list<mpi::request>::iterator requestIterator;
WorkerStatus():functionIndex(-1){}
bool busy(){return functionIndex!=-1;};
};
class Master{
public:
mpi::communicator& world;
vector<ComputationStatus> cs;
vector<WorkerStatus> ws;
//bool initialised;
list<mpi::request> reqs;
Master(mpi::communicator& w):world(w),ws(world.size()-1){}
/*Master(mpi::communicator& w, InitMessage m):world(w),ws(world.size()-1),initialised(false){
initialise(m);
}
void initialise(InitMessage m){
if(!initialised){
vector<mpi::request> initReqs(ws.size());
for(uint i=0; i<ws.size(); i++){
initReqs[i] = world.isend(i+1, 0, m);
}
mpi::wait_all(initReqs.begin(),initReqs.end());
initialised = true;
}else{
cerr << "Master already initialised" << endl;
}
}*/
void addComputation(InputMessage& input, OutputMessage& output){cs.emplace_back(input,output);}
void execute()
{
execute(emptyfunc);
}
void execute(void (*func) (InputMessage&, OutputMessage&)){
//Execute all functionCalls
uint nextFunc = 0;
int p, newp;
p=0;
newp=0;
while(nextFunc<cs.size()) {
for(uint i = 0; i < ws.size() && nextFunc<cs.size(); i++) {
if(!ws[i].busy()) {
execute(i,nextFunc);
nextFunc++;
}
}
newp = nextFunc*100 / cs.size();
if(newp>p){
p = newp;
cout << "\r"<< "Execution: " << p << "%";
cout.flush();
}
if(nextFunc<cs.size()) {
pair< mpi::status, list<mpi::request>::iterator > p = mpi::wait_any(reqs.begin(),reqs.end());
clean(p,func);
}
}
while(reqs.size() > 0){
pair< mpi::status, list<mpi::request>::iterator > p = mpi::wait_any(reqs.begin(),reqs.end());
clean(p,func);
}
cout << " - Completed" << endl;
cs.clear();
for(uint i = 0; i < ws.size(); i++){
ws[i].functionIndex = -1;
}
}
void execute(uint worker, uint functionIndex)
{
world.send(worker+1,0,cs[functionIndex].input);
reqs.push_front(world.irecv(worker+1, mpi::any_tag, cs[functionIndex].output));
ws[worker].requestIterator = reqs.begin();
ws[worker].functionIndex = functionIndex;
cs[functionIndex].status = 1;
cs[functionIndex].worker = worker;
}
void clean(pair< mpi::status, list<mpi::request>::iterator >& p, void (*func) (InputMessage&, OutputMessage& ))
{
uint source = p.first.source() -1;
assert(&(*(ws[source].requestIterator)) == &(*(p.second)));
int findex = ws[source].functionIndex;
func(cs[findex].input,cs[findex].output);
cs[findex].status = 2;
ws[source].functionIndex = -1;
reqs.erase(ws[source].requestIterator);
}
};
#endif
|
#include <fstream>
#include <cmath>
#include <boost/test/unit_test.hpp>
#include <epecur/geometry.hpp>
#include <epecur/StdHits.hpp>
#define L(a) (sizeof(a) / sizeof(a[0]))
BOOST_AUTO_TEST_SUITE(StdHits_test)
BOOST_AUTO_TEST_CASE(check_basic_prop_and_drift)
{
std::ifstream f(PROJECT_SOURCE_DIR "/contrib/geom_apr10.c", ios::in);
Geometry g(f);
StdHits hook(g, NULL);
wire_id_t wires[] = {1, 3, 4, 6};
hook.handle_event_start();
hook.handle_prop_data(wires, wires + L(wires), 3); // dev_id=3
hook.handle_event_end();
BOOST_REQUIRE_EQUAL(hook.last_event[1].size(), L(wires)); // translates to chamber_id=1
hook.handle_event_start();
hook.handle_prop_data(wires, wires + L(wires), 3);
hook.handle_prop_data(wires, wires + L(wires), 4);
hook.handle_event_end();
BOOST_REQUIRE_EQUAL(hook.last_event[1].size(), 2 * L(wires));
std::vector<wire_id_t> drift_wires = {1, 2, 3, 4};
std::vector<uint16_t> drift_times = {10, 20, 1, 80};
hook.handle_event_start();
hook.handle_drift_data(drift_wires, drift_times, 122);
hook.handle_event_end();
BOOST_REQUIRE_EQUAL(hook.last_event[24].size(), drift_wires.size());
hook.handle_event_start();
hook.handle_event_end();
BOOST_REQUIRE_EQUAL(hook.last_event[1].size(), 0); // should be empty
BOOST_REQUIRE_EQUAL(hook.last_event[24].size(), 0);
}
BOOST_AUTO_TEST_CASE(check_drift_calib)
{
std::ifstream f(PROJECT_SOURCE_DIR "/contrib/geom_apr10.c", ios::in);
Geometry g(f);
StdHits::calibration_curve_t calibs;
vector<double> curve(100);
for(int i = 0; i < 100; i++)
{
curve[i] = min(i/100.0, 1.0);
}
calibs[24] = curve;
StdHits hook(g, &calibs);
std::vector<wire_id_t> drift_wires = {1, 20};
std::vector<uint16_t> drift_times = {0, 3};
hook.handle_event_start();
hook.handle_drift_data(drift_wires, drift_times, 122);
hook.handle_event_end();
BOOST_REQUIRE_EQUAL(hook.last_event[24].size(), 2 * drift_wires.size());
}
BOOST_AUTO_TEST_SUITE_END()
|
/*
time O(nklog(k)) and space O(1)
Node* merge(Node* a,Node* b)
{
if(a==NULL)
{
return b;
}
if(b==NULL)
{
return a;
}
Node* result = NULL;
if(a->data <= b->data)
{
result = a;
result->next = merge(a->next,b);
}
else
{
result = b;
result->next = merge(a,b->next);
}
return result;
}
arr[] is an array of pointers to heads of linked lists
and N is size of arr[]
Node * mergeKLists(Node *arr[], int N)
{
if(N==0)
{
return NULL;
}
if(N==1)
{
return arr[0];
}
for(int i=1;i<N;i++)
{
arr[0]=merge(arr[0],arr[i]);
}
return arr[0];
}*/
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "UI_CrossHair.generated.h"
class UImage;
UCLASS()
class THIRDPERSONSHOOTER_API UUI_CrossHair : public UUserWidget
{
GENERATED_BODY()
private:
UPROPERTY(Category="CrossHair", BlueprintReadOnly, meta=(BindWidget, AllowPrivateAccess = "true"))
UImage* TopCH;
UPROPERTY(Category="CrossHair", BlueprintReadOnly, meta=(BindWidget, AllowPrivateAccess = "true"))
UImage* BottomCH;
UPROPERTY(Category="CrossHair", BlueprintReadOnly, meta=(BindWidget, AllowPrivateAccess = "true"))
UImage* LeftCH;
UPROPERTY(Category="CrossHair", BlueprintReadOnly, meta=(BindWidget, AllowPrivateAccess = "true"))
UImage* RightCH;
UPROPERTY(Category="CrossHair", BlueprintReadOnly, meta=(BindWidget, AllowPrivateAccess = "true"))
UImage* CenterDot;
public:
#pragma region Properties
UPROPERTY(Category="CrossHair", EditAnywhere)
int LineLength;
UPROPERTY(Category="CrossHair", EditAnywhere)
int LineThickness;
UPROPERTY(Category="CrossHair", EditAnywhere)
int LineOffset;
UPROPERTY(Category="CrossHair", EditAnywhere)
float LineOpacity;
UPROPERTY(Category="CrossHair", EditAnywhere)
int CircleRadius;
UPROPERTY(Category="CrossHair", EditAnywhere)
float CircleOpacity;
UPROPERTY(Category="CrossHair", EditAnywhere)
FSlateColor CrossHairColor;
#pragma endregion
virtual void NativeTick(const FGeometry& MyGeometry, float InDeltaTime) override;
};
|
#ifndef XOROSHIRO_
#define XOROSHIRO_
#include "prng.h"
typedef long long unsigned int randtype;
class xorshiro
{
private:
prng rnd;
int a;
int b;
int c;
randtype s[2];
public:
xorshiro();
~xorshiro();
randtype rotl(const randtype, int k);
randtype xorshiro128p();
double rand(double min = 0., double max = 1.);
double landau(double x, double mu = 0., double sigma = 1.);
double landau_tc(double mu =0, double sigma = 1,
double xmin = 0, double xmax = 1,
double ymin = 0, double ymax = 0.5);
};
#endif //XOROSHIRO_
|
#include "Viiva.h"
#include "tilastot.h"
const float Viiva::MAX_KIIHTYVYYS = 10; //pitäisi olla 1.5
ofColor ViivanApufunktiot::asetaHSLnMukaan(float lh, float ls, float ll) {
float bh = lh;
if (ll <= 0.5)
ls *= ll;
else
ls *= 1 - ll;
float bb = ll + ls;
float bs = (2 * ls) / (ll + ls);
ofColor col = ofColor::white;
col.setHsb(bh, bs * 255, bb * 255);
return col;
}
float ViivanApufunktiot::getLightness(double s, double v) {
return ((2 - s) * v) / 2;
}
ofVec2f Viiva::paksuusSumeusVektori() {
return ofVec2f(paksuus.back(), sumeus.back());
}
ofVec3f ViivanApufunktiot::variRGBtoVec3(ofColor col) {
return ofVec3f(col.r, col.g, col.b);
}
ofColor ViivanApufunktiot::variRGBfromVec3(ofVec3f vec) {
return ofColor(ofClamp(vec.x, 0, 255), ofClamp(vec.y, 0, 255), ofClamp(vec.z, 0, 255));
}
//-----------------------------------------------------------------------------------------------------
std::string Viiva::nimeaViiva(std::string format) {
//aikamuoto on vvvv-kk-pp_hh-mm-ss
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, format.c_str(), timeinfo);
puts(buffer);
return std::string(buffer);
}
Viiva::Viiva() : improvisaatioLaskin(0), kalibraatioValmis(false),improvisaatioValmis(false),kohde(NULL) {
nimi = "viiva_" + nimeaViiva();
}
bool Viiva::muodostaViiva(
const std::vector<ofPoint>& pisteet_,
const std::vector<float>& paineet_,
const std::vector<float>& paksuudet_,
const std::vector<float>& sumeudet_,
const std::vector<VaiheetEnum>& vaiheet_,
const std::vector<ofColor>& varit_,
std::string nimi_
) {
tyhjennaOminaisuudet();
//tarkistetaan, että eri vektorien koot täsmäävät
int koko = pisteet_.size();
if( koko != paineet_.size()
|| koko != paksuudet_.size()
|| koko != sumeudet_.size()
|| koko != vaiheet_.size()
|| koko != varit_.size()
) {
cout << "muodosta viiva: vektorien koko ei täsmää: " << pisteet_.size() << " " << paineet_.size() << " " << paksuudet_.size() << " " << sumeudet_.size() << " " << vaiheet_.size() << " " << varit_.size() << "\n";
return false; //vektorit eivät ole samankokoisia!
}
//seuraavat vektorit voi kopioida suoraan:
pisteet = pisteet_;
vaiheet = vaiheet_;
varit = varit_;
nimi = nimi_;
//paineet, paksuudet ja sumeudet pitää laskea yksitellen:
for(int i=0; i<koko; i++) {
//asetetaan kalibrointitiedot kun kalibrointivaihe päättyy:
if(i>0) {
if(vaiheet[i] != Kalibroi && vaiheet[i-1] == Kalibroi)
asetaKalibraatio();
}
paine.lisaaJaLaske(paineet_[i], OTANNAN_KOKO);
paksuus.lisaaJaLaske(paksuudet_[i], OTANNAN_KOKO);
sumeus.lisaaJaLaske(sumeudet_[i], OTANNAN_KOKO);
}
//jos oli pelkkää kalibraatiota loppuun asti, tallennetaan lopussa kalibrointitiedot
if(!kalibraatioValmis)
asetaKalibraatio();
return true;
}
void Viiva::lisaaPiste(ofPoint paikka, float paine_, VaiheetEnum vaihe) {
if(size() != 0 && vaihe != LahestyKohdetta) {
ofColor col = varit[0];
varit.push_back(col);
}
if (!vaiheet.empty())
tarkistaVaihe(vaihe);
vaiheet.push_back(vaihe);
//lisaa uusin paine ja laske keskiarvot ja muut
paine.lisaaJaLaske(paine_, OTANNAN_KOKO);
ofVec2f uusiNopeus;
ofVec2f viimeNopeus;
//lasketaan nopeus ja kiihtyvyys edellisten pisteiden sijainnin perusteella. Nopeus vektorina, kiihtyvyydestä riittää suuruus:
if (pisteet.size() >= 1)
uusiNopeus = paikka - pisteet.back();
if (pisteet.size() >= 2)
viimeNopeus = pisteet.back() - pisteet[pisteet.size() - 2];
float kiihtyvyys = (uusiNopeus - viimeNopeus).length();
//paksuus on kiihtyvyys skaalattuna välille 0...1
float uusiPaksuus = ofClamp(kiihtyvyys / MAX_KIIHTYVYYS, 0, 1);
paksuus.lisaaJaLaske(uusiPaksuus, OTANNAN_KOKO);
//sumeus on paineen vastakohta
float uusiSumeus = 1 - paine.back();
sumeus.lisaaJaLaske(uusiSumeus, OTANNAN_KOKO);
//lisätään piste ja ominaisuudet viivaan
pisteet.push_back(paikka);
//korjataan vielä viivan alkupää, koska siihen jää muuten räjähtävä kiihtyvyys
if (pisteet.size() == 3) {
paksuus[0] = paksuus[2];
paksuus[1] = paksuus[2];
sumeus[0] = sumeus[2];
sumeus[1] = sumeus[2];
}
cout << "vektorien koot: " << pisteet.size() << " " << paine.size() << " " << sumeus.size() << " " << paksuus.size() << " " << varit.size() << " " << vaiheet.size() << "\n";
}
void Viiva::tarkistaVaihe(VaiheetEnum vaihe) {
if (vaihe != vaiheet.back())
nollaaLaskurit();
// Kalibraatio
if (vaihe == Kalibroi)
tarkistaKalibraatio();
// Improvisaatio
if (vaiheet.back() == Kalibroi && vaihe == Improvisoi) {
asetaKalibraatio();
} else if (vaihe == Improvisoi) {
tarkistaImprovisaatio();
}
//LahestyKohdetta
// if (vaihe == LahestyKohdetta) {
// lahestyKohdetta();
// tarkistaLahestyKohdetta();
// }
if (vaihe != LahestyKohdetta && vaiheet.back() == LahestyKohdetta) {
muutos = ViivanOminaisuus();
kohde.reset();
}
}
void Viiva::tarkistaKalibraatio() {
float konvergenssi;
if (paksuus.konvergenssit.back() == 0)
konvergenssi = sumeus.konvergenssit.back();
else if (sumeus.konvergenssit.back() == 0)
konvergenssi = paksuus.konvergenssit.back();
else
konvergenssi = paksuus.konvergenssit.back() * sumeus.konvergenssit.back();
if (konvergenssi > 0.6)
kalibraatioValmis = true;
else
kalibraatioValmis = false;
}
void Viiva::tarkistaImprovisaatio() {
if ((paksuusSumeusVektori() - kalibraatio.paksuusSumeusVektori()).length() > 0.02) {
improvisaatioLaskin++;
} else {
improvisaatioLaskin = 0;
}
if (improvisaatioLaskin > 10) {
improvisaatioValmis = true;
} else
improvisaatioValmis = false;
}
void Viiva::tarkistaLahestyKohdetta() {
lahestymisLaskuri++;
float muutoksenKeskihajonta = muutos.keskihajonnat.back();
cout << "muutos, koko: " << muutos.size() << "\n";
cout << "muutoksenKh: " << muutos.keskihajonnat.back() << "\n";
if (muutoksenKeskihajonta > 0.06 && lahestymisLaskuri > 50)
lahestyKohdettaValmis = true;
else if(muutoksenKeskihajonta < 0.06)
lahestymisLaskuri = 0;
}
void Viiva::lahestyKohdetta() {
muutos.lisaaJaLaske(muutoksenMaaraPolulla(), OTANNAN_KOKO);
//muokkaaVaria2(muutos.back(), muutos.keskihajonnat.back());
}
void Viiva::asetaKalibraatio() {
kalibraatio.vari = haeVari();
kalibraatio.paksuus = paksuus.back();
kalibraatio.paksuusKa = paksuus.keskiarvot.back();
kalibraatio.paksuusKh = paksuus.keskihajonnat.back();
kalibraatio.paksuusKhkh = paksuus.keskihajonnanKeskihajonnat.back();
kalibraatio.paksuusKonvergenssi = paksuus.konvergenssit.back();
kalibraatio.sumeus = sumeus.back();
kalibraatio.sumeusKa = sumeus.keskiarvot.back();
kalibraatio.sumeusKh = sumeus.keskihajonnat.back();
kalibraatio.sumeusKhkh = sumeus.keskihajonnanKeskihajonnat.back();
kalibraatio.sumeusKonvergenssi = sumeus.konvergenssit.back();
kalibraatioValmis = true;
}
void Viiva::muokkaaVaria() {
float sumeusMuunnos = (sumeus.keskiarvot.back() - kalibraatio.sumeusKa) * 0.7;
float paksuusMuunnos = (paksuus.keskiarvot.back() - kalibraatio.sumeusKa) * 127 * 0.7;
float lightness = getLightness(kalibraatio.vari.getSaturation() / 255, kalibraatio.vari.getBrightness() / 255) + sumeusMuunnos;
varit.back() = asetaHSLnMukaan(kalibraatio.vari.getHue(), (kalibraatio.vari.getSaturation() + paksuusMuunnos) / 255, lightness);
}
float Viiva::muutoksenMaaraPolulla() {
//lasketaan käyttäjän improvisoinninaikaisen eleen muutoksen projektio vektorilla, joka osoittaa lähtöpisteestä päämäärään, PS-koordinaatistossa.
//skaalataan niin, että päämäärän kohdalla projektio on 1 ja lähtöpisteessä 0
if (!kohde)
return 0;
//eli muokattavan projektio samankaltaisimmalla
ofVec2f m = paksuusSumeusKeskiarvoVektori();
ofVec2f s = kohde->paksuusSumeusKeskiarvoVektori();
ofVec2f k = kalibraatio.paksuusSumeusKeskiarvoVektori();
float projektio = (m - k).dot((s - k).getNormalized()) / (s - k).length();
if(projektio > 1)
projektio = 1;
if(projektio < 0)
projektio = 0;
return projektio;
return ofClamp(projektio, -0.5, 1.2);
}
void Viiva::muokkaaVaria2(float maara, float muutoksenKh) {
ofVec3f kohta = variRGBtoVec3(kalibraatio.vari) + (variRGBtoVec3(kohde->kalibraatio.vari) - variRGBtoVec3(kalibraatio.vari) ) * maara;
varit.back() = variRGBfromVec3(kohta);
varit.back().r = ofClamp(varit.back().r, 0, 255);
varit.back().g = ofClamp(varit.back().g, 0, 255);
varit.back().b = ofClamp(varit.back().b, 0, 255);
}
void Viiva::asetaVari(ofColor vari) {
varit.push_back(vari.getLerped(varit.back(),0.98));
}
ofColor Viiva::haeVari() {
if (varit.empty())
return ofColor();
return varit.back();
}
ofxOscMessage Viiva::makePisteAsOscMessage() {
ofxOscMessage msg;
msg.setAddress("/viiva/piste");
msg.addFloatArg(pisteet.back().x);
msg.addFloatArg(pisteet.back().y);
msg.addFloatArg(paine.back());
return msg;
}
ofxOscMessage Viiva::makePaksuusAsOscMessage() {
ofxOscMessage msg;
msg.setAddress("/viiva/paksuus");
msg.addFloatArg(paksuus.back());
msg.addFloatArg(paksuus.keskiarvot.back());
msg.addFloatArg(paksuus.keskihajonnat.back());
msg.addFloatArg(paksuus.konvergenssit.back());
return msg;
}
ofxOscMessage Viiva::makeSumeusAsOscMessage() {
ofxOscMessage msg;
msg.setAddress("/viiva/sumeus");
msg.addFloatArg(sumeus.back());
msg.addFloatArg(sumeus.keskiarvot.back());
msg.addFloatArg(sumeus.keskihajonnat.back());
msg.addFloatArg(sumeus.konvergenssit.back());
return msg;
}
void Viiva::nollaaLaskurit() {
improvisaatioLaskin = 0;
improvisaatioValmis = false;
kalibraatioValmis = false;
lahestymisLaskuri = 0;
lahestyKohdettaValmis = false;
muutos = ViivanOminaisuus();
}
void Viiva::tyhjennaOminaisuudet() {
paksuus = ViivanOminaisuus();
sumeus = ViivanOminaisuus();
paine = ViivanOminaisuus();
pisteet.clear();
varit.clear();
}
void Viiva::asetaKohde(shared_ptr<Viiva> kohde_) {
kohde = kohde_;
sarja = kohde->sarja;
cout << "kohde->nimi: " << kohde->nimi << "\n";
}
OminaisuusSiivu ViivanOminaisuus::haeSiivu(int id) {
OminaisuusSiivu siivu;
if (id < size()) {
siivu.arvo = arvot[id];
siivu.keskiarvo = keskiarvot[id];
siivu.keskihajonta = keskihajonnat[id];
siivu.keskihajonnanKeskihajonta = keskihajonnanKeskihajonnat[id];
siivu.konvergenssi = konvergenssit[id];
}
return siivu;
}
void Viiva::resize(int i) {
pisteet.resize(i);
varit.resize(i);
vaiheet.resize(i);
paine.resize(i);
paksuus.resize(i);
sumeus.resize(i);
}
|
// avvinci - summers 18
// #include"prettyprint.hpp"
#include<bits/stdc++.h>
using namespace std;
typedef pair<long long,long long > P;
#define mod 1000000007
#define pb emplace_back
#define fs first
#define sc second
#define ll long long
#define fr(it,st,en) for(it=st;it<en;it++)
#define all(container) container.begin(),container.end()
#define INP ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ws(x) cout << #x << " = " << x << endl;
#define N 1000004
const long long infl = 1e18+5;
ll n,m,k,q,x,y,f,val,t,i,j;
ll ind,cnt,sz,sm,ans,mx,mn;
ll a[N] ;
int main(){
INP
if (fopen("inp.txt", "r")) {
freopen("myfile.txt","w",stdout);
freopen("inp.txt", "r", stdin);
}
cin>>n;
fr(i,0,n){
cin>>a[i] ;
if(a[i] < 0 ) cnt++ ;
sm += abs(a[i]) ;
// if(a[i] == a[i-])
}
if(n == 1) {
cout<<a[0] ;
return 0 ;
}
if(cnt > 0 && cnt < n ) {
cout<<sm;
return 0 ;
}
ans = -infl ;
fr(i,1,n){
if(a[i] == a[i-1]) cnt++;
else cnt = 0 ;
val = sm - abs(a[i]) - abs( a[i-1]) ;
val += abs(a[i] - a[i-1]) ;
ans = max(ans,val) ;
}
cout<<ans;
return 0 ;
}
|
#pragma once
#pragma once
#ifndef prob2_h
#define prob2_h
#include <iostream>
#include <string >
//using namespace std;
int i, total = 0, two = 2;
int a[3] = { 0XBEEF, 0XFADE, 0XCABE };
std::string b[3] = { "BEEF", "FADE", "CABE" };
void outputEven()
{
std::cout << b[i] << " is a valid ID for the family " << std::endl;
}
void oupuOdd()
{
std::cout << b[i] << " is not valid ID for the family " << std::endl;
}
void pin()
{
__asm
{
mov eax, 0XF;
mov i, 0;
lea esi, a;
forLoop:
cmp i, 3;
je Done;
mov ebx, [esi];
shl eax, 12;
and eax, ebx;
shr eax, 12;
add total, eax;
mov eax, 0XF;
shl eax, 8;
and eax, ebx;
shr eax, 8;
add total, eax;
mov eax, 0XF;
shl eax, 4;
and eax, ebx;
shr eax, 4;
add total, eax;
mov eax, 0XF;
and eax, ebx;
add total, eax;
cdq;
mov eax, total;
idiv two;
cmp edx, 0;
je EvenNumber;
call oupuOdd;
mov eax, 0XF;
mov total, 0;
add esi, 4;
inc i;
jmp forLoop;
EvenNumber:
mov ebx, 1b;
call outputEven;
mov eax, 0XF;
mov total, 0;
add esi, 4;
inc i;
jmp forLoop;
Done:
}
}
#endif // !PROGRAM_2
|
#include<bits/stdc++.h>
using namespace std;
int rep[1005];
void init(int n)
{
for(int i = 1; i <= n; i++)
rep[i] = i;
}
int find(int x)
{
return rep[x] = (rep[x] == x ? x : find(rep[x]));
}
void unio(int x, int y)
{
rep[find(x)] = rep[find(y)];
}
main()
{
int n,m;
cin >> n >> m;
init(n);
vector<vector<int> >v(n+1);
set<int> ans;
for(int i = 0; i < m; i++)
{
char a; int b,c;
cin >> a >> b >> c;
if(a == 'F')
{
unio(b,c);
}
else
{
v[b].push_back(c);
for(int i = 0; i < v[b].size(); i++)
{
unio(c,v[b][i]);
}
v[c].push_back(b);
for(int i = 0; i < v[c].size(); i++)
{
unio(b,v[c][i]);
}
}
}
for(int i = 1; i <= n; i++)
{
ans.insert(find(i));
}
cout << ans.size() << '\n';
}
|
#include <iostream>
#include <string>
#include "fx.hpp"
using namespace std;
int main(){
printer *Printer = new printer;
Printer->back = NULL;
Printer->front = NULL;
stack *hubStack = NULL;
stack *javiStack = NULL;
stack *johnStack = NULL;
string command;
//Podría usar un switch para hacerlo fancy, pero esto es más fácil.
while(true){
cin>>command;
if(command == "add"){
string args;
getline(cin,args);
if (getStackOwner(args) == " hubert stack"){
pushToStack(hubStack,getDoc(args));
}
else if (getStackOwner(args) == " javiera stack"){
pushToStack(javiStack,getDoc(args));
}
else if (getStackOwner(args) == " john stack"){
pushToStack(johnStack,getDoc(args));
}
}else if (command == "turn"){
string arg;
cin>>arg;
//Asumo que cuando se apaga la impresora se libera la memoria
if(arg== "on"){
Printer->turnPrinterOn();
}
else if(arg == "off"){
Printer->turnPrinterOff();
liberarMemoria(hubStack,javiStack,johnStack,Printer);
break;
}
}else if(command == "read"){
if(Printer->checkPrinter()){
readDocs(hubStack,javiStack,johnStack,Printer);
}else{
cout << "the printer is off" << endl;
}
}else if(command == "print"){
if(Printer->checkPrinter()){
print(Printer);
}else{
cout << "the printer is off" << endl;
}
}
}
// printQueue(Printer);
// cout << "hubStack" << endl;
// printStack(hubStack);
// cout << "javiStack" << endl;
// printStack(javiStack);
// cout << "johnStack" << endl;
// printStack(johnStack);
/* cout << printer.checkPrinter() << endl;
printer.turnPrinter();
cout << printer.checkPrinter() << endl; */
return 0;
}
|
// include header files
#include <iostream>
// using namespace declaration
using namespace std;
int main()
{
// variables
const double PI = 3.14159265359f;
double radius = 0.0f;
// output a message to the console
cout << "\t\t\t\t\tCircumference\\Radius" << endl;
cout << "\t\t\t\t\t====================" << endl << endl;
cout << "Enter the radius of a circle : ";
// store the user input
cin >> radius;
// do the math
double area = PI * radius * radius;
// output a new line
cout << endl;
// output a message with the radius to the console
cout << "The area (A) of a circle with radius " << radius << " = " << area << endl;
// do the math
double circumference = 2 * PI * radius;
// output a message and the circumference to the console
cout << "The circumference (C) of a circle with radius " << radius << " = " << circumference << endl << endl;
// output a message to the console
cout << "Press any key to exit the application" << endl;
// ignore any user input for console instructions
cin.ignore();
// wait for a key press before exiting the console
cin.get();
// ensure we exit without error
return 0;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "MovingPlatform.h"
AMovingPlatform::AMovingPlatform()
{
PrimaryActorTick.bCanEverTick = true;
SetMobility(EComponentMobility::Movable);
}
void AMovingPlatform::AddActiveTrigger()
{
ActiveTriggers++;
}
void AMovingPlatform::RemoveActiveTrigger()
{
if (ActiveTriggers >0)
{
ActiveTriggers--;
}
}
void AMovingPlatform::BeginPlay()
{
Super::BeginPlay();
/// <summary>
/// IMPORTANT
/// Will give error if HasAuthority() check is not provided
/// Replicates functions only run on Servers.
/// Which makes sense as we don't want Clients to update data on the Server,
/// but Vice-Versa.
/// </summary>
if (HasAuthority())
{
SetReplicates(true);
SetReplicateMovement(true);
}
GlobalStartLocation = GetActorLocation();
GlobalTargetLocation = GetTransform().TransformPosition(TargetLocation);
}
void AMovingPlatform::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (ActiveTriggers > 0)
{
/// HasAuthority() return TRUE if the instance of the game is the Server.
if (HasAuthority())
{
FVector Location = GetActorLocation();
float JourneyLength = (GlobalTargetLocation - GlobalStartLocation).Size();
float JourneyTravelled = (Location - GlobalStartLocation).Size();
if (JourneyTravelled >= JourneyLength)
{
FVector Swap = GlobalStartLocation;
GlobalStartLocation = GlobalTargetLocation;
GlobalTargetLocation = Swap;
}
FVector Direction = (GlobalTargetLocation - GlobalStartLocation).GetSafeNormal();
Location += Speed * DeltaTime * Direction;
SetActorLocation(Location);
}
}
}
|
/********************************************************************************
** Form generated from reading UI file 'ctkVTKScalarsToColorsWidget.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_CTKVTKSCALARSTOCOLORSWIDGET_H
#define UI_CTKVTKSCALARSTOCOLORSWIDGET_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDoubleSpinBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QWidget>
#include "ctkExpandButton.h"
#include "ctkColorPickerButton.h"
#include "ctkDoubleRangeSlider.h"
#include "ctkVTKScalarsToColorsView.h"
QT_BEGIN_NAMESPACE
class Ui_ctkVTKScalarsToColorsWidget
{
public:
QGridLayout *gridLayout;
QHBoxLayout *TopLayout;
QSpacerItem *TopSpacer;
QLabel *PointIdLabel;
QSpinBox *PointIdSpinBox;
ctkColorPickerButton *ColorPickerButton;
QLabel *XLabel;
QDoubleSpinBox *XSpinBox;
QLabel *OpacityLabel;
QDoubleSpinBox *OpacitySpinBox;
QLabel *MidPointLabel;
QDoubleSpinBox *MidPointSpinBox;
QLabel *SharpnessLabel;
QDoubleSpinBox *SharpnessSpinBox;
ctkExpandButton *ExpandButton;
ctkVTKScalarsToColorsView *View;
ctkDoubleRangeSlider *XRangeSlider;
ctkDoubleRangeSlider *YRangeSlider;
void setupUi(QWidget *ctkVTKScalarsToColorsWidget)
{
if (ctkVTKScalarsToColorsWidget->objectName().isEmpty())
ctkVTKScalarsToColorsWidget->setObjectName(QStringLiteral("ctkVTKScalarsToColorsWidget"));
ctkVTKScalarsToColorsWidget->resize(508, 144);
gridLayout = new QGridLayout(ctkVTKScalarsToColorsWidget);
gridLayout->setSpacing(0);
gridLayout->setContentsMargins(0, 0, 0, 0);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
TopLayout = new QHBoxLayout();
TopLayout->setObjectName(QStringLiteral("TopLayout"));
TopSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
TopLayout->addItem(TopSpacer);
PointIdLabel = new QLabel(ctkVTKScalarsToColorsWidget);
PointIdLabel->setObjectName(QStringLiteral("PointIdLabel"));
TopLayout->addWidget(PointIdLabel);
PointIdSpinBox = new QSpinBox(ctkVTKScalarsToColorsWidget);
PointIdSpinBox->setObjectName(QStringLiteral("PointIdSpinBox"));
PointIdSpinBox->setEnabled(false);
PointIdSpinBox->setMinimum(-1);
PointIdSpinBox->setMaximum(-1);
TopLayout->addWidget(PointIdSpinBox);
ColorPickerButton = new ctkColorPickerButton(ctkVTKScalarsToColorsWidget);
ColorPickerButton->setObjectName(QStringLiteral("ColorPickerButton"));
ColorPickerButton->setEnabled(false);
ColorPickerButton->setDisplayColorName(false);
ColorPickerButton->setDialogOptions(ctkColorPickerButton::UseCTKColorDialog);
TopLayout->addWidget(ColorPickerButton);
XLabel = new QLabel(ctkVTKScalarsToColorsWidget);
XLabel->setObjectName(QStringLiteral("XLabel"));
TopLayout->addWidget(XLabel);
XSpinBox = new QDoubleSpinBox(ctkVTKScalarsToColorsWidget);
XSpinBox->setObjectName(QStringLiteral("XSpinBox"));
XSpinBox->setEnabled(false);
TopLayout->addWidget(XSpinBox);
OpacityLabel = new QLabel(ctkVTKScalarsToColorsWidget);
OpacityLabel->setObjectName(QStringLiteral("OpacityLabel"));
TopLayout->addWidget(OpacityLabel);
OpacitySpinBox = new QDoubleSpinBox(ctkVTKScalarsToColorsWidget);
OpacitySpinBox->setObjectName(QStringLiteral("OpacitySpinBox"));
OpacitySpinBox->setEnabled(false);
OpacitySpinBox->setMaximum(1);
OpacitySpinBox->setSingleStep(0.1);
TopLayout->addWidget(OpacitySpinBox);
MidPointLabel = new QLabel(ctkVTKScalarsToColorsWidget);
MidPointLabel->setObjectName(QStringLiteral("MidPointLabel"));
TopLayout->addWidget(MidPointLabel);
MidPointSpinBox = new QDoubleSpinBox(ctkVTKScalarsToColorsWidget);
MidPointSpinBox->setObjectName(QStringLiteral("MidPointSpinBox"));
MidPointSpinBox->setEnabled(false);
MidPointSpinBox->setMaximum(1);
MidPointSpinBox->setSingleStep(0.1);
TopLayout->addWidget(MidPointSpinBox);
SharpnessLabel = new QLabel(ctkVTKScalarsToColorsWidget);
SharpnessLabel->setObjectName(QStringLiteral("SharpnessLabel"));
TopLayout->addWidget(SharpnessLabel);
SharpnessSpinBox = new QDoubleSpinBox(ctkVTKScalarsToColorsWidget);
SharpnessSpinBox->setObjectName(QStringLiteral("SharpnessSpinBox"));
SharpnessSpinBox->setEnabled(false);
SharpnessSpinBox->setMaximum(1);
SharpnessSpinBox->setSingleStep(0.1);
TopLayout->addWidget(SharpnessSpinBox);
ExpandButton = new ctkExpandButton(ctkVTKScalarsToColorsWidget);
ExpandButton->setObjectName(QStringLiteral("ExpandButton"));
ExpandButton->setContextMenuPolicy(Qt::DefaultContextMenu);
TopLayout->addWidget(ExpandButton);
gridLayout->addLayout(TopLayout, 0, 0, 1, 2);
View = new ctkVTKScalarsToColorsView(ctkVTKScalarsToColorsWidget);
View->setObjectName(QStringLiteral("View"));
gridLayout->addWidget(View, 1, 0, 1, 1);
XRangeSlider = new ctkDoubleRangeSlider(ctkVTKScalarsToColorsWidget);
XRangeSlider->setObjectName(QStringLiteral("XRangeSlider"));
XRangeSlider->setMaximum(1);
XRangeSlider->setSingleStep(0.01);
XRangeSlider->setMaximumValue(1);
XRangeSlider->setOrientation(Qt::Horizontal);
gridLayout->addWidget(XRangeSlider, 2, 0, 1, 1);
YRangeSlider = new ctkDoubleRangeSlider(ctkVTKScalarsToColorsWidget);
YRangeSlider->setObjectName(QStringLiteral("YRangeSlider"));
YRangeSlider->setMaximum(1);
YRangeSlider->setSingleStep(0.01);
YRangeSlider->setOrientation(Qt::Vertical);
gridLayout->addWidget(YRangeSlider, 1, 1, 1, 1);
gridLayout->setColumnStretch(0, 1);
retranslateUi(ctkVTKScalarsToColorsWidget);
QMetaObject::connectSlotsByName(ctkVTKScalarsToColorsWidget);
} // setupUi
void retranslateUi(QWidget *ctkVTKScalarsToColorsWidget)
{
ctkVTKScalarsToColorsWidget->setWindowTitle(QApplication::translate("ctkVTKScalarsToColorsWidget", "ScalarsToColorsWidget", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
PointIdLabel->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "Point ID", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
PointIdLabel->setText(QApplication::translate("ctkVTKScalarsToColorsWidget", "Point:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
PointIdSpinBox->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "Point ID", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
ColorPickerButton->setText(QString());
#ifndef QT_NO_TOOLTIP
XLabel->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "X coordinate of the current point", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
XLabel->setText(QApplication::translate("ctkVTKScalarsToColorsWidget", "X:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
XSpinBox->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "X coordinate of the current point", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
OpacityLabel->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "Opacity of the current point", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
OpacityLabel->setText(QApplication::translate("ctkVTKScalarsToColorsWidget", "O:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
OpacitySpinBox->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "Opacity of the current point", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
MidPointLabel->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "Position of the midpoint", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
MidPointLabel->setText(QApplication::translate("ctkVTKScalarsToColorsWidget", "M:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
MidPointSpinBox->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "Position of the midpoint", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
SharpnessLabel->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "Sharpness of the midpoint", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
SharpnessLabel->setText(QApplication::translate("ctkVTKScalarsToColorsWidget", "S:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
SharpnessSpinBox->setToolTip(QApplication::translate("ctkVTKScalarsToColorsWidget", "Sharpness of the midpoint", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
} // retranslateUi
};
namespace Ui {
class ctkVTKScalarsToColorsWidget: public Ui_ctkVTKScalarsToColorsWidget {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_CTKVTKSCALARSTOCOLORSWIDGET_H
|
#include<iostream>
using namespace std;
struct BinaryTreeNode {
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(int x) { value = x; left = NULL; right = NULL; }
};
bool func(BinaryTreeNode* root1, BinaryTreeNode* root2) //判断是否是子结构
{
if (root2 == nullptr) //root2为空 无论root1是否为空 2都是1 的子结构
{
return true;
}
if (root1 == nullptr) { //2不为空 1为空 不是子结构
return false;
}
if (root1->value != root2->value) { //都不为空时,当前节点的值不等 不是子结构
return false;
}
return func(root1->left, root2->left) && func(root1->right, root2->right); //当前节点的值相等 分别判断左子树和右子树
}
bool isSubTree(BinaryTreeNode* rootA, BinaryTreeNode* rootB)
{
if (rootA == nullptr) {
return false;
}
else if (rootB == nullptr)
{
return true;
}
else
{
bool output = false;
if (rootA && rootB) {
if (rootA->value == rootB->value) { //当前根节点值相等
output = func(rootA, rootB); //如果相等 判断是否是子结构 不相等 output仍为false
}
if (!output) { //false 1.上一个根节点的值不等 2.上一个根节点的值相等但是不存在子结构
output = isSubTree(rootA->left, rootB);
}
if (!output) {
output = isSubTree(rootA->right, rootB);
}
}
return output;
}
}
int main()
{
BinaryTreeNode* a;
a = new BinaryTreeNode(1);
BinaryTreeNode* b;
b = new BinaryTreeNode(2);
BinaryTreeNode* c;
c = new BinaryTreeNode(3);
BinaryTreeNode* d;
d = new BinaryTreeNode(4);
a->left = b;
b->left = c;
b->right = d;
BinaryTreeNode* a1;
a1 = new BinaryTreeNode(2);
BinaryTreeNode* b1;
b1 = new BinaryTreeNode(4);
BinaryTreeNode* c1;
c1 = new BinaryTreeNode(1);
//a1->left = b1;
a1->right = b1;
bool output = isSubTree(a, a1);
cout << output << endl;
return 0;
}
|
#pragma once
namespace Util
{
template <class T>
class CSingleton
{
static T& getInstance()
{
static T s_instance;
return s_instance;
}
};
}
|
/**
* Author : BurningTiles
* Created : 2020-08-07 13:54:41
**/
#include <bits/stdc++.h>
using namespace std;
bool find(int n, int a[], int x){
bool flag=false;
int remsum, start, end;
for(int i=0; i<n; ++i){
remsum = x-a[i];
start = i+1;
end = n-1;
while(start < end){
if(a[start]+a[end] > remsum)
--end;
else if(a[start]+a[end] < remsum)
++start;
else
return true;
}
}
return flag;
}
int main(){
int n;
cin >> n;
int a[n], x;
for(int i=0; i<n; ++i)
cin >> a[i];
cin >> x;
sort(a,a+n);
(find(n,a,x))? cout << "True" : cout << "False";
return 0;
}
/**
Sheldon Cooper, Leonard Hofstadter and Penny decide to go for drinks at Cheese cake factory. Sheldon proposes to make a game out of this. Sheldon proposes as follows,
To decide the amount of beverage they plan to consume, say X.
Then order for a random number of different drinks, say {A, B, C, D, E, F} of quantities {a, b, c, d, e, f} respectively.
If quantity of any three drinks add up to X then we'll have it else we'll return the order.
E.g. If a + d + f = X then True else False
You are given
Number of bottles N corresponding to different beverages and hence their sizes
Next N lines, contain a positive integer corresponding to the size of the beverage
Last line consists of an integer value, denoted by X above
Your task is to help find out if there can be any combination of three beverage sizes that can sum up to the quantity they intend to consume. If such a combination is possible print True else False
Input Format
First line contains number of bottles ordered denoted by N
Next N lines, contains a positive integer Ai, the size of the ith bottle
Last line contains the quantity they intend to consume denoted by X in text above
Output Format
True, if combination is possible
False, if combination is not possible
Constraints
N >= 3
Ai > 0
1 <= i <= N
X > 0
Sample Input 1
6
1
4
45
6
10
8
22
Sample Output 1
True
Explanation
The sum of 2nd, 5th and 6th beverage size is equal to 22. So the output will be True.
Sample Input 2
4
1
3
12
4
14
Sample Output 2
False
Explanation
Since no combination of given beverage sizes sum up to X i.e. 14, the output will be False.
**/
|
///////////////////////////////////////////////////////////////////////////////
// Name: src/univ/glx11.cpp
// Purpose: code common to all X11-based wxGLCanvas implementations
// Author: Vadim Zeitlin
// Created: 2007-04-15
// RCS-ID: $Id: glx11.cpp 54022 2008-06-08 00:12:12Z VZ $
// Copyright: (c) 2007 Vadim Zeitlin <vadim@wxwindows.org>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if wxUSE_GLCANVAS
#ifndef WX_PRECOMP
#include "wx/log.h"
#endif //WX_PRECOMP
#include "wx/glcanvas.h"
// ============================================================================
// wxGLContext implementation
// ============================================================================
IMPLEMENT_CLASS(wxGLContext, wxObject)
wxGLContext::wxGLContext(wxGLCanvas *gc, const wxGLContext *other)
{
if ( wxGLCanvas::GetGLXVersion() >= 13 )
{
GLXFBConfig *fbc = gc->GetGLXFBConfig();
wxCHECK_RET( fbc, _T("invalid GLXFBConfig for OpenGL") );
m_glContext = glXCreateNewContext( wxGetX11Display(), fbc[0], GLX_RGBA_TYPE,
other ? other->m_glContext : None,
GL_TRUE );
}
else // GLX <= 1.2
{
XVisualInfo *vi = gc->GetXVisualInfo();
wxCHECK_RET( vi, _T("invalid visual for OpenGL") );
m_glContext = glXCreateContext( wxGetX11Display(), vi,
other ? other->m_glContext : None,
GL_TRUE );
}
wxASSERT_MSG( m_glContext, _T("Couldn't create OpenGL context") );
}
wxGLContext::~wxGLContext()
{
if ( !m_glContext )
return;
if ( m_glContext == glXGetCurrentContext() )
MakeCurrent(None, NULL);
glXDestroyContext( wxGetX11Display(), m_glContext );
}
bool wxGLContext::SetCurrent(const wxGLCanvas& win) const
{
if ( !m_glContext )
return false;
const Window xid = win.GetXWindow();
wxCHECK2_MSG( xid, return false, _T("window must be shown") );
return MakeCurrent(xid, m_glContext);
}
// wrapper around glXMakeContextCurrent/glXMakeCurrent depending on GLX
// version
/* static */
bool wxGLContext::MakeCurrent(GLXDrawable drawable, GLXContext context)
{
if (wxGLCanvas::GetGLXVersion() >= 13)
return glXMakeContextCurrent( wxGetX11Display(), drawable, drawable, context);
else // GLX <= 1.2 doesn't have glXMakeContextCurrent()
return glXMakeCurrent( wxGetX11Display(), drawable, context);
}
// ============================================================================
// wxGLCanvasX11 implementation
// ============================================================================
// ----------------------------------------------------------------------------
// initialization methods and dtor
// ----------------------------------------------------------------------------
wxGLCanvasX11::wxGLCanvasX11()
{
m_fbc = NULL;
m_vi = NULL;
}
bool wxGLCanvasX11::InitVisual(const int *attribList)
{
return InitXVisualInfo(attribList, &m_fbc, &m_vi);
}
wxGLCanvasX11::~wxGLCanvasX11()
{
if ( m_fbc && m_fbc != ms_glFBCInfo )
XFree(m_fbc);
if ( m_vi && m_vi != ms_glVisualInfo )
XFree(m_vi);
}
// ----------------------------------------------------------------------------
// working with GL attributes
// ----------------------------------------------------------------------------
/* static */
bool wxGLCanvasBase::IsExtensionSupported(const char *extension)
{
Display * const dpy = wxGetX11Display();
return IsExtensionInList(glXQueryExtensionsString(dpy, DefaultScreen(dpy)),
extension);
}
/* static */
bool wxGLCanvasX11::IsGLXMultiSampleAvailable()
{
static int s_isMultiSampleAvailable = -1;
if ( s_isMultiSampleAvailable == -1 )
s_isMultiSampleAvailable = IsExtensionSupported("GLX_ARB_multisample");
return s_isMultiSampleAvailable != 0;
}
bool
wxGLCanvasX11::ConvertWXAttrsToGL(const int *wxattrs, int *glattrs, size_t n)
{
wxCHECK_MSG( n >= 16, false, _T("GL attributes buffer too small") );
/*
Different versions of GLX API use rather different attributes lists, see
the following URLs:
- <= 1.2: http://www.opengl.org/sdk/docs/man/xhtml/glXChooseVisual.xml
- >= 1.3: http://www.opengl.org/sdk/docs/man/xhtml/glXChooseFBConfig.xml
Notice in particular that
- GLX_RGBA is boolean attribute in the old version of the API but a
value of GLX_RENDER_TYPE in the new one
- Boolean attributes such as GLX_DOUBLEBUFFER don't take values in the
old version but must be followed by True or False in the new one.
*/
if ( !wxattrs )
{
size_t i = 0;
// use double-buffered true colour by default
glattrs[i++] = GLX_DOUBLEBUFFER;
if ( GetGLXVersion() < 13 )
{
// default settings if attriblist = 0
glattrs[i++] = GLX_RGBA;
glattrs[i++] = GLX_DEPTH_SIZE; glattrs[i++] = 1;
glattrs[i++] = GLX_RED_SIZE; glattrs[i++] = 1;
glattrs[i++] = GLX_GREEN_SIZE; glattrs[i++] = 1;
glattrs[i++] = GLX_BLUE_SIZE; glattrs[i++] = 1;
glattrs[i++] = GLX_ALPHA_SIZE; glattrs[i++] = 0;
}
else // recent GLX can choose the defaults on its own just fine
{
// we just need to have a value after GLX_DOUBLEBUFFER
glattrs[i++] = True;
}
glattrs[i] = None;
wxASSERT_MSG( i < n, _T("GL attributes buffer too small") );
}
else // have non-default attributes
{
size_t p = 0;
for ( int arg = 0; wxattrs[arg] != 0; )
{
// check if we have any space left, knowing that we may insert 2
// more elements during this loop iteration and we always need to
// terminate the list with None (hence -3)
if ( p > n - 3 )
return false;
// indicates whether we have a boolean attribute
bool isBoolAttr = false;
switch ( wxattrs[arg++] )
{
case WX_GL_BUFFER_SIZE:
glattrs[p++] = GLX_BUFFER_SIZE;
break;
case WX_GL_LEVEL:
glattrs[p++] = GLX_LEVEL;
break;
case WX_GL_RGBA:
if ( GetGLXVersion() >= 13 )
{
// this is the default GLX_RENDER_TYPE anyhow
continue;
}
glattrs[p++] = GLX_RGBA;
isBoolAttr = true;
break;
case WX_GL_DOUBLEBUFFER:
glattrs[p++] = GLX_DOUBLEBUFFER;
isBoolAttr = true;
break;
case WX_GL_STEREO:
glattrs[p++] = GLX_STEREO;
isBoolAttr = true;
break;
case WX_GL_AUX_BUFFERS:
glattrs[p++] = GLX_AUX_BUFFERS;
break;
case WX_GL_MIN_RED:
glattrs[p++] = GLX_RED_SIZE;
break;
case WX_GL_MIN_GREEN:
glattrs[p++] = GLX_GREEN_SIZE;
break;
case WX_GL_MIN_BLUE:
glattrs[p++] = GLX_BLUE_SIZE;
break;
case WX_GL_MIN_ALPHA:
glattrs[p++] = GLX_ALPHA_SIZE;
break;
case WX_GL_DEPTH_SIZE:
glattrs[p++] = GLX_DEPTH_SIZE;
break;
case WX_GL_STENCIL_SIZE:
glattrs[p++] = GLX_STENCIL_SIZE;
break;
case WX_GL_MIN_ACCUM_RED:
glattrs[p++] = GLX_ACCUM_RED_SIZE;
break;
case WX_GL_MIN_ACCUM_GREEN:
glattrs[p++] = GLX_ACCUM_GREEN_SIZE;
break;
case WX_GL_MIN_ACCUM_BLUE:
glattrs[p++] = GLX_ACCUM_BLUE_SIZE;
break;
case WX_GL_MIN_ACCUM_ALPHA:
glattrs[p++] = GLX_ACCUM_ALPHA_SIZE;
break;
case WX_GL_SAMPLE_BUFFERS:
if ( !IsGLXMultiSampleAvailable() )
{
// if it was specified just to disable it, no problem
if ( !wxattrs[arg++] )
continue;
// otherwise indicate that it's not supported
return false;
}
glattrs[p++] = GLX_SAMPLE_BUFFERS_ARB;
break;
case WX_GL_SAMPLES:
if ( !IsGLXMultiSampleAvailable() )
{
if ( !wxattrs[arg++] )
continue;
return false;
}
glattrs[p++] = GLX_SAMPLES_ARB;
break;
default:
wxLogDebug(_T("Unsupported OpenGL attribute %d"),
wxattrs[arg - 1]);
continue;
}
if ( isBoolAttr )
{
// as explained above, for pre 1.3 API the attribute just needs
// to be present so we only add its value when using the new API
if ( GetGLXVersion() >= 13 )
glattrs[p++] = True;
}
else // attribute with real (non-boolean) value
{
// copy attribute value as is
glattrs[p++] = wxattrs[arg++];
}
}
glattrs[p] = None;
}
return true;
}
/* static */
bool
wxGLCanvasX11::InitXVisualInfo(const int *attribList,
GLXFBConfig **pFBC,
XVisualInfo **pXVisual)
{
int data[512];
if ( !ConvertWXAttrsToGL(attribList, data, WXSIZEOF(data)) )
return false;
Display * const dpy = wxGetX11Display();
if ( GetGLXVersion() >= 13 )
{
int returned;
*pFBC = glXChooseFBConfig(dpy, DefaultScreen(dpy), data, &returned);
if ( *pFBC )
{
*pXVisual = glXGetVisualFromFBConfig(wxGetX11Display(), **pFBC);
if ( !*pXVisual )
{
XFree(*pFBC);
*pFBC = NULL;
}
}
}
else // GLX <= 1.2
{
*pFBC = NULL;
*pXVisual = glXChooseVisual(dpy, DefaultScreen(dpy), data);
}
return *pXVisual != NULL;
}
/* static */
bool
wxGLCanvasBase::IsDisplaySupported(const int *attribList)
{
GLXFBConfig *fbc = NULL;
XVisualInfo *vi = NULL;
const bool
isSupported = wxGLCanvasX11::InitXVisualInfo(attribList, &fbc, &vi);
if ( fbc )
XFree(fbc);
if ( vi )
XFree(vi);
return isSupported;
}
// ----------------------------------------------------------------------------
// default visual management
// ----------------------------------------------------------------------------
XVisualInfo *wxGLCanvasX11::ms_glVisualInfo = NULL;
GLXFBConfig *wxGLCanvasX11::ms_glFBCInfo = NULL;
/* static */
bool wxGLCanvasX11::InitDefaultVisualInfo(const int *attribList)
{
FreeDefaultVisualInfo();
return InitXVisualInfo(attribList, &ms_glFBCInfo, &ms_glVisualInfo);
}
/* static */
void wxGLCanvasX11::FreeDefaultVisualInfo()
{
if ( ms_glFBCInfo )
{
XFree(ms_glFBCInfo);
ms_glFBCInfo = NULL;
}
if ( ms_glVisualInfo )
{
XFree(ms_glVisualInfo);
ms_glVisualInfo = NULL;
}
}
// ----------------------------------------------------------------------------
// other GL methods
// ----------------------------------------------------------------------------
/* static */
int wxGLCanvasX11::GetGLXVersion()
{
static int s_glxVersion = 0;
if ( s_glxVersion == 0 )
{
// check the GLX version
int glxMajorVer, glxMinorVer;
bool ok = glXQueryVersion(wxGetX11Display(), &glxMajorVer, &glxMinorVer);
wxASSERT_MSG( ok, _T("GLX version not found") );
if (!ok)
s_glxVersion = 10; // 1.0 by default
else
s_glxVersion = glxMajorVer*10 + glxMinorVer;
}
return s_glxVersion;
}
bool wxGLCanvasX11::SwapBuffers()
{
const Window xid = GetXWindow();
wxCHECK2_MSG( xid, return false, _T("window must be shown") );
glXSwapBuffers(wxGetX11Display(), xid);
return true;
}
bool wxGLCanvasX11::IsShownOnScreen() const
{
return GetXWindow() && wxGLCanvasBase::IsShownOnScreen();
}
#endif // wxUSE_GLCANVAS
|
{
gROOT->ProcessLine(".L ../external/class_lib.so");
gROOT->ProcessLine(".x ./macros/class_asymmetry_sl.C");
}
|
#ifndef VEHICULECONTROLLER_H
#define VEHICULECONTROLLER_H
#include <QGeoCoordinate>
#include <QObject>
#include <QGeoCircle>
class VehiculeController:public QObject
{
Q_OBJECT
Q_PROPERTY(QGeoCoordinate center READ center NOTIFY centerChanged)
Q_PROPERTY(qreal radius READ radius WRITE setRadius NOTIFY radiusChanged)
public:
VehiculeController(QObject *parent=0):QObject(parent){
mCircle.setRadius(1000);
}
QGeoCoordinate center() const
{
return mCircle.center();
}
void setCenter(const QGeoCoordinate ¢er){
if(mCircle.center() == center)
return;
mCircle.setCenter(center);
emit centerChanged();
}
void translate(double degreesLatitude, double degreesLongitude){
mCircle.translate(degreesLatitude, degreesLongitude);
emit centerChanged();
}
qreal radius() const{ return mCircle.radius();}
void setRadius(const qreal &radius){
if(mCircle.radius() == radius)
return;
mCircle.setRadius(radius);
emit radiusChanged();
}
signals:
void centerChanged();
void radiusChanged();
private:
QGeoCircle mCircle;
};
#endif // VEHICULECONTROLLER_H
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Metadata {
struct IApiInformationStatics;
}
namespace Windows::Foundation::Metadata {
struct IApiInformationStatics;
struct ApiInformation;
}
namespace Windows::Foundation::Metadata {
template <typename T> struct impl_IApiInformationStatics;
}
namespace Windows::Foundation::Metadata {
enum class FeatureStage
{
AlwaysDisabled = 0,
DisabledByDefault = 1,
EnabledByDefault = 2,
AlwaysEnabled = 3,
};
enum class GCPressureAmount
{
Low = 0,
Medium = 1,
High = 2,
};
}
}
|
// Copyright ⓒ 2020 Valentyn Bondarenko. All rights reserved.
#pragma once
#include <IRender.hpp>
#include <..\DiligentTools\TextureLoader\interface\TextureUtilities.h>
#include <..\DiligentCore\Graphics\GraphicsTools\interface\MapHelper.hpp>
#include <..\DiligentCore\Graphics\GraphicsTools\interface\GraphicsUtilities.h>
namespace be::render
{
// Direct3D11 implementation using Diligent Graphics Engine.
class D3D11Render : virtual public IRender
{
public:
D3D11Render();
~D3D11Render();
D3D11Render(const D3D11Render&) = delete;
D3D11Render(D3D11Render&&) = delete;
D3D11Render operator=(const D3D11Render&) = delete;
D3D11Render operator=(D3D11Render&&) = delete;
public:
void preinitialize(HWND winhandle, const math::int2& resolution, const bool& fullscreen) override final;
void initialize() override final;
void run() override final { }; // use present instead
void finalize() override final;
void present(const bool& vsync) override final;
void render(ITextureView* ms_color_rtv = nullptr, ITextureView* ms_depth_dsv = nullptr) override final;
void reset() override final;
IEngineFactory* getEngineFactory() override final { return pFactoryD3D11; }
IRenderDevice* getRenderDevice() override final { return device; }
IDeviceContext* getDeviceContext() override final { return immediate_context; }
ISwapChain* getSwapChain() override final { return swap_chain; }
IPipelineState* getPipelineState() override final { return pipeline_state; }
PipelineStateCreateInfo& getPipelineInfo() override final { return *&PSOCreateInfo; }
public:
void getCaps() override final;
void getDeviceCaps() override final;
void setPipelineState() override final;
void setFullScreen(const math::int2& resolution) override final;
void setWindowed() override final;
void resize(const math::int2& resolution);
void createPipelineState() override final;
void createSRB(IShaderResourceBinding** srb) override final;
void createUniBuffer(IBuffer** VSConstants, const Diligent::Uint32& size) override final;
void loadTexture(ITexture** Tex, const fs::path& file_name) override final;
void getStaVarByName(SHADER_TYPE sht, IBuffer* VSConstants, const char* cb_name) override final;
private:
IEngineFactoryD3D11* pFactoryD3D11 = nullptr;
IRenderDevice* device = nullptr;
IDeviceContext* immediate_context = nullptr;
ISwapChain* swap_chain = nullptr;
IPipelineState* pipeline_state = nullptr;
ITextureView* pRTV = nullptr;
ITextureView* pDSV = nullptr;
public:
EngineD3D11CreateInfo EngineCI;
PipelineStateCreateInfo PSOCreateInfo;
vector<AdapterAttribs> Adapters;
TEXTURE_FORMAT texture_format = TEX_FORMAT_RGBA8_UNORM_SRGB;
RENDER_DEVICE_TYPE m_DeviceType = RENDER_DEVICE_TYPE_D3D11;
ADAPTER_TYPE adapter_type = ADAPTER_TYPE_UNKNOWN;
AdapterAttribs m_AdapterAttribs;
vector<DisplayModeAttribs> m_DisplayModes;
DisplayModeAttribs current_dma;
HWND hwnd;
std::optional<math::int2> swap_chain_desc_size;
float clear_color[4];
Uint32 m_AdapterId = 0;
};
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
#include <map>
#include <sstream>
#include <cmath>
#include <unordered_set> // 需要c++ 11才能支持
#include <unordered_map> // 需要c++ 11才能支持
using namespace std;
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
// 相同题目 《剑指offer》 二叉搜索树与双向链表
class Converter {
public:
ListNode* treeToList(TreeNode* root) {
ListNode dummy(-1), *pre = &dummy;
inorder(root, pre);
return dummy.next;
}
private:
void inorder(TreeNode* root, ListNode*& pre){
if(root == NULL) return;
inorder(root->left, pre);
pre->next = new ListNode(root->val);
pre = pre->next;
inorder(root->right, pre);
}
};
int main(){
return 0;
}
|
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_FWD_ENTITY_MEMBERS_HPP
#define NBDL_FWD_ENTITY_MEMBERS_HPP
#include <nbdl/macros/NBDL_ENTITY.hpp>
#include <boost/hana/string.hpp>
#include <type_traits>
namespace nbdl
{
template <typename E>
struct entity_name_impl;
template <typename E>
using entity_name = decltype(entity_name_impl<std::decay_t<E>>::apply());
template <typename E>
struct entity_members_impl;
template <typename E>
using entity_members_t = typename entity_members_impl<std::decay_t<E>>::type;
template <typename E>
constexpr entity_members_t<E> entity_members{};
template <typename Member>
struct get_member_fn
{
template <typename Entity>
decltype(auto) operator()(Entity&& e) const;
};
template <typename Member>
constexpr get_member_fn<Member> get_member{};
template <class Owner, typename T, T Owner::*p>
struct member
{
using owner_type = Owner;
using member_type = T;
static constexpr T Owner::*ptr = p;
};
template <typename T>
struct member_traits;
template <class Owner, typename T>
struct member_traits<T Owner::*>
{
using owner_type = Owner;
using member_type = T;
};
template <typename Member>
struct member_name_impl;
template <class M>
using member_name = decltype(member_name_impl<M>::apply());
template <class M>
struct member_default;
template <class M>
struct member_string_max_length
{
//default max length of 50 for all strings
static const int value = 50;
};
template <class M>
struct member_string_min_length
{
static const int value = 0;
};
template <class M>
struct member_match
{
// TODO figure out if this really needs to be a nullptr
static constexpr const char *value = nullptr;
};
//allow a string to have zero length
template <class M>
struct member_allow_blank
{
static const bool value = false;
};
//string treated as buffer and does no trim filtering
template <class M>
struct member_raw_buffer
{
static const bool value = false;
};
template <class M>
struct member_custom_validator
{
template <typename T, typename AddError>
static void validate(T&, AddError) {}
};
}//nbdl
/*
* MEMBER MACROS
*/
#define NBDL_MEMBER(mptr) ::nbdl::member<typename ::nbdl::member_traits<decltype(mptr)>::owner_type, typename ::nbdl::member_traits<decltype(mptr)>::member_type, mptr>
#define NBDL_MEMBER_NAME(Owner, MemberName) \
template <> \
struct member_name_impl<NBDL_MEMBER(&Owner::MemberName)> { \
static auto apply() { return BOOST_HANA_STRING(#MemberName); }; \
};
#define NBDL_MEMBER_DEFAULT(mptr, val) template <> struct member_default<NBDL_MEMBER(mptr)> \
{ static constexpr decltype(val) value = val; }; \
#define NBDL_MEMBER_MAXLENGTH(mptr, v) template <> struct member_string_max_length<NBDL_MEMBER(mptr)> \
{ static const unsigned value = v; };
#define NBDL_MEMBER_MINLENGTH(mptr, v) template <> struct member_string_min_length<NBDL_MEMBER(mptr)> \
{ static const unsigned value = v; };
#define NBDL_MEMBER_MATCH(mptr, reg) template <> struct member_match<NBDL_MEMBER(mptr)> \
{ static constexpr const char *value = reg; };
#define NBDL_MEMBER_ALLOWBLANK(mptr) template <> struct member_allow_blank<NBDL_MEMBER(mptr)> \
{ static const bool value = true; };
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.