blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bcb839988196eda454104ca2c2e19d2cfda80093 | 082fa6b3970bc27d7e349dcc56e209f33a997442 | /code/common/LibHNLobby/HNLobby/ChildLayer/GamePayLayer.cpp | 48f61ff2439e4f7261f6193e86c5b16efe3e27f2 | [] | no_license | Crasader/C-_Project | e0627276e9305b661c82706f635cf0bdfa009897 | 106d2c8fd9561730a59d36af12f11677e54f8772 | refs/heads/master | 2021-10-27T05:48:05.937651 | 2019-04-16T07:30:35 | 2019-04-16T07:30:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,332 | cpp | GamePayLayer.cpp | #include "HNLobby/ChildLayer/GamePayLayer.h"
#include "HNLobby/PlatformDefine.h"
#include "HNLobby/PlatformConfig.h"
#include "HNMarketExport.h"
#include "UI/Base/HNLayerColor.h"
static const char* PAY_JSON_PATH = "platform/pay/PayUI_1.json"; //
//static const char* PAY_BG = "platform/common_bg.png"; // backGround
GamePayLayer* GamePayLayer::createPaySelected(PRODUCT_INFO* product) {
GamePayLayer *pRet = new GamePayLayer();
if (pRet && pRet->initWithProduct(product)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return pRet;
}
GamePayLayer::GamePayLayer() : _opacity(0), _payUILayout(nullptr), _delegate(nullptr) {
memset(&_payUI, 0x0, sizeof(_payUI));
}
GamePayLayer::~GamePayLayer() {
}
bool GamePayLayer::initWithProduct(PRODUCT_INFO* product) {
if (!HNLayer::init()) {
return false;
}
_product = *product;
_colorLayer = HNLayerColor::create();
_colorLayer->setTag(10);
addChild(_colorLayer);
Size winSize = Director::getInstance()->getWinSize();
_payUILayout = dynamic_cast<Layout*>(GUIReader::getInstance()->widgetFromJsonFile(PAY_JSON_PATH));
_payUILayout->setAnchorPoint(Vec2(0.5, 0.5));
_payUILayout->setPosition(Vec2(winSize.width/2, winSize.height/2));
float _xScale = winSize.width / PlatformConfig::getInstance()->getPlatformDesignSize().width;
float _yScale = winSize.height / PlatformConfig::getInstance()->getPlatformDesignSize().height;
_payUILayout->setScale(_xScale, _yScale);
addChild(_payUILayout, 2, 3);
_payUIRect = _payUILayout->getBoundingBox();
auto MyListener = EventListenerTouchOneByOne::create();
//阻止触摸向下传递
MyListener->setSwallowTouches(true);
MyListener->onTouchBegan = [&](Touch* touch, Event* event) {
auto target = dynamic_cast<GamePayLayer*>(event->getCurrentTarget());//获取的当前触摸的目标
Point locationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect(0, 0, s.width, s.height);
if (rect.containsPoint(locationInNode)) { //判断触摸点是否在目标的范围内
if (_payUIRect.containsPoint(locationInNode)) return true;
HNAudioEngine::getInstance()->playEffect(GAME_SOUND_CLOSE);
auto size = Director::getInstance()->getWinSize();
if (this->getPositionX() == 0) {
auto winSize = Director::getInstance()->getWinSize();
this->runAction(Sequence::create(EaseSineIn::create(MoveBy::create(0.3f, Vec2(-winSize.width, 0))),
CCCallFunc::create(CC_CALLBACK_0(GamePayLayer::closeLayer, this)),
RemoveSelf::create(true), nullptr));
}
return true;
} else {
return false;
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(MyListener, this);
// 商品描述
_payUI.Label_Product_Description = (Text*)Helper::seekWidgetByName(_payUILayout, "Label_Product_Description");
if (nullptr != _payUI.Label_Product_Description) {
//_payUI.Label_Product_Description->setString(GBKToUtf8(_product.description.c_str()));
}
// 商品价格
_payUI.Label_Product_Price = (Text*)Helper::seekWidgetByName(_payUILayout, "Label_Product_Price");
if (nullptr != _payUI.Label_Product_Price) {
char buffer[32];
sprintf(buffer, GBKToUtf8("%u 元"), _product.price);
_payUI.Label_Product_Price->setString(buffer);
}
// 咨询电话
_payUI.Label_Phone = (Text*)Helper::seekWidgetByName(_payUILayout, "Label_Phone");
if (nullptr != _payUI.Label_Phone) {
_payUI.Label_Phone->setString("");
}
// 关闭按钮
_payUI.Button_Close = (Button*)Helper::seekWidgetByName(_payUILayout, "Button_Close");
_payUI.Button_Close->addTouchEventListener(CC_CALLBACK_2(GamePayLayer::paySelectEventCallBack, this, PAY_UI::CLOSE_TAG));
// 阿里支付按钮
_payUI.Button_Alipay = (Button*)Helper::seekWidgetByName(_payUILayout, "Button_Alipay");
_payUI.Button_Alipay->addTouchEventListener(CC_CALLBACK_2(GamePayLayer::paySelectEventCallBack, this, PAY_UI::ALIPAY_TAG));
// 微信支付按钮
_payUI.Button_WeChat = (Button*)Helper::seekWidgetByName(_payUILayout, "Button_WeChat");
_payUI.Button_WeChat->addTouchEventListener(CC_CALLBACK_2(GamePayLayer::paySelectEventCallBack, this, PAY_UI::WECHAT_TAG));
// 银联支付按钮
_payUI.Button_UnionPay = (Button*)Helper::seekWidgetByName(_payUILayout, "Button_UnionPay");
_payUI.Button_UnionPay->addTouchEventListener(CC_CALLBACK_2(GamePayLayer::paySelectEventCallBack, this, PAY_UI::UNIONPAY));
return true;
}
void GamePayLayer::onEnter() {
HNLayer::onEnter();
schedule(schedule_selector(GamePayLayer::updateOpacity), 0.01f);
}
void GamePayLayer::paySelectEventCallBack(Ref* pSender, Widget::TouchEventType type, int uiTag) {
if (Widget::TouchEventType::ENDED != type) return;
HNAudioEngine::getInstance()->playEffect(GAME_SOUND_CLOSE);
switch (uiTag) {
case PAY_UI::CLOSE_TAG: {
auto winSize = Director::getInstance()->getWinSize();
this->runAction(Sequence::create(EaseSineIn::create(MoveBy::create(0.3f, Vec2(-winSize.width, 0))),
CCCallFunc::create(CC_CALLBACK_0(GamePayLayer::closeLayer, this)),
RemoveSelf::create(true), nullptr));
}
break;
case PAY_UI::WECHAT_TAG:
_delegate->onPayEvent(PaySelectedDelegate::WECHAT);
break;
case PAY_UI::ALIPAY_TAG:
_delegate->onPayEvent(PaySelectedDelegate::ALIPAY);
break;
case PAY_UI::UNIONPAY:
_delegate->onPayEvent(PaySelectedDelegate::UNIONPAY);
break;
{
}
break;
default:
break;
}
}
void GamePayLayer::updateOpacity(float dt) {
_opacity = _opacity + 8;
Layer* colorLayer = (Layer*)this->getChildByTag(10);
colorLayer->setOpacity(_opacity);
if (_opacity >= 100) {
unschedule(schedule_selector(GamePayLayer::updateOpacity));
}
}
void GamePayLayer::closeLayer() {
_delegate->onPayClose();
}
|
37c1b9243056d7413fcf0094f78742a9dd61b482 | 61b23cadab2249c09fae26cb9485314207f4eab3 | /src/semantic/types/constraints/TypeConstraintUnifyVisitor.cpp | 2c8efd9da2115c5c899a24bb1b84d0886d81bc17 | [
"MIT"
] | permissive | matthewbdwyer/tipc | c3fc058958b540830be15a2a24321dd4e60f2d69 | 92bc57d0c2f63e9d14ac6eca3fb28368ed2fa3a5 | refs/heads/main | 2023-08-17T03:40:51.183052 | 2023-08-15T21:09:30 | 2023-08-15T21:09:30 | 205,929,620 | 62 | 32 | MIT | 2023-09-02T21:38:23 | 2019-09-02T20:13:09 | C++ | UTF-8 | C++ | false | false | 365 | cpp | TypeConstraintUnifyVisitor.cpp | #include "TypeConstraintUnifyVisitor.h"
#include "ConstraintUnifier.h"
TypeConstraintUnifyVisitor::TypeConstraintUnifyVisitor(SymbolTable *pTable)
: TypeConstraintVisitor(pTable, std::move(buildConstraintHandler())) {}
std::shared_ptr<ConstraintHandler>
TypeConstraintUnifyVisitor::buildConstraintHandler() {
return std::make_shared<ConstraintUnifier>();
}
|
42c02e149e8df56172b749b572f3dc3b0646c821 | 0c907bdb4a7a8c81d4f5d645c0e08ffaaf9b30ba | /FlyForYourLife/Source/RacingGame/Private/GameModes/TimeTrialMode.cpp | d84a405780f42c5ae29e4e2216d3d1bd1e1b4817 | [] | no_license | Rodolfo377/Futuristic_Racing | 4a35a66cd3652b27ccb176c3c59e1b7668cfad68 | 6e826a06e0090d3094f78d597e67e1d689f4a5a0 | refs/heads/master | 2021-03-11T13:01:52.352243 | 2020-07-22T22:54:40 | 2020-07-22T22:54:40 | 246,531,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 132 | cpp | TimeTrialMode.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "../../Public/GameModes/TimeTrialMode.h"
|
bbc540207c23fc64710350bc7a4733b736f26b5c | 686fc01dffaddffcf97a42f7bdfe1d368c326ed5 | /src/meta_data/cppwrapper.hpp | eaecd380e6de7e74f684281f1373385f7a9840bd | [] | no_license | rootfs/fusionfs | 4330dc1e1d4d15b9ccd34ec366ef22792c685f84 | 7dcdd03578112a9bc66d2e930ac8029fda10a3d0 | refs/heads/master | 2020-05-20T09:21:45.435057 | 2015-01-14T14:11:23 | 2015-01-14T14:11:23 | 29,246,384 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,686 | hpp | cppwrapper.hpp | #ifndef cppwrap_hh
#define cppwrap_hh
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <fuse.h>
#include <libgen.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/xattr.h>
#ifdef __cplusplus
extern "C" {
#endif
void set_Namespace(const char *path);
int cppwrap_create(const char *path, mode_t mode, struct fuse_file_info *fileInfo);
int cppwrap_getattr(const char *path, struct stat *statbuf);
int cppwrap_readlink(const char *path, char *link, size_t size);
int cppwrap_mknod(const char *path, mode_t mode, dev_t dev);
int cppwrap_mkdir(const char *path, mode_t mode);
int cppwrap_unlink(const char *path);
int cppwrap_rmdir(const char *path);
int cppwrap_symlink(const char *path, const char *link);
int cppwrap_rename(const char *path, const char *newpath);
int cppwrap_link(const char *path, const char *newpath);
int cppwrap_chmod(const char *path, mode_t mode);
int cppwrap_chown(const char *path, uid_t uid, gid_t gid);
int cppwrap_truncate(const char *path, off_t newSize);
int cppwrap_utime(const char *path, struct utimbuf *ubuf);
int cppwrap_open(const char *path, struct fuse_file_info *fileInfo);
int cppwrap_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo);
int cppwrap_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo);
int cppwrap_statfs(const char *path, struct statvfs *statInfo);
int cppwrap_flush(const char *path, struct fuse_file_info *fileInfo);
int cppwrap_release(const char *path, struct fuse_file_info *fileInfo);
int cppwrap_fsync(const char *path, int datasync, struct fuse_file_info *fi);
int cppwrap_setxattr(const char *path, const char *name, const char *value, size_t size, int flags);
int cppwrap_getxattr(const char *path, const char *name, char *value, size_t size);
int cppwrap_listxattr(const char *path, char *list, size_t size);
int cppwrap_removexattr(const char *path, const char *name);
int cppwrap_opendir(const char *path, struct fuse_file_info *fileInfo);
int cppwrap_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo);
int cppwrap_releasedir(const char *path, struct fuse_file_info *fileInfo);
int cppwrap_fsyncdir(const char *path, int datasync, struct fuse_file_info *fileInfo);
void* cppwrap_init(struct fuse_conn_info *conn);
int cppwrap_access(const char *path, int mode);
#ifdef __cplusplus
}
#endif
#endif //cppwrap_hh
|
3327ce1738cc8e4adbc36fd05d7a0b9311276e0d | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-mediaconnect/include/aws/mediaconnect/model/DescribeOfferingRequest.h | 24fbaef28dce40bcf9134ccc06c93dad6430a9fd | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 2,629 | h | DescribeOfferingRequest.h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/mediaconnect/MediaConnect_EXPORTS.h>
#include <aws/mediaconnect/MediaConnectRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace MediaConnect
{
namespace Model
{
/**
*/
class DescribeOfferingRequest : public MediaConnectRequest
{
public:
AWS_MEDIACONNECT_API DescribeOfferingRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "DescribeOffering"; }
AWS_MEDIACONNECT_API Aws::String SerializePayload() const override;
/**
* The Amazon Resource Name (ARN) of the offering.
*/
inline const Aws::String& GetOfferingArn() const{ return m_offeringArn; }
/**
* The Amazon Resource Name (ARN) of the offering.
*/
inline bool OfferingArnHasBeenSet() const { return m_offeringArnHasBeenSet; }
/**
* The Amazon Resource Name (ARN) of the offering.
*/
inline void SetOfferingArn(const Aws::String& value) { m_offeringArnHasBeenSet = true; m_offeringArn = value; }
/**
* The Amazon Resource Name (ARN) of the offering.
*/
inline void SetOfferingArn(Aws::String&& value) { m_offeringArnHasBeenSet = true; m_offeringArn = std::move(value); }
/**
* The Amazon Resource Name (ARN) of the offering.
*/
inline void SetOfferingArn(const char* value) { m_offeringArnHasBeenSet = true; m_offeringArn.assign(value); }
/**
* The Amazon Resource Name (ARN) of the offering.
*/
inline DescribeOfferingRequest& WithOfferingArn(const Aws::String& value) { SetOfferingArn(value); return *this;}
/**
* The Amazon Resource Name (ARN) of the offering.
*/
inline DescribeOfferingRequest& WithOfferingArn(Aws::String&& value) { SetOfferingArn(std::move(value)); return *this;}
/**
* The Amazon Resource Name (ARN) of the offering.
*/
inline DescribeOfferingRequest& WithOfferingArn(const char* value) { SetOfferingArn(value); return *this;}
private:
Aws::String m_offeringArn;
bool m_offeringArnHasBeenSet = false;
};
} // namespace Model
} // namespace MediaConnect
} // namespace Aws
|
cd791abc8c18bac0978af1684f96ee4af9aff69e | 8a95cb1e783c9e15dacf28f43b6bb19fa047cab7 | /Event.cpp | 1e672d9508769d75af2fa68b9e69db8db7c1f191 | [] | no_license | cbshiles/KALX-Open-Bloomberg | 65d1cfcdbc6e24d2a2d4098ab3ee9499dcee4a37 | a7326612e73459e6ceb5f75ac190823122878dd5 | refs/heads/master | 2021-07-23T23:36:33.513258 | 2013-07-05T16:59:45 | 2013-07-05T16:59:45 | 109,073,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,003 | cpp | Event.cpp | // Event.cpp - blpapi Event class
// Copyright KALX, LLC. All rights reserved. No warranty made.
#pragma warning(disable: 4244 4127)
#include "blpapi_event.h"
#include "xllblp.h"
using namespace BloombergLP;
using namespace blpapi;
using namespace xll;
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_ADMIN, BLPAPI_EVENTTYPE_ADMIN, CATEGORY, "Admin event", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_ADMIN))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_SESSION_STATUS, BLPAPI_EVENTTYPE_SESSION_STATUS, CATEGORY, "Status updates for a session.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_SESSION_STATUS))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_SUBSCRIPTION_STATUS, BLPAPI_EVENTTYPE_SUBSCRIPTION_STATUS, CATEGORY, "Status updates for a subscription.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_SUBSCRIPTION_STATUS))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_REQUEST_STATUS, BLPAPI_EVENTTYPE_REQUEST_STATUS, CATEGORY, "Status updates for a request.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_REQUEST_STATUS))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_RESPONSE, BLPAPI_EVENTTYPE_RESPONSE, CATEGORY, "The final (possibly only) response to a request.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_RESPONSE))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_PARTIAL_RESPONSE, BLPAPI_EVENTTYPE_PARTIAL_RESPONSE, CATEGORY, "A partial response to a request.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_PARTIAL_RESPONSE))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_SUBSCRIPTION_DATA, BLPAPI_EVENTTYPE_SUBSCRIPTION_DATA, CATEGORY, "Data updates resulting from a subscription.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_SUBSCRIPTION_DATA))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_SERVICE_STATUS, BLPAPI_EVENTTYPE_SERVICE_STATUS, CATEGORY, "Status updates for a service.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_SERVICE_STATUS))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_TIMEOUT, BLPAPI_EVENTTYPE_TIMEOUT, CATEGORY, "An Event returned from nextEvent() if it timed out.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_TIMEOUT))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_AUTHORIZATION_STATUS, BLPAPI_EVENTTYPE_AUTHORIZATION_STATUS, CATEGORY, "Status updates for user authorization.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_AUTHORIZATION_STATUS))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_RESOLUTION_STATUS, BLPAPI_EVENTTYPE_RESOLUTION_STATUS, CATEGORY, "Status updates for a resolution operation.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_RESOLUTION_STATUS))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_TOPIC_STATUS, BLPAPI_EVENTTYPE_TOPIC_STATUS, CATEGORY, "Status updates about topics for service providers.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_TOPIC_STATUS))
XLL_ENUM_DOC(BLPAPI_EVENTTYPE_TOKEN_STATUS, BLPAPI_EVENTTYPE_TOKEN_STATUS, CATEGORY, "Status updates for a generate token request.", "Has value " XLL_STRZ_(BLPAPI_EVENTTYPE_TOKEN_STATUS))
static AddIn xai_blp_event_type(
Function(XLL_LONG, "?xll_blp_event_type", "BLP.EVENT.TYPE")
.Arg(XLL_HANDLE, "Event", "is a handle to an Event.")
.Category(CATEGORY)
.FunctionHelp("Return the type of an Event from the BLPAPI_EVENTTYPE_* enumeration.")
.Documentation(
"Return the basic data type used to represent a value in this "
"element. The possible return values are enumerated in "
"the <codeInline>BLPAPI_DATATYPE_*</codeInline> enumeration. "
)
);
LONG WINAPI
xll_blp_event_type(HANDLEX event)
{
#pragma XLLEXPORT
int l(0);
try {
handle<Event> he(event,false);
ensure (he && he->isValid());
l = he->eventType();
}
catch (const std::exception& ex) {
XLL_ERROR(ex.what());
}
catch (const Exception& ex) {
XLL_ERROR(ex.description().c_str());
}
return l;
}
static AddIn xai_blp_message_iterator(
Function(XLL_HANDLE, "?xll_blp_message_iterator", "BLP.MESSAGE.ITERATOR")
.Arg(XLL_HANDLE, "Event", "is a handle to an Event.")
.Category(CATEGORY)
.FunctionHelp("Return a handle to a MessageIterator of Event.")
.Documentation(
"An iterator over the Message objects within an Event. "
"</para><para>"
"MessageIterator objects are used to process the individual "
"Message objects in an Event received in an EventHandler, from "
"EventQueue::nextEvent() or from Session::nextEvent(). "
"</para><para>"
"This class is used to iterate over each message in an "
"Event. The user must ensure that the Event this iterator is "
"created for is not destroyed before the iterator. "
)
);
HANDLEX WINAPI
xll_blp_message_iterator(HANDLEX event)
{
#pragma XLLEXPORT
HANDLEX h(0);
try {
handle<Event> he(event,false);
ensure (he && he->isValid());
MessageIterator mi(*he);
h = p2h<MessageIterator>(&mi);
}
catch (const std::exception& ex) {
XLL_ERROR(ex.what());
}
catch (const Exception& ex) {
XLL_ERROR(ex.description().c_str());
}
return h;
}
static AddIn xai_blp_message_iterator_next(
Function(XLL_BOOL, "?xll_blp_message_iterator_next", "BLP.MESSAGE.ITERATOR.NEXT")
.Arg(XLL_HANDLE, "MessageIterator", "is a handle to a MessageIterator.")
.Category(CATEGORY)
.FunctionHelp("Advance to the next message and return 0 on success.")
.Documentation(
"Attempts to advance this MessageIterator to the next "
"Message in this Event. Returns 0 on success and non-zero if "
"there are no more messages. After next() returns 0 "
"isValid() returns true, even if called repeatedly until the "
"next call to next(). After next() returns non-zero then "
"isValid() always returns false. "
)
);
BOOL WINAPI
xll_blp_message_iterator_next(HANDLEX message_iterator)
{
#pragma XLLEXPORT
BOOL b(1);
try {
handle<MessageIterator> hmi(message_iterator,false);
ensure (hmi && hmi->isValid());
b = hmi->next();
}
catch (const std::exception& ex) {
XLL_ERROR(ex.what());
}
catch (const Exception& ex) {
XLL_ERROR(ex.description().c_str());
}
return b;
}
static AddIn xai_blp_message_iterator_message(
Function(XLL_HANDLE, "?xll_blp_message_iterator_message", "BLP.MESSAGE.ITERATOR.MESSAGE")
.Arg(XLL_HANDLE, "MessageIterator", "is a handle to a MessageIterator.")
.Arg(XLL_BOOL, "Clone", "is an optional boolean indicating a copy of the Message will be returned. ")
.Category(CATEGORY)
.FunctionHelp("Returns the Message at the current position of this iterator.")
.Documentation(
"If the "
"specified 'Clone' flag is set, the internal handle of the "
"message returned is added a reference and the message can outlive "
"the call to next(). If the 'Clone' flag is set to false, "
"the use of message outside the scope of the iterator or after the "
"next() call is undefined. "
"The behavior is undefined if isValid() returns false. "
)
);
HANDLEX WINAPI
xll_blp_message_iterator_message(HANDLEX message_iterator, BOOL clone)
{
#pragma XLLEXPORT
HANDLEX h(0);
try {
handle<MessageIterator> hmi(message_iterator,false);
ensure (hmi && hmi->isValid());
Message m(hmi->message(clone != 0)); // pulls in __imp__g_blpapiFunctionEntries
h = p2h<Message>(&m);
}
catch (const std::exception& ex) {
XLL_ERROR(ex.what());
}
catch (const Exception& ex) {
XLL_ERROR(ex.description().c_str());
}
return h;
}
|
764e8357df6d9b67b5da456dd6f41bd4088fd51c | b44bf2739444921db3dd3c8e6efc41c70c6cb0b9 | /WN8OS-master/kernel/core/ioport.cc | 61a912eead1591877325d3adc1cf0f5eeea2bcb5 | [
"MIT"
] | permissive | satyrswang/os | ebf25df1964fe851e5aed48513aa3fa25c0907bd | 79bc2778a530dd3a8866cf85320dac6ac2fa8b66 | refs/heads/master | 2021-05-05T18:11:31.396928 | 2017-09-15T21:59:27 | 2017-09-15T21:59:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | cc | ioport.cc | #include "ioport.h"
namespace ioport
{
void outb(ioport_t port, u8 val)
{
__asm__ __volatile__ ("outb %0, %1" :: "a"(val), "Nd" (port));
}
void outw(ioport_t port, u16 val)
{
__asm__ __volatile__ ("outw %0, %1" :: "a"(val), "Nd" (port));
}
void outl(ioport_t port, u32 val)
{
__asm__ __volatile__ ("outl %0, %1" :: "a"(val), "Nd" (port));
}
u8 inb(ioport_t port)
{
u8 val;
__asm__ __volatile__ ("inb %1, %0" : "=a"(val) : "Nd"(port));
return val;
}
u16 inw(ioport_t port)
{
u16 val;
__asm__ __volatile__ ("inw %1, %0" : "=a"(val) : "Nd"(port));
return val;
}
u32 inl(ioport_t port)
{
u32 val;
__asm__ __volatile__ ("inl %1, %0" : "=a"(val) : "Nd"(port));
return val;
}
}
|
049b7f4220482ce43158bf164f09ccd594f79bfc | b8273be80d7f36b64768c68e2228783d004f334a | /成绩管理系统/Source.cpp | 171b242bacde75902dd09402bc5e86ad205c7390 | [] | no_license | SH201808/level1 | 2fc6e6136b98523048954082dd069be7643e6985 | af11ce4bb62e8b05ff508272e5191132026f6c97 | refs/heads/master | 2023-05-03T09:15:48.651627 | 2021-05-21T13:07:24 | 2021-05-21T13:07:24 | 369,515,426 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,430 | cpp | Source.cpp | #include<iostream>
#include<string>
#include<vector>
#include<fstream>
#include<sstream>
using namespace std;
struct student{
string ID;
string name;
string Cla;
int math;
int physics;
int c;
}s;
class Student_System{
public:
void input();
void output();
void Add();
void Search_Dele_Modify();
void Delete(int s);
void Modify(int v);
void Sort();
void select(int k,int F);
void exchangeA(int z);
void outData(int o);
private:
int max = 0;
vector<student>a = {};
}ss;
bool judge(string &s, string &s1);
template<class T>
void exchange(T &x, T &y){
T t;
t = x;
x = y;
y = t;
}
void Student_System::exchangeA(int z){
exchange(a[z].math, a[z + 1].math);
exchange(a[z].physics, a[z + 1].physics);
exchange(a[z].c, a[z + 1].c);
exchange(a[z].name, a[z+1].name);
exchange(a[z].ID, a[z + 1].ID);
exchange(a[z].Cla, a[z + 1].Cla);
}
int main()
{
int n;
cout << "【1】输入文件内容" << endl;
cout << "【2】显示文件内容" << endl;
cout << "【3】增添数据" << endl;
cout << "【4】查找数据,修改数据,删除数据" << endl;
cout << "【5】成绩排序" << endl;
cout << "请选择功能,或者按0退出程序" << endl;
while (cin >> n){
if (n == 0){
return 0;
}
else{
switch (n)
{
case 1:
ss.input();
break;
case 2:
ss.output();
break;
case 3:
ss.Add();
break;
case 4:
ss.Search_Dele_Modify();
break;
case 5:
ss.Sort();
break;
case 6:
system("cls");
break;
default:
cout << "输入方式错误" << endl;
break;
}
}
cout << "【1】输入文件内容" << endl;
cout << "【2】显示文件内容" << endl;
cout << "【3】增添数据" << endl;
cout << "【4】查找数据,修改数据,删除数据" << endl;
cout << "【5】成绩排序" << endl;
cout << "【6】清屏" << endl;
cout << "请选择功能,或者按0退出程序" << endl;
}
}
//输入
void Student_System::input(){
string filename,temp1,temp2,temp3;
cout << "请输入打开的csv文件格式:" << endl;
cin >> filename;
//filename = "C:\\Users\\DELL\\Desktop\\Data.csv";
ifstream infile(filename);
if (!infile)
cout << "文件打开失败" << endl;
else
cout << "文件打开成功" << endl;
while (infile.peek() != EOF){
getline(infile, s.ID, ',');
getline(infile, s.name, ',');
getline(infile, s.Cla, ',');
getline(infile, temp1,',');
stringstream ss1(temp1);
ss1 >> s.math;
getline(infile, temp2, ',');
stringstream ss2(temp2);
ss2 >> s.physics;
getline(infile, temp3);
stringstream ss3(temp3);
ss3 >> s.c;
a.push_back(s);
max++;
}
}
//输出
void Student_System::output(){
cout << "序号\t" << "ID\t\t" << "姓名\t\t"<<"班级\t\t" << "高等数学\t" <<"大学物理\t"<<"编程基础\t"<< endl;
for (int i = 0; i < max; i++){
outData(i);
}
}
//查找
void Student_System::Search_Dele_Modify(){
int f = 0;
int n;
cout << "【1】学号查找" << endl;
cout << "【2】姓名查找" << endl;
cout << "【3】序号查找" << endl;
cout << "【4】班级查找" << endl;
cout << "请选择查找方式:" << endl;
cin >> n;
if (n == 1){
string SID;
int f = 0;
cout << "请输入查找的学号:" << endl;
cin >> SID;
for (int i = 0; i < max; i++){
if (judge(a[i].ID, SID)){
select(i, n);
f++;
break;
}
}
if (f==0)
cout << "查无此人" << endl;
}
else if (n == 2){
string Sname;
cout << "请输入查找的姓名:" << endl;
cin >> Sname;
for (int i = 0; i < max; i++){
if (judge(a[i].name, Sname)){
select(i, n);
f++;
}
}
if (f == 0)
cout << "查无此人" << endl;
}
else if (n == 3){
int No_;
cout << "请输入查找的序号" << endl;
cin >> No_;
if (No_ <= max){
select(No_-1, n);
}
else{
cout << "查无此人" << endl;
}
}
else if (n == 4){
string cla;
cout << "请输入查找的班级" << endl;
cin >> cla;
for (int i = 0; i < max; i++){
if (judge(a[i].Cla, cla)){
select(i, n);
f++;
}
}
if (f == 0){
cout << "查无此人" << endl;
}
}
}
//增添问题
void Student_System::Add(){
cout << "请输入增添的学号:" << endl;
cin >> s.ID;
cout << "请输入增添的姓名:" << endl;
cin >> s.name;
cout << "请输入增添的班级:" << endl;
cin >> s.Cla;
cout << "请输入增添的高数成绩:" << endl;
cin >> s.math;
cout << "请输入增添的大物成绩:" << endl;
cin >> s.physics;
cout << "请输入增添的编程成绩:" << endl;
cin >> s.c;
cout << "插入完成" << endl;
a.push_back(s);
max++;
}
//删除
void Student_System::Delete(int v){
int sign = v;
int i = 0;
if (sign+1 == max){
a.pop_back();
}
else{
vector<student>::iterator del;
for (del = a.begin(); del != a.end(); del++,i++){
if (sign == i){
del = a.erase(del);
}
}
}
max--;
cout << "删除成功" << endl;
}
//修改数据
void Student_System::Modify(int v){
int n2,tmath,tphy,tc;
int sign = v;
string Itemp, Ntemp,Ctemp;
cout << "请选择需要修改的数据:" << endl;
cout << "【1】学号" << endl;
cout << "【2】姓名" << endl;
cout << "【3】班级" << endl;
cout << "【4】高数成绩" << endl;
cout << "【5】大物成绩" << endl;
cout << "【6】编程成绩" << endl;
cin >> n2;
if (n2 == 1){
cout << "请输入修改后的学号:" << endl;
(cin>>Itemp);
a[sign].ID = Itemp;
}
else if (n2 == 2){
cout << "请输入修改后的姓名:" << endl;
cin>>Ntemp;
a[sign].name = Ntemp;
}
else if (n2 == 3){
cout << "请输入修改后的班级:" << endl;
cin >> Ctemp;
a[sign].Cla = Ctemp;
}
else if (n2 == 4){
cout << "请输入修改后的高数成绩:" << endl;
cin >> tmath;
a[sign].math = tmath;
}
else if (n2 == 5){
cout << "请输入修改后的大物成绩:" << endl;
cin >> tphy;
a[sign].physics = tphy;
}
else if (n2 == 6){
cout << "请输入修改后的编程成绩:" << endl;
cin >> tc;
a[sign].c = tc;
}
cout << "修改完成" << endl;
}
//查找
void Student_System::select(int k,int F){
int n;
if (F == 1 || F == 2||F==4){
cout << "查找成功" << endl;
cout << "序号\t" << "ID\t\t" << "姓名\t\t" << "班级\t\t" << "高等数学\t" << "大学物理\t" << "编程基础\t" << endl;
outData(k);
cout << "请问是否对该学生数据进行删除或修改:" << endl;
cout << "【5】删除数据" << endl;
cout << "【6】修改数据" << endl;
cout << "【0】继续查找或返回主菜单" << endl;
cin >> n;
if (n == 5){
Delete(k);
}
else if (n == 6){
Modify(k);
}
}
else if (F==3){
cout << "查找成功" << endl;
cout << "序号\t" << "ID\t\t" << "姓名\t\t" << "班级\t\t" << "高等数学\t" << "大学物理\t" << "编程基础\t" << endl;
outData(k);
cout << "请问是否对该学生数据进行删除或修改:" << endl;
cout << "【5】删除数据" << endl;
cout << "【6】修改数据" << endl;
cout << "【0】继续查找或返回主菜单" << endl;
cin >> n;
if (n == 5){
Delete(k);
}
else if (n == 6){
Modify(k);
}
}
}
//排序
void Student_System::Sort(){
int r;
cout << "请输入需要排序的科目" << endl;
cout << "【1】高等数学" << endl;
cout << "【2】大学物理" << endl;
cout << "【3】编程基础" << endl;
cin >> r;
for (int i = 0; i < max - 1; i++){
bool flag = false;
for (int j = 0; j < max -i-1 ; j++){
if (r == 1){
if (a[j].math < a[j + 1].math){
exchangeA(j);
flag = true;
}
}
else if (r==2){
if (a[j].physics < a[j + 1].physics){
exchangeA(j);
flag = true;
}
}
else if (r == 3){
if (a[j].c < a[j + 1].c){
exchangeA(j);
flag = true;
}
}
}
if (!flag)
break;
}
cout << "排序完成" << endl;
}
//输出单条数据
void Student_System::outData(int o){
if (a[o].name.size() <= 6){
cout << o + 1 << "\t" << a[o].ID << "\t" << a[o].name << "\t\t" << a[o].Cla << "\t" << a[o].math << "\t\t" << a[o].physics << "\t\t" << a[o].c << endl;
}
else{
cout << o + 1 << "\t" << a[o].ID << "\t" << a[o].name << "\t" << a[o].Cla << "\t" << a[o].math << "\t\t" << a[o].physics << "\t\t" << a[o].c << endl;
}
}
//判断数据是否匹配
bool judge(string &s, string&s1){
int len = s.size(), len1 = s1.size();
if (len != len1){
return false;
}
else{
for (int i = 0; i < len; i++){
if (s[i] != s1[i]){
return false;
}
}
return true;
}
}
|
3af5d10066181db27b6d7e4088883d5c9b656850 | 48a128080eef29a1f5bf38d10dc5e2beca89a02d | /src/GeepGLFW/Foundation.h | db798536a2b42c43bc90b9a02658efa133959cf0 | [
"Apache-2.0"
] | permissive | AtomicFiction/rezpackages | 636ecefd58a5c1d8597a44337f3d7677a1de4735 | 906cd67f7144a22a1d3b1ce77554d2b3e5d2bba8 | refs/heads/master | 2022-02-11T08:32:57.931129 | 2019-06-20T20:54:24 | 2019-06-20T20:54:24 | 45,408,080 | 5 | 1 | null | 2018-03-22T17:11:33 | 2015-11-02T16:50:03 | CMake | UTF-8 | C++ | false | false | 1,751 | h | Foundation.h | //-*****************************************************************************
// Copyright 2015 Christopher Jon Horvath
//
// 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 _EncinoWaves_GeepGLFW_Foundation_h_
#define _EncinoWaves_GeepGLFW_Foundation_h_
#define GLFW_INCLUDE_GLU 1
//-*****************************************************************************
// MAC INCLUDES
//-*****************************************************************************
#ifndef PLATFORM_DARWIN
#include <GL/glew.h>
#else
//#include <OpenGL/gl3.h>
#endif // ifdef PLATFORM_DARWIN
#define GLFW_INCLUDE_GLCOREARB
#undef GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#ifdef PLATFORM_DARWIN
#include <OpenGL/glext.h>
#endif
#include <Util/All.h>
#include <vector>
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
namespace EncinoWaves {
namespace GeepGLFW {
//-*****************************************************************************
// NOTHING
//-*****************************************************************************
} // namespace GeepGLFW
} // namespace EncinoWaves
#endif
|
a41e2e9a9a7dd4122c7f5e662c4098d53308c6ae | 278f96657aec5dfe3e793642acc1b41aee018db1 | /source/JitterFromRedNoise.cpp | 632de182e4710a78448354cfa8172807df077dc4 | [] | no_license | BertoltLang/BertPlatoSim | 615ef4e12518e02c5eddf8d0fa6f077911f2d0c6 | c79d1ee68e2b82d6ab4369f80bf1ec3f8b562ca5 | refs/heads/master | 2021-01-23T07:43:53.801973 | 2017-03-28T08:45:52 | 2017-03-28T08:45:52 | 86,436,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,101 | cpp | JitterFromRedNoise.cpp | #include "JitterFromRedNoise.h"
/**
* \brief Constructor
*
* \param configParams The configuration parameters from the input parameters file
*/
JitterFromRedNoise::JitterFromRedNoise(ConfigurationParameters &configParams)
: lastYaw(0.0), lastPitch(0.0), lastRoll(0.0)
{
// Set the configuration parameters
configure(configParams);
// Seed the random generator. The seed should have been set by configure().
// Initialise the standard normal distribution with mu=0, and sigma=1.0.
jitterNoiseGenerator.seed(jitterNoiseSeed);
normalDistribution = normal_distribution<double>(0.0, 1.0);
}
/**
* \brief Destructor
*/
JitterFromRedNoise::~JitterFromRedNoise()
{
}
/**
* \brief Configure this object using the parameters from the input parameters file
*
* \param configParams The configuration parameters
*/
void JitterFromRedNoise::configure(ConfigurationParameters &configParams)
{
// Note that the inputfile lists the jitter RMS values in [arcsec]
yawRMS = deg2rad(configParams.getDouble("Platform/JitterYawRms") / 3600.);
pitchRMS = deg2rad(configParams.getDouble("Platform/JitterPitchRms") / 3600.);
rollRMS = deg2rad(configParams.getDouble("Platform/JitterRollRms") / 3600.);
jitterTimeScale = configParams.getDouble("Platform/JitterTimeScale");
jitterNoiseSeed = configParams.getLong("RandomSeeds/JitterSeed");
// We determine the jitter time interval as a fraction of the jitter time scale.
// so that the changes in (yaw, pitch, roll) can still be reliably tracked.
jitterTimeInterval = jitterTimeScale / 20.0;
}
/**
* \brief Get the next (yaw, pitch, roll) values using a Brownian motion model. These yaw, pitch,
* and roll values are with respect to the original pointing (at t=0), NOT with respect to
* the last pointing.
*
* \note Also during CCD readout, the spacecraft jitters, to the user needs to take this into
* account when passing 'timeInterval'.
*
* \param timeInterval[in] Time interval that has passed since the last getNextYawPitchRoll() request. [s]
*
* \return (newYaw, newPitch, newRoll) [rad]
*/
tuple<double, double, double> JitterFromRedNoise::getNextYawPitchRoll(double timeInterval)
{
// If the time interval is zero, return the last computed values
if (timeInterval == 0.0)
{
make_tuple(lastYaw, lastPitch, lastRoll);
}
// Use bind() to get a shorter normal01() function to generate random numbers instead of
// the cumbersome normalDistribition(jitterNoiseGenerator). Note: the std::ref() is needed,
// otherwise a copy is passed and the generator would always return the same number.
auto normal01 = std::bind(normalDistribution, ref(jitterNoiseGenerator));
// The time step with which the yaw, pitch and roll will be iteratively updated.
// Normally this time step is the jitterTimeInterval, but if the user-given timeInterval
// is actually smaller than, take the latter.
double timeStep = min(timeInterval, jitterTimeInterval);
// Initialise the (yaw, pitch, roll) values with the last computed ones
double newYaw = lastYaw;
double newPitch = lastPitch;
double newRoll = lastRoll;
// Move through the user-given timeInterval in steps of 'timeStep',
// each time updating the yaw, pitch, and roll.
int n = 0;
while (n * timeStep < timeInterval)
{
newYaw = exp(-timeStep/jitterTimeScale) * newYaw + yawRMS * sqrt(timeStep/jitterTimeScale) * normal01();
newPitch = exp(-timeStep/jitterTimeScale) * newPitch + pitchRMS * sqrt(timeStep/jitterTimeScale) * normal01();
newRoll = exp(-timeStep/jitterTimeScale) * newRoll + rollRMS * sqrt(timeStep/jitterTimeScale) * normal01();
n++;
}
// In case that the user-given timeInterval cannot be covered with an integral number
// of 'timeSteps', there is a small time interval left which still needs to be covered
timeStep = timeInterval - (n-1) * timeStep;
newYaw = exp(-timeStep/jitterTimeScale) * newYaw + yawRMS * sqrt(timeStep/jitterTimeScale) * normal01();
newPitch = exp(-timeStep/jitterTimeScale) * newPitch + pitchRMS * sqrt(timeStep/jitterTimeScale) * normal01();
newRoll = exp(-timeStep/jitterTimeScale) * newRoll + rollRMS * sqrt(timeStep/jitterTimeScale) * normal01();
// Save the (yaw, pitch, roll) values for the next request
lastYaw = newYaw;
lastPitch = newPitch;
lastRoll = newRoll;
// That's it!
return make_tuple(newYaw, newPitch, newRoll);
}
/**
* \brief Return the heartbeat interval of this Red Noise jitter generator
*
* \details The heartbeat interval is the jitter time interval which is set to a fraction of
* the jitter time scale. so that the changes in (yaw, pitch, roll) can still be
* reliably tracked.
*
* \return heartbeatInterval [s]
*/
double JitterFromRedNoise::getHeartbeatInterval()
{
return jitterTimeInterval;
}
|
8eec75c1847a43018887550b2de2b99b4e277e96 | 74cd1bf6cb3359e26282f5f814b6d02d426f0b31 | /09_thousandLookAtMe/src/square.cpp | 62ea15f7af15345c689f9fd9ad36c3cba6e0cb18 | [] | no_license | bschorr/OFCourse_ThousandParticles | 6e2c0e068f2c9b75b90a50f4c1d69362b2917e93 | 772623c6c2cd511d64a2855c588b625db7962442 | refs/heads/master | 2016-08-11T19:21:48.891731 | 2016-03-19T23:30:49 | 2016-03-19T23:30:49 | 54,291,643 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 565 | cpp | square.cpp | //
// square.cpp
// 06_lookAtMe
//
// Created by Bernardo Schorr on 4/30/15.
//
//
#include "square.h"
void square::setup(ofVec2f _pos) {
pos = _pos;
}
void square::update(ofVec2f lookAt) {
ofVec2f diff;
diff = lookAt - pos;
rot = atan2(diff.y, diff.x);
rot = ofRadToDeg(rot);
gray = diff.length();
}
void square::draw() {
ofSetRectMode(OF_RECTMODE_CENTER);
ofSetColor(0, gray);
ofPushMatrix();
ofTranslate(pos);
ofRotate(rot);
ofRect(0, 0, 20, 20);
ofPopMatrix();
} |
8dd576862df41c5e61da4f954d7db706158b3e61 | 94f955b45caef0b21d1ff5ed453519d0fb632e05 | /resource/performance_sample/performance_sample/src/sample_data.cpp | 2a48035efcedfc59fceb784e14e00f4001f75955 | [] | no_license | googol-lab/310_data | 2259bd10ec91a6b303845c709ed93f4f69ffba45 | b06663fdea4d387eb02435f7a10520c9b5096fbf | refs/heads/master | 2020-12-12T08:02:38.232393 | 2019-06-12T08:48:35 | 2019-06-12T08:48:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,164 | cpp | sample_data.cpp | /**
* @file sample_main.cpp
*
* Copyright (C) <2018> <Huawei Technologies Co., Ltd.>. All Rights Reserved.
*
* 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.
*/
#include "sample_data.h"
#include "hiaiengine/data_type.h"
#include "hiaiengine/ai_memory.h"
// 注册序列化和反序列化函数
/**
* @ingroup hiaiengine
* @brief GetTransSearPtr, 序列化Trans数据
* @param [in] : data_ptr 结构体指针
* @param [out]:struct_str 结构体buffer
* @param [out]:data_ptr 结构体数据指针buffer
* @param [out]:struct_size 结构体大小
* @param [out]:data_size 结构体数据大小
* @author w00437212
*/
void GetTransSearPtr(void* data_ptr, std::string& struct_str,
uint8_t*& buffer, uint32_t& buffer_size)
{
EngineTransNewT* engine_trans = (EngineTransNewT*)data_ptr;
// 获取结构体buffer和size
struct_str = std::string((char*)data_ptr, sizeof(EngineTransNewT));
// 获取结构体数据buffer和size
buffer = (uint8_t*)engine_trans->trans_buff.get();
buffer_size = engine_trans->buffer_size;
}
/**
* @ingroup hiaiengine
* @brief GetTransSearPtr, 反序列化Trans数据
* @param [in] : ctrl_ptr 结构体指针
* @param [in] : data_ptr 结构体数据指针
* @param [out]:std::shared_ptr<void> 传给Engine的指针结构体指针
* @author w00437212
*/
std::shared_ptr<void> GetTransDearPtr(
const char* ctrlPtr, const uint32_t& ctrlLen,
const uint8_t* dataPtr, const uint32_t& dataLen)
{
std::shared_ptr<EngineTransNewT> engine_trans_ptr = std::make_shared<EngineTransNewT>();
// 给engine_trans_ptr赋值
engine_trans_ptr->buffer_size = ((EngineTransNewT*)ctrlPtr)->buffer_size;
engine_trans_ptr->trans_buff.reset((unsigned char*)dataPtr, hiai::HIAIMemory::HIAI_DFree);
return std::static_pointer_cast<void>(engine_trans_ptr);
}
// 注册EngineTransNewT
HIAI_REGISTER_SERIALIZE_FUNC("EngineTransNewT", EngineTransNewT, GetTransSearPtr, GetTransDearPtr);
|
72c7a16dbeb0d772a265baad8efa38c4e775f3e2 | 6987a1383bb376adda4303a7aa80c6d4192681c7 | /src/libcamera/include/ipa_context_wrapper.h | c9e194120de6b69c3efea554c386bb2871362e7b | [] | no_license | shristi428/libcamera | 66af541c9ce7e2d390a953e07d5520cd632f5ff3 | dd9429f438865c5a48b460b4ce33b3f74f90027f | refs/heads/master | 2021-02-25T15:04:35.251005 | 2020-02-05T10:34:46 | 2020-02-24T09:45:56 | 245,457,790 | 1 | 0 | null | 2020-03-06T15:44:10 | 2020-03-06T15:44:09 | null | UTF-8 | C++ | false | false | 1,274 | h | ipa_context_wrapper.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
* Copyright (C) 2019, Google Inc.
*
* ipa_context_wrapper.h - Image Processing Algorithm context wrapper
*/
#ifndef __LIBCAMERA_IPA_CONTEXT_WRAPPER_H__
#define __LIBCAMERA_IPA_CONTEXT_WRAPPER_H__
#include <ipa/ipa_interface.h>
#include "control_serializer.h"
namespace libcamera {
class IPAContextWrapper final : public IPAInterface
{
public:
IPAContextWrapper(struct ipa_context *context);
~IPAContextWrapper();
int init() override;
void configure(const std::map<unsigned int, IPAStream> &streamConfig,
const std::map<unsigned int, const ControlInfoMap &> &entityControls) override;
void mapBuffers(const std::vector<IPABuffer> &buffers) override;
void unmapBuffers(const std::vector<unsigned int> &ids) override;
virtual void processEvent(const IPAOperationData &data) override;
private:
static void queue_frame_action(void *ctx, unsigned int frame,
struct ipa_operation_data &data);
static const struct ipa_callback_ops callbacks_;
void doQueueFrameAction(unsigned int frame,
const IPAOperationData &data);
struct ipa_context *ctx_;
IPAInterface *intf_;
ControlSerializer serializer_;
};
} /* namespace libcamera */
#endif /* __LIBCAMERA_IPA_CONTEXT_WRAPPER_H__ */
|
b2293d8e3ae7bae7e5d58604d9c2746abc929132 | 85ba4e6e293b61908abee97cf12fc6f04fa5b99a | /ecl/hqlcpp/hqlcse.cpp | 328c1441d012cee59eb18c8c402d3aa83b91937d | [
"Apache-2.0"
] | permissive | praveenmak/HPCC-Platform | 6021a561c01d9706aaf5b86bbaa059284b9f6190 | 30cb9026779310921567106e9d5b090e81065b33 | refs/heads/master | 2021-01-14T11:48:56.585472 | 2014-04-02T14:20:09 | 2014-04-02T14:20:09 | 18,383,693 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,759 | cpp | hqlcse.cpp | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
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 "platform.h"
#include "jlib.hpp"
#include "jmisc.hpp"
#include "jstream.ipp"
#include "hql.hpp"
#include "hqlcse.ipp"
#include "hqlutil.hpp"
#include "hqlcpputil.hpp"
#include "hqlthql.hpp"
#include "hqlcatom.hpp"
#include "hqlfold.hpp"
#include "hqlpmap.hpp"
#include "hqlopt.hpp"
#include "hqlcerrors.hpp"
#include "hqlttcpp.ipp"
#ifdef _DEBUG
//#define TRACE_CSE
#endif
//The following allows x != y and x == y to be commoned up. It works, but currently disabled
//because cse doesn't preserve short circuit of AND and OR, and some examples mean it will do more
//work because the alias will always be evaluated. (e.g., salt1.xhql)
//Really aliases need to be functional and executed on demand or something similar.
//#define OPTIMIZE_INVERSE
//---------------------------------------------------------------------------
inline bool canWrapWithCSE(IHqlExpression * expr)
{
switch (expr->getOperator())
{
case no_mapto:
return false;
}
return true;
}
bool canCreateTemporary(IHqlExpression * expr)
{
switch (expr->getOperator())
{
case no_range:
case no_rangefrom:
case no_rangeto:
case no_rangecommon:
case no_constant:
case no_all:
case no_mapto:
case no_record:
case no_attr:
case no_attr_expr:
case no_attr_link:
case no_joined:
case no_sizeof:
case no_offsetof:
case no_newtransform:
case no_transform:
case no_assign:
case no_assignall:
case no_left:
case no_right:
case no_self:
case no_top:
case no_activetable:
case no_alias:
case no_skip:
case no_assert:
case no_counter:
case no_sortlist:
case no_matched:
case no_matchtext:
case no_matchunicode:
case no_matchposition:
case no_matchlength:
case no_matchattr:
case no_matchrow:
case no_matchutf8:
case no_recordlist:
case no_transformlist:
case no_rowvalue:
case no_pipe:
case no_colon:
case no_globalscope:
case no_subgraph:
case no_forcelocal:
case no_forcenolocal:
case no_allnodes:
case no_thisnode:
case no_libraryscopeinstance:
case no_loopbody:
return false;
}
ITypeInfo * type = expr->queryType();
if (!type)
return false;
switch (type->getTypeCode())
{
case type_transform:
case type_null:
case type_void:
case type_rule:
case type_pattern:
case type_token:
return false;
default:
return true;
}
}
//---------------------------------------------------------------------------
/*
Cse spotting...
* Don't remove named symbols from items that aren't transformed.
* Common items up regardless of the named symbol used to reference it.
*/
CseSpotterInfo::CseSpotterInfo(IHqlExpression * expr) : NewTransformInfo(expr)
{
numRefs = 0;
numAssociatedRefs = 0;
alreadyAliased = false;
canAlias = false;
dontTransform = false;
dontTransformSelector = false;
treatAsAliased = false;
inverse = NULL;
annotatedExpr = NULL;
}
//worth aliasing if referenced more than once, and used more than once in the expressions that are going to be evaluated now
bool CseSpotterInfo::worthAliasingOnOwn()
{
return numRefs > 1 && (numRefs != numAssociatedRefs);
}
bool CseSpotterInfo::worthAliasing()
{
if (!inverse)
return worthAliasingOnOwn();
//no_not will always traverse the inverse (at least once), so don't sum the two counts - just use the non inverted count
if (original->getOperator() == no_not)
return worthAliasingOnOwn() || inverse->worthAliasingOnOwn();
if (inverse->original->getOperator() == no_not)
return worthAliasingOnOwn();
unsigned totalRefs = numRefs + inverse->numRefs;
unsigned totalAssociatedRefs = numAssociatedRefs + inverse->numAssociatedRefs;
if ((totalRefs > 1) && (totalRefs != totalAssociatedRefs))
return true;
return false;
}
//Do we create an alias for this node, or the other one?
bool CseSpotterInfo::useInverseForAlias()
{
if (!inverse)
return false;
if (numRefs == numAssociatedRefs)
return true;
node_operator op = original->getOperator();
switch (op)
{
case no_not:
case no_ne:
case no_notin:
case no_notbetween:
return inverse->worthAliasingOnOwn();
}
node_operator invOp = inverse->original->getOperator();
switch (invOp)
{
case no_not: return false; //No otherwise we'll expand recursively!
case no_ne:
case no_notin:
case no_notbetween:
return !worthAliasingOnOwn();
}
return op > invOp;
}
static HqlTransformerInfo cseSpotterInfo("CseSpotter");
CseSpotter::CseSpotter(bool _spotCseInIfDatasetConditions)
: NewHqlTransformer(cseSpotterInfo), spotCseInIfDatasetConditions(_spotCseInIfDatasetConditions)
{
canAlias = true;
isAssociated = false;
spottedCandidate = false;
invariantSelector = NULL;
createLocalAliases = false;
createdAlias = false;
}
void CseSpotter::analyseAssociated(IHqlExpression * expr, unsigned pass)
{
isAssociated = true;
analyse(expr, pass);
isAssociated = false;
}
void CseSpotter::analyseExpr(IHqlExpression * expr)
{
CseSpotterInfo * extra = queryBodyExtra(expr);
if (!extra->annotatedExpr && expr->isAnnotation())
extra->annotatedExpr = expr;
if (isAssociated)
extra->numAssociatedRefs++;
node_operator op = expr->getOperator();
#ifdef OPTIMIZE_INVERSE
if (getInverseOp(op) != no_none)
{
OwnedHqlExpr inverse = getInverse(expr);
CseSpotterInfo * inverseExtra = queryBodyExtra(inverse);
extra->inverse = inverseExtra;
inverseExtra->inverse = extra;
}
#endif
if (op == no_alias)
{
queryBodyExtra(expr->queryChild(0))->alreadyAliased = true;
extra->alreadyAliased = true;
}
switch (op)
{
case no_assign:
case no_transform:
case no_newtransform:
case no_range:
case no_rangefrom:
if (expr->isConstant())
return;
break;
case no_constant:
return;
}
if (extra->numRefs++ != 0)
{
if (op == no_alias)
return;
if (!spottedCandidate && extra->worthAliasing())
spottedCandidate = true;
if (canCreateTemporary(expr))
return;
//Ugly! This is here as a temporary hack to stop branches of maps being commoned up and always
//evaluated. The alias spotting and generation really needs to take conditionality into account....
if (op == no_mapto)
return;
}
if (!containsPotentialCSE(expr))
return;
if (canAlias && !expr->isDataset())
extra->canAlias = true;
bool savedCanAlias = canAlias;
if (expr->isDataset() && (op != no_select) && (!spotCseInIfDatasetConditions || (op != no_if)))
{
//There is little point looking for CSEs within dataset expressions, because only a very small
//minority which would correctly cse, and it can cause lots of problems - e.g., join conditions.
unsigned first = getFirstActivityArgument(expr);
unsigned num = getNumActivityArguments(expr);
HqlExprArray children;
bool defaultCanAlias = canAlias;
ForEachChild(i, expr)
{
IHqlExpression * cur = expr->queryChild(i);
if (i >= first && i < first+num)
canAlias = defaultCanAlias;
else
canAlias = false;
analyseExpr(cur);
}
}
else
PARENT::analyseExpr(expr);
canAlias = savedCanAlias;
}
IHqlExpression * CseSpotter::createAliasOwn(IHqlExpression * expr, CseSpotterInfo * extra)
{
#ifdef TRACE_CSE
StringBuffer s;
DBGLOG("Create alias for %s (%d refs)", getExprIdentifier(s, expr).str(), extra->numRefs);
#endif
extra->alreadyAliased = true;
if (createLocalAliases)
return ::createAliasOwn(expr, createLocalAttribute());
return ::createAliasOwn(expr, NULL);
}
IHqlExpression * CseSpotter::createTransformed(IHqlExpression * expr)
{
node_operator op = expr->getOperator();
switch (op)
{
case no_matched:
case no_matchtext:
case no_matchunicode:
case no_matchposition:
case no_matchlength:
case no_matchrow:
case no_matchutf8:
//These actually go wrong if we remove the named symbols, so traverse under no circumstances.
//others can be traversed to patch up references to datasets that have changed.
case no_translated:
return LINK(expr);
}
OwnedHqlExpr transformed = PARENT::createTransformed(expr);
CseSpotterInfo * splitter = queryBodyExtra(expr);
//MORE: Possibly add a unique number to the alias when this starts worrying about child scopes.
if (splitter->canAlias && splitter->worthAliasing() && checkPotentialCSE(expr, splitter))
{
if (splitter->useInverseForAlias())
{
OwnedHqlExpr inverse = getInverse(expr);
OwnedHqlExpr transformedInverse = transform(inverse);
return getInverse(transformedInverse);
}
createdAlias = true;
//Use the transformed body to ensure that any cses only create a single instance,
//But annotate with first annotation spotted, try and retain the symbols to aid debugging.
LinkedHqlExpr aliasValue = transformed->queryBody();
// if (splitter->annotatedExpr)
// aliasValue.setown(splitter->annotatedExpr->cloneAllAnnotations(aliasValue));
OwnedHqlExpr alias = createAliasOwn(aliasValue.getClear(), splitter);
return alias.getClear();
return expr->cloneAllAnnotations(alias);
}
return transformed.getClear();
}
ANewTransformInfo * CseSpotter::createTransformInfo(IHqlExpression * expr)
{
return CREATE_NEWTRANSFORMINFO(CseSpotterInfo, expr);
}
bool CseSpotter::containsPotentialCSE(IHqlExpression * expr)
{
switch (expr->getOperator())
{
case no_record:
case no_attr:
case no_attr_expr:
case no_attr_link:
case no_joined:
case no_sizeof:
case no_offsetof:
case no_field:
case no_evaluate: // MORE: This is an example of introducing a new scope...
case no_translated: // Causes recursion otherwise....
case no_left:
case no_right:
case no_top:
case no_self:
case no_selfref:
case no_activetable:
case no_filepos:
case no_file_logicalname:
case no_matched:
case no_matchtext:
case no_matchunicode:
case no_matchposition:
case no_matchrow:
case no_matchlength:
case no_matchutf8:
case no_catch:
case no_projectrow:
// case no_evalonce:
return false;
case no_select:
return false; //isNewSelector(expr);
case NO_AGGREGATE:
//There may possibly be cses, but we would need to do lots of scoping analysis to work out whether they were
//really common.
return false;
case no_assign:
case no_assignall:
case no_transform:
case no_newtransform:
case no_range:
case no_rangefrom:
case no_rangeto:
case no_rangecommon:
case no_skip:
return true;
case no_compound_diskread:
case no_compound_indexread:
case no_compound_disknormalize:
case no_compound_diskaggregate:
case no_compound_diskcount:
case no_compound_diskgroupaggregate:
case no_compound_indexnormalize:
case no_compound_indexaggregate:
case no_compound_indexcount:
case no_compound_indexgroupaggregate:
case no_compound_childread:
case no_compound_childnormalize:
case no_compound_childaggregate:
case no_compound_childcount:
case no_compound_childgroupaggregate:
case no_compound_selectnew:
case no_compound_inline:
return false;
#if 0
//Strictly speaking, we shouldn't common up conditional expressions, but it generally provides such a reduction in code
//that it will stay enabled until I come up with a better scheme.
case no_if:
case no_rejected:
case no_which:
case no_case:
case no_map:
return false;
#endif
}
ITypeInfo * type = expr->queryType();
if (type && type->getTypeCode() == type_void)
return false;
return !expr->isConstant();// || expr->isDataset() || expr->isDatarow();
}
bool CseSpotter::checkPotentialCSE(IHqlExpression * expr, CseSpotterInfo * extra)
{
if (extra->alreadyAliased)
return false;
if (!expr->isPure() || !canCreateTemporary(expr))
return false;
if (invariantSelector && exprReferencesDataset(expr, invariantSelector))
return false;
switch (expr->getOperator())
{
case no_eq:
case no_ne:
case no_gt:
case no_ge:
case no_lt:
case no_le:
{
//Don't combine integer comparisons into a CSE - not worth it...
ITypeInfo * type = expr->queryChild(0)->queryType();
switch (type->getTypeCode())
{
case type_boolean:
case type_int:
return false;
}
return true;
}
case no_not:
{
IHqlExpression * child = expr->queryChild(0);
if (queryBodyExtra(child)->isAliased())
return false;
break;
}
case no_charlen:
{
IHqlExpression * child = expr->queryChild(0);
if (queryBodyExtra(child)->isAliased() || child->getOperator() == no_select)
{
type_t tc = child->queryType()->getTypeCode();
switch (tc)
{
case type_varstring:
case type_varunicode:
return true;
}
//prevent (trivial-cast)length(x) from being serialized etc.
extra->treatAsAliased = true;
return false;
}
break;
}
case no_field:
throwUnexpected();
case no_select:
//MORE: ds[n].x would probably be worth cseing.
return false;
case no_list:
case no_datasetlist:
case no_getresult: // these are commoned up in the code generator, so don't do it twice.
case no_getgraphresult:
case no_getgraphloopresult:
case no_translated: // Causes recursion otherwise....
case no_random:
return false;
case no_call:
case no_externalcall:
case no_libraryinput:
case no_counter:
return true;
case no_substring:
{
SubStringHelper helper(expr);
return !helper.canGenerateInline();
}
case no_cast:
case no_implicitcast:
{
ITypeInfo * exprType = expr->queryType();
if (exprType->getTypeCode() == type_set)
return false;
IHqlExpression * uncast = expr->queryChild(0);
if (uncast->queryValue())
return false;
//Ignore integral casts of items that have already been aliased
if (queryBodyExtra(uncast)->isAliased())
{
if (exprType->isInteger() && uncast->queryType()->isInteger())
{
if (extra->numRefs < 5)
return false;
}
}
break;
}
//Following are all source datasets - no point in commoning them up
//although probably exceptions e.g., table(,pipe)
case no_none:
case no_null:
case no_anon:
case no_pseudods:
case no_all:
// case no_table: - normally work commoning up
case no_temptable:
case no_inlinetable:
case no_xmlproject:
case no_datasetfromrow:
case no_datasetfromdictionary:
case no_preservemeta:
case no_dataset_alias:
case no_workunit_dataset:
case no_left:
case no_right:
case no_top:
case no_self:
case no_selfref:
case no_keyindex:
case no_newkeyindex:
case no_fail:
case no_activetable:
case no_soapcall:
case no_newsoapcall:
case no_id2blob:
case no_embedbody:
case no_rows:
return false;
}
if (!expr->queryType())
return false;
return (expr->numChildren() > 0);
}
IHqlExpression * CseSpotter::transform(IHqlExpression * expr)
{
return PARENT::transform(expr);
}
IHqlExpression * CseSpotter::queryAlreadyTransformed(IHqlExpression * expr)
{
CseSpotterInfo * extra = queryBodyExtra(expr);
if (extra->dontTransform)
return expr;
IHqlExpression * ret = PARENT::queryAlreadyTransformed(expr);
if (!ret)
{
IHqlExpression * body = expr->queryBody();
if (body != expr)
{
ret = PARENT::queryAlreadyTransformed(body);
if (ret == body)
return NULL;
}
}
return ret;
}
IHqlExpression * CseSpotter::queryAlreadyTransformedSelector(IHqlExpression * expr)
{
CseSpotterInfo * extra = queryBodyExtra(expr);
if (extra->dontTransformSelector)
return expr;
return PARENT::queryAlreadyTransformedSelector(expr);
}
void CseSpotter::stopTransformation(IHqlExpression * expr)
{
IHqlExpression * normalized = expr->queryNormalizedSelector();
queryBodyExtra(expr)->dontTransform = true;
queryBodyExtra(normalized)->dontTransformSelector = true;
}
//---------------------------------------------------------------------------
static HqlTransformerInfo conjunctionTransformerInfo("ConjunctionTransformer");
ConjunctionTransformer::ConjunctionTransformer() : NewHqlTransformer(conjunctionTransformerInfo)
{
}
IHqlExpression * ConjunctionTransformer::createTransformed(IHqlExpression * expr)
{
node_operator op = expr->getOperator();
OwnedHqlExpr transformed;
switch (op)
{
case no_matched:
case no_matchtext:
case no_matchunicode:
case no_matchlength:
case no_matchposition:
case no_matchrow:
case no_matchutf8:
return LINK(expr);
//not so sure why the following causes problems - because the tables get changed I think.
case no_filepos:
case no_file_logicalname:
case no_sizeof:
case no_offsetof:
return LINK(expr);
case no_and:
case no_or:
{
IHqlExpression * left = expr->queryChild(0);
if (left->getOperator() == op)
{
HqlExprArray args, transformedArgs;
left->unwindList(args, op);
ForEachItemIn(i, args)
transformedArgs.append(*transform(&args.item(i)));
transformedArgs.append(*transform(expr->queryChild(1)));
transformed.setown(createLeftBinaryList(op, transformedArgs));
// return expr->cloneAllAnnotations(transformed);
}
break;
}
}
if (!transformed)
transformed.setown(NewHqlTransformer::createTransformed(expr));
return transformed.getClear();
}
//---------------------------------------------------------------------------
#ifdef NEW_CSE_PROCESSING
inline bool canInsertCodeAlias(IHqlExpression * expr)
{
switch (expr->getOperator())
{
case no_range:
case no_rangefrom:
case no_rangeto:
case no_rangecommon:
case no_mapto:
case no_recordlist:
case no_transformlist:
case no_rowvalue:
case no_sortlist:
return false;
default:
return true;
}
}
static HqlTransformerInfo cseScopeTransformerInfo("CseScopeTransformer");
CseScopeTransformer::CseScopeTransformer()
: NewHqlTransformer(cseScopeTransformerInfo)
{
activeParent = NULL;
seq = 0;
conditionDepth = 0;
}
void CseScopeTransformer::analyseExpr(IHqlExpression * expr)
{
expr = expr->queryBody();
if (!containsNonGlobalAlias(expr))
return;
node_operator op = expr->getOperator();
CseScopeInfo * splitter = queryExtra(expr);
if (splitter->seq)
{
splitter->hasSharedParent = true;
splitter->addParent(activeParent);
return;
}
splitter->firstParent = activeParent;
splitter->seq = ++seq;
splitter->isUnconditional = (conditionDepth == 0);
{
IHqlExpression * savedParent = activeParent;
activeParent = expr;
switch (op)
{
case no_if:
case no_or:
case no_and:
case no_case:
{
analyseExpr(expr->queryChild(0));
conditionDepth++;
ForEachChildFrom(i, expr, 1)
analyseExpr(expr->queryChild(i));
conditionDepth--;
break;
}
default:
NewHqlTransformer::analyseExpr(expr);
break;
}
activeParent = savedParent;
}
//Add here so the cse are in the correct order to cope with dependencies...
if (op == no_alias)
{
assertex(!expr->hasAttribute(globalAtom));
allCSEs.append(*LINK(splitter));
}
}
bool CseScopeTransformer::attachCSEs(IHqlExpression * root)
{
bool changed = false;
ForEachItemIn(idx, allCSEs)
{
CseScopeInfo& cur = allCSEs.item(idx);
IHqlExpression * aliasLocation = findAliasLocation(&cur);
if (!aliasLocation && cur.isUnconditional)
aliasLocation = root;
if (aliasLocation && aliasLocation != cur.original)
{
queryExtra(aliasLocation)->aliasesToDefine.append(*LINK(cur.original));
changed = true;
}
}
return changed;
}
IHqlExpression * CseScopeTransformer::createTransformed(IHqlExpression * expr)
{
//Can't short-circuit transformation if (!containsAlias(expr)) because it means references to transformed datasets won't get patched up
IHqlExpression * body = expr->queryBody(true);
if (body != expr)
{
OwnedHqlExpr ret = transform(body);
return expr->cloneAnnotation(ret);
}
//slight difference from before...
IHqlExpression * transformed = NewHqlTransformer::createTransformed(expr);
CseScopeInfo * splitter = queryExtra(expr);
if (splitter->aliasesToDefine.ordinality())
{
HqlExprArray args;
args.append(*transformed);
ForEachItemIn(idx, splitter->aliasesToDefine)
{
IHqlExpression * value = &splitter->aliasesToDefine.item(idx);
args.append(*transform(value));
}
if (expr->isDataset())
transformed = createDataset(no_alias_scope, args);
else if (expr->isDatarow())
transformed = createRow(no_alias_scope, args);
else
transformed = createValue(no_alias_scope, transformed->getType(), args);
}
return transformed;
}
ANewTransformInfo * CseScopeTransformer::createTransformInfo(IHqlExpression * expr)
{
return CREATE_NEWTRANSFORMINFO(CseScopeInfo, expr);
}
//First find the highest shared parent node (or this if no parents are shared)
CseScopeInfo * CseScopeTransformer::calcCommonLocation(CseScopeInfo * extra)
{
if (extra->calcedCommonLocation)
return extra->commonLocation;
CseScopeInfo * commonLocation = extra;
if (extra->firstParent)
{
CseScopeInfo * firstParentExtra = queryExtra(extra->firstParent);
CseScopeInfo * commonParent = calcCommonLocation(firstParentExtra);
if ((extra->parents.ordinality() == 0) && (!firstParentExtra->hasSharedParent || extra->firstParent->getOperator() == no_alias))
// if ((extra->parents.ordinality() == 0) && !firstParentExtra->hasSharedParent)
{
//assertex(commonParent == firstParentExtra);
//commonParent = extra;
}
else
{
extra->hasSharedParent = true;
commonLocation = commonParent;
ForEachItemIn(i, extra->parents)
{
CseScopeInfo * nextExtra = calcCommonLocation(queryExtra(extra->parents.item(i)));
if (nextExtra->isUnconditional)
extra->isUnconditional = true;
commonLocation = findCommonPath(commonLocation, nextExtra);
if (!commonLocation && extra->isUnconditional)
break;
}
}
}
else
{
if (extra->hasSharedParent)
commonLocation = NULL;
}
extra->calcedCommonLocation = true;
extra->commonLocation = commonLocation;
return commonLocation;
}
IHqlExpression * CseScopeTransformer::findAliasLocation(CseScopeInfo * extra)
{
CseScopeInfo * best = calcCommonLocation(extra);
loop
{
if (!best)
return NULL;
IHqlExpression * bestLocation = best->original;
if (canInsertCodeAlias(bestLocation))
return bestLocation;
best = selectParent(best);
}
}
CseScopeInfo * CseScopeTransformer::selectParent(CseScopeInfo * info)
{
if (info->hasSharedParent)
return info->commonLocation;
if (!info->firstParent)
return NULL;
return queryExtra(info->firstParent);
}
CseScopeInfo * CseScopeTransformer::findCommonPath(CseScopeInfo * left, CseScopeInfo * right)
{
loop
{
if (!left || !right)
return NULL;
if (left == right)
return left;
if (left->seq > right->seq)
left = selectParent(left);
else
right = selectParent(right);
}
}
#else
CSEentry::CSEentry(IHqlExpression * _value, PathArray & _path)
{
value.set(_value);
unsigned depth=_path.ordinality();
path.ensure(depth);
ForEachItemIn(idx, _path)
path.append(_path.item(idx));
ensurePathValid();
}
void CSEentry::ensurePathValid()
{
//It is not valid to insert a no_code_alias at certain points....
while (path.ordinality())
{
switch (path.tos().getOperator())
{
case no_range:
case no_rangefrom:
case no_rangeto:
case no_rangecommon:
case no_mapto:
case no_recordlist:
case no_transformlist:
case no_rowvalue:
case no_sortlist:
path.pop();
break;
default:
return;
}
}
}
void CSEentry::findCommonPath(PathArray & otherPath)
{
unsigned prevPath = path.ordinality();
unsigned maxPath = path.ordinality();
if (maxPath > otherPath.ordinality())
maxPath = otherPath.ordinality();
unsigned idx;
for (idx = 0; idx < maxPath; idx++)
{
IHqlExpression * l = &path.item(idx);
IHqlExpression * r = &otherPath.item(idx);
if (l != r)
break;
}
//Ensure the new location is valid for receiving the CSE
while (idx != 0)
{
if (canWrapWithCSE(&path.item(idx-1)))
break;
idx--;
}
path.trunc(idx);
if (prevPath != path.ordinality())
{
ForEachItemIn(idx2, dependsOn)
dependsOn.item(idx2).findCommonPath(path);
}
ensurePathValid();
}
static HqlTransformerInfo cseScopeTransformerInfo("CseScopeTransformer");
CseScopeTransformer::CseScopeTransformer()
: NewHqlTransformer(cseScopeTransformerInfo)
{
}
void CseScopeTransformer::analyseExpr(IHqlExpression * expr)
{
expr = expr->queryBody();
if (!containsNonGlobalAlias(expr))
return;
CSEentry * cse = NULL;
node_operator op = expr->getOperator();
if (op == no_alias)
{
assertex(!expr->hasAttribute(globalAtom));
CseScopeInfo * splitter = queryExtra(expr);
//PrintLog("splitter: %s", expr->toString(StringBuffer()).str());
if (splitter->cseUse)
{
//Find the common path, and map the alias.
CSEentry * cse = splitter->cseUse;
cse->findCommonPath(path);
if (activeCSE.ordinality())
activeCSE.tos().dependsOn.append(*LINK(cse));
return;
}
cse = new CSEentry(expr, path);
splitter->cseUse.setown(cse);
if (activeCSE.ordinality())
activeCSE.tos().dependsOn.append(*LINK(cse));
activeCSE.append(*LINK(cse));
}
#if 0
if ((op == no_transform) || (op == no_newtransform))
{
//For a transform add each assignment as a path point - so the aliases for assignments don't end up
//before aliases for skip attributes.
path.append(*expr);
ForEachChild(i, expr)
{
IHqlExpression * cur = expr->queryChild(i);
analyseExpr(cur);
path.append(*cur);
}
ForEachChild(i2, expr)
path.pop();
path.pop();
}
else
#endif
{
path.append(*expr);
NewHqlTransformer::analyseExpr(expr);
path.pop();
}
//Add here so the cse are in the correct order to cope with dependencies...
if (cse)
{
allCSEs.append(*LINK(cse));
activeCSE.pop();
}
}
bool CseScopeTransformer::attachCSEs(IHqlExpression * /*root*/)
{
bool changed = false;
ForEachItemIn(idx, allCSEs)
{
CSEentry & cur = allCSEs.item(idx);
if (cur.path.ordinality())
{
IHqlExpression & location = cur.path.tos();
queryExtra(&location)->cseDefine.append(OLINK(cur));
changed = true;
}
}
return changed;
}
IHqlExpression * CseScopeTransformer::createTransformed(IHqlExpression * expr)
{
//Can't short-circuit transformation if (!containsAlias(expr)) because it means references to transformed datasets won't get patched up
IHqlExpression * body = expr->queryBody(true);
if (body != expr)
{
OwnedHqlExpr ret = transform(body);
return expr->cloneAnnotation(ret);
}
//slight difference from before...
IHqlExpression * transformed = NewHqlTransformer::createTransformed(expr);
CseScopeInfo * splitter = queryExtra(expr);
if (splitter->cseDefine.ordinality())
{
HqlExprArray args;
args.append(*transformed);
ForEachItemIn(idx, splitter->cseDefine)
{
CSEentry & cur = splitter->cseDefine.item(idx);
args.append(*transform(cur.value));
}
if (expr->isDataset())
transformed = createDataset(no_alias_scope, args);
else if (expr->isDatarow())
transformed = createRow(no_alias_scope, args);
else
transformed = createValue(no_alias_scope, transformed->getType(), args);
}
return transformed;
}
ANewTransformInfo * CseScopeTransformer::createTransformInfo(IHqlExpression * expr)
{
return CREATE_NEWTRANSFORMINFO(CseScopeInfo, expr);
}
#endif
IHqlExpression * spotScalarCSE(IHqlExpression * expr, IHqlExpression * limit, bool spotCseInIfDatasetConditions)
{
if (expr->isConstant())
return LINK(expr);
switch (expr->getOperator())
{
case no_select:
if (!isNewSelector(expr))
return LINK(expr);
break;
}
OwnedHqlExpr transformed = LINK(expr); //removeNamedSymbols(expr);
bool addedAliases = false;
//First spot the aliases - so that restructuring the ands doesn't lose any existing aliases.
{
CseSpotter spotter(spotCseInIfDatasetConditions);
spotter.analyse(transformed, 0);
if (spotter.foundCandidates())
{
if (limit)
spotter.stopTransformation(limit);
transformed.setown(spotter.transformRoot(transformed));
addedAliases = spotter.createdNewAliases();
}
}
if (!containsAlias(transformed))
return transformed.getClear();
//Transform conjunctions so they are (a AND (b AND (c AND d))) not (((a AND b) AND c) AND d)
//so that alias scope can be introduced in a better place.
{
ConjunctionTransformer tr;
transformed.setown(tr.transformRoot(transformed));
}
if (!addedAliases)
return transformed.getClear();
//Now work out where in the tree the aliases should be evaluated.
{
CseScopeTransformer scoper;
scoper.analyse(transformed, 0);
if (scoper.attachCSEs(transformed))
transformed.setown(scoper.transformRoot(transformed));
}
return transformed.getClear();
}
void spotScalarCSE(SharedHqlExpr & expr, SharedHqlExpr & associated, IHqlExpression * limit, IHqlExpression * invariantSelector, bool spotCseInIfDatasetConditions)
{
CseSpotter spotter(spotCseInIfDatasetConditions);
spotter.analyse(expr, 0);
if (associated)
spotter.analyseAssociated(associated, 0);
if (!spotter.foundCandidates())
return;
if (limit)
spotter.stopTransformation(limit);
if (invariantSelector)
spotter.setInvariantSelector(invariantSelector);
expr.setown(spotter.transformRoot(expr));
associated.setown(spotter.transformRoot(associated));
}
void spotScalarCSE(HqlExprArray & exprs, HqlExprArray & associated, IHqlExpression * limit, IHqlExpression * invariantSelector, bool spotCseInIfDatasetConditions)
{
CseSpotter spotter(spotCseInIfDatasetConditions);
spotter.analyseArray(exprs, 0);
ForEachItemIn(ia, associated)
spotter.analyseAssociated(&associated.item(ia), 0);
if (!spotter.foundCandidates())
return;
if (limit)
spotter.stopTransformation(limit);
if (invariantSelector)
spotter.setInvariantSelector(invariantSelector);
HqlExprArray newExprs;
HqlExprArray newAssociated;
spotter.transformRoot(exprs, newExprs);
spotter.transformRoot(associated, newAssociated);
replaceArray(exprs, newExprs);
replaceArray(associated, newAssociated);
}
//---------------------------------------------------------------------------
//The TableInvariantTransformer is important for ensuring that getResultXXX code is executed in the code context, amongst other things
//It must ensure that any global aliases couldn't contain some other global aliases inside a child query, otherwise when the child query is
//evaluated the result won't be in the correct place.
//
//MORE: This could be improved to work out whether it is worth creating an alias (which will then be serialized...)
//e.g., don't alias i) <alias<n>> +- offset or ii) extension of an alias's size., iii) substring of a fixed size string. iv) length(string
//however it is pretty good as it stands.
//ideally it would need information about how many times the expression is likely to be evaluated (e.g., 1/many)
//so that could be taken into account (e.g, filenames which are 'string' + conditional)
static bool canHoistInvariant(IHqlExpression * expr)
{
if (!canCreateTemporary(expr))
{
if ((expr->getOperator() != no_alias) || expr->hasAttribute(globalAtom))
return false;
}
if (!expr->isPure())
return false;
switch (expr->getOperator())
{
case no_list:
case no_datasetlist:
case no_createdictionary:
return false; // probably don't want to hoist these
}
return true;
}
static HqlTransformerInfo tableInvariantTransformerInfo("TableInvariantTransformer");
TableInvariantTransformer::TableInvariantTransformer() : NewHqlTransformer(tableInvariantTransformerInfo)
{
canAlias = true;
}
bool TableInvariantTransformer::isInvariant(IHqlExpression * expr)
{
TableInvariantInfo * extra = queryBodyExtra(expr);
if (extra->cachedInvariant)
return extra->isInvariant;
bool invariant = false;
node_operator op = expr->getOperator();
switch (op)
{
case no_record:
case no_null:
case no_activetable:
case no_activerow:
case no_left:
case no_right:
case no_self:
case no_top:
case no_selfref:
case no_filepos:
case no_file_logicalname:
case no_joined:
case no_offsetof:
case no_sizeof:
case NO_AGGREGATE:
break;
case no_preservemeta:
invariant = isInvariant(expr->queryChild(0));
break;
case no_workunit_dataset:
case no_getresult:
if (expr->hasAttribute(wuidAtom))
invariant = isInvariant(expr->queryAttribute(wuidAtom));
else
invariant = true;
break;
case no_constant:
case no_getgraphresult:
invariant = true;
break;
case no_select:
{
if (!expr->isDataset())
{
IHqlExpression * ds = expr->queryChild(0);
if (expr->hasAttribute(newAtom) || ds->isDatarow())
invariant = isInvariant(ds);
}
break;
}
case no_newaggregate:
{
//Allow these on a very strict subset of the datasets - to ensure that no potential globals can be included in the dataset
if (!isInvariant(expr->queryChild(0)))
break;
switch (querySimpleAggregate(expr, false, true))
{
case no_existsgroup:
case no_countgroup:
invariant = true;
break;
}
break;
}
case no_selectnth:
switch (expr->queryChild(1)->getOperator())
{
case no_constant:
case no_counter:
invariant = isInvariant(expr->queryChild(0));
break;
}
break;
default:
if (!isContextDependent(expr))
//MORE: The following line is needed if the xml/parse flags are removed from the context, but it causes problems
//preventing counts from being hoisted as aliases. That is really correct - but it makes code worse for some examples.
//if (!isContextDependent(expr) && expr->isIndependentOfScope())
{
if (!expr->isAction())// && !expr->isDataset() && !expr->isDatarow())
{
invariant = true;
ForEachChild(i, expr)
{
IHqlExpression * cur = expr->queryChild(i);
if (!isInvariant(cur))
{
invariant = false;
break;
}
}
}
}
break;
}
extra->cachedInvariant = true;
extra->isInvariant = invariant;
return invariant;
}
#if 0
void TableInvariantTransformer::analyseExpr(IHqlExpression * expr)
{
expr = expr->queryBody();
if (alreadyVisited(expr))
return;
node_operator op = expr->getOperator();
switch (op)
{
case no_record:
case no_constant:
return;
}
if (isInvariant(expr) && !expr->isAttribute() && !expr->isConstant() && canHoistInvariant(expr))
{
TableInvariantInfo * extra = queryBodyExtra(expr);
if (op == no_alias)
{
if (!expr->hasAttribute(globalAtom))
extra->createAlias = true;
}
else
extra->createAlias = true;
return;
}
if (op == no_attr_expr)
analyseChildren(expr);
else
NewHqlTransformer::analyseExpr(expr);
}
#else
void TableInvariantTransformer::analyseExpr(IHqlExpression * expr)
{
expr = expr->queryBody();
TableInvariantInfo * extra = queryBodyExtra(expr);
if (alreadyVisited(expr))
return;
//More - these need to be handled properly...
node_operator op = expr->getOperator();
switch (op)
{
case no_record:
case no_constant:
return;
}
//We are trying to ensure that any expressions that don't access fields that are dependent on the activeDatasets/context are only
//evaluated once => check for active dataset rather than any dataset
bool candidate = false;
if (!isContextDependent(expr) && !expr->isAttribute())
{
if (isInlineTrivialDataset(expr) && !expr->isConstant())
{
candidate = (op != no_null);
}
else
{
if (!containsActiveDataset(expr))
{
//MORE: We should be able to hoist constant datasets (e.g., temptables), but it causes problems
//e.g., stops items it contains from being aliased. So
if (!expr->isAction() && !expr->isDataset() && !expr->isDatarow())
{
switch (op)
{
case no_alias:
if (!expr->hasAttribute(globalAtom))
extra->createAlias = true;
return;
default:
//MORE: We should be able to hoist constant datasets (e.g., temptables), but it causes problems
//e.g., stops items it contains from being aliased.
candidate = !expr->isConstant();
break;
}
}
}
}
if (candidate && canHoistInvariant(expr))
{
extra->createAlias = true;
return;
}
}
if (op == no_attr_expr)
analyseChildren(expr);
else
NewHqlTransformer::analyseExpr(expr);
}
#endif
bool TableInvariantTransformer::isAlwaysAlias(IHqlExpression * expr)
{
if (queryBodyExtra(expr)->createAlias)
return true;
switch (expr->getOperator())
{
case no_alias:
case no_getresult: // these are commoned up in the code generator, so don't do it twice.
case no_getgraphresult:
case no_getgraphloopresult:
return true;
}
return false;
}
bool TableInvariantTransformer::isTrivialAlias(IHqlExpression * expr)
{
switch (expr->getOperator())
{
case no_cast:
case no_implicitcast:
//Don't create aliases for items that are simply integral casts of other aliases.
{
ITypeInfo * type = expr->queryType();
if (type->isInteger())
{
IHqlExpression * cast = expr->queryChild(0);
ITypeInfo * castType = cast->queryType();
if (castType->isInteger() && isAlwaysAlias(cast))
{
switch (type->getSize())
{
case 1: case 2: case 4: case 8:
return true;
}
}
}
break;
}
case no_not:
{
IHqlExpression * child = expr->queryChild(0);
if (isAlwaysAlias(child))
return true;
break;
}
}
return false;
}
IHqlExpression * TableInvariantTransformer::createTransformed(IHqlExpression * expr)
{
if (expr->getOperator() == no_alias)
{
OwnedHqlExpr newChild = transform(expr->queryChild(0));
if (newChild->getOperator() == no_alias)
return newChild.getClear();
}
OwnedHqlExpr transformed = NewHqlTransformer::createTransformed(expr);
if (queryBodyExtra(expr)->createAlias)
{
if (!isTrivialAlias(expr))
{
OwnedHqlExpr attr = createAttribute(globalAtom);
if (transformed->getOperator() == no_alias)
transformed.set(transformed->queryChild(0));
return createAlias(transformed->queryBody(), attr);
}
}
return transformed.getClear();
}
//---------------------------------------------------------------------------
IHqlExpression * spotTableInvariant(IHqlExpression * expr)
{
TableInvariantTransformer transformer;
transformer.analyse(expr, 0);
return transformer.transformRoot(expr);
}
IHqlExpression * spotTableInvariantChildren(IHqlExpression * expr)
{
TableInvariantTransformer transformer;
ForEachChild(i1, expr)
transformer.analyse(expr->queryChild(i1), 0);
return transformer.transformRoot(expr);
}
//---------------------------------------------------------------------------
static HqlTransformerInfo globalAliasTransformerInfo("GlobalAliasTransformer");
GlobalAliasTransformer::GlobalAliasTransformer() : NewHqlTransformer(globalAliasTransformerInfo)
{
insideGlobal = false;
}
void GlobalAliasTransformer::analyseExpr(IHqlExpression * expr)
{
if (!containsAlias(expr))
return;
bool wasInsideGlobal = insideGlobal;
GlobalAliasInfo * extra = queryBodyExtra(expr);
extra->numUses++;
if (expr->getOperator() == no_alias)
{
if (expr->hasAttribute(globalAtom))
{
// assertex(!containsActiveDataset(expr) || isInlineTrivialDataset(expr));
if (!insideGlobal)
extra->isOuter = true;
}
if (extra->numUses > 1)
return;
if (extra->isOuter)
insideGlobal = true;
}
else
{
//ugly, but we need to walk children more than once even if we've already been here.
//What is important is if visited >1 or occur globally, so can short circuit based on that condition.
//This currently links too many times because subsequent cse generation may common up multiple uses of the same item
//but it's not too bad.
//We could rerun this again if that was a major issue.
if (insideGlobal)
{
if (extra->numUses > 2)
return; // may need to visit children more than once so that alias is linked twice.
}
else
{
if (extra->isOuter && (extra->numUses > 2))
return;
extra->isOuter = true;
}
}
if (expr->getOperator() == no_attr_expr)
analyseChildren(expr);
else
NewHqlTransformer::analyseExpr(expr);
insideGlobal = wasInsideGlobal;
}
IHqlExpression * GlobalAliasTransformer::createTransformed(IHqlExpression * expr)
{
OwnedHqlExpr transformed = NewHqlTransformer::createTransformed(expr);
if ((expr->getOperator() == no_alias))
{
GlobalAliasInfo * extra = queryBodyExtra(expr);
if (expr->hasAttribute(globalAtom))
{
if (!extra->isOuter)
{
if (extra->numUses == 1)
return LINK(transformed->queryChild(0));
if (!expr->hasAttribute(localAtom))
return appendLocalAttribute(transformed);
}
else if (expr->hasAttribute(localAtom))
{
//Should never occur - but just about conceivable that some kind of constant folding
//might cause a surrounding global alias to be removed.
return removeLocalAttribute(transformed);
}
}
else
{
if ((extra->numUses == 1) && !expr->hasAttribute(internalAtom))
return LINK(transformed->queryChild(0));
}
}
return transformed.getClear();
}
//---------------------------------------------------------------------------
IHqlExpression * optimizeActivityAliasReferences(IHqlExpression * expr)
{
if (!containsAlias(expr))
return LINK(expr);
unsigned first = getFirstActivityArgument(expr);
unsigned last = first + getNumActivityArguments(expr);
bool foundAlias = false;
ForEachChild(i1, expr)
{
IHqlExpression * cur = expr->queryChild(i1);
if (((i1 < first) || (i1 >= last)) && containsAlias(cur))
{
foundAlias = true;
break;
}
}
if (!foundAlias)
return LINK(expr);
GlobalAliasTransformer transformer;
ForEachChild(i2, expr)
{
IHqlExpression * cur = expr->queryChild(i2);
if (((i2 < first) || (i2 >= last)) && containsAlias(cur))
transformer.analyse(cur, 0);
}
HqlExprArray args;
ForEachChild(i3, expr)
{
IHqlExpression * cur = expr->queryChild(i3);
if ((i3 < first) || (i3 >= last))
args.append(*transformer.transformRoot(cur));
else
args.append(*LINK(cur));
}
return cloneOrLink(expr, args);
}
|
f95dbe0feafe79fbd4a642c48dbd81a51b8ace7d | 3eb188167143d0f45f56328cf9177405d0e1adb9 | /src/Player.cpp | a88cdbd2a04622d9e4dcf61d710bc0d8a76e69ca | [] | no_license | iarwain/ld49 | 5e2b2be35e47d25f67c9f6c027bfc0b7155fe8cd | 3a52f4a5b3e06176889f2c319f2918aae5541742 | refs/heads/master | 2023-08-31T13:41:38.714863 | 2021-10-05T05:32:34 | 2021-10-05T05:32:34 | 412,701,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,300 | cpp | Player.cpp | /**
* @file Player.cpp
* @date 2-Oct-2021
*/
#include "Player.h"
#include "Arena.h"
void orxFASTCALL Attract(const orxCLOCK_INFO *_pstClockInfo, void *_pContext)
{
Player *poPlayer = (Player *)_pContext;
if(!poPlayer->bDead)
{
poPlayer->PushConfigSection();
const orxSTRING zSet = orxInput_GetCurrentSet();
orxInput_SelectSet(orxConfig_GetString("Input"));
orxFLOAT fDelay = orxConfig_GetFloat("AttractDelay");
if(orxMath_GetRandomFloat(orxFLOAT_0, orxFLOAT_1) <= orxConfig_GetFloat("AttackChance"))
{
orxInput_SetValue(orxConfig_GetString("AttackList"), orxFLOAT_1);
fDelay += orxConfig_GetFloat("AttackDelay");
}
else
{
orxInput_SetValue(orxConfig_GetString("MoveList"), orxFLOAT_1);
}
orxClock_AddGlobalTimer(Attract, fDelay, 1, _pContext);
orxInput_SelectSet(zSet);
poPlayer->PopConfigSection();
}
}
void Player::Die()
{
if(!bDead)
{
Object::Die();
bDead = orxTRUE;
fEnergy = fMaxEnergy;
IncreaseEnergy();
SetAnim("Die");
orxCOLOR stColor;
GetColor(stColor);
stColor.fAlpha *= 0.75f;
SetColor(stColor);
}
}
void Player::IncreaseEnergy()
{
if(!bDead)
{
PushConfigSection();
if(orxConfig_GetBool("IsUnstable"))
{
fEnergy = orxMIN(orxFLOAT_0, fEnergy + fEnergyRate);
}
else
{
fEnergy = orxMIN(fMaxEnergy, fEnergy + fEnergyRate);
}
PopConfigSection();
}
}
void Player::OnCreate()
{
ld49 &roGame = ld49::GetInstance();
// Init variables
Object::OnCreate();
orxConfig_SetBool("IsPlayer", orxTRUE);
s32X = -1;
s32Y = -1;
u32ID = orxU32_UNDEFINED;
bIsAttract = orxConfig_GetBool("IsAttract");
fEnergy = fMaxEnergy = orxConfig_GetFloat("Energy");
fEnergyRate = orxConfig_GetFloat("EnergyRate");
IncreaseEnergy();
// Register with arena
Arena *poArena = roGame.GetObject<Arena>(orxConfig_GetU64("Arena"));
if(poArena)
{
orxVECTOR vPos;
orxConfig_GetVector("InitPos", &vPos);
u32ID = poArena->RegisterPlayer(*this, orxF2S(vPos.fX), orxF2S(vPos.fY));
u64ArenaID = poArena->GetGUID();
if(bIsAttract)
{
orxClock_AddGlobalTimer(Attract, orxConfig_GetFloat("AttractDelay"), 1, this);
}
}
else
{
SetLifeTime(orxFLOAT_0);
}
}
void Player::OnDelete()
{
// Remove attract mode
orxClock_RemoveGlobalTimer(Attract, -orxFLOAT_1, this);
}
void Player::Update(const orxCLOCK_INFO &_rstInfo)
{
if(!bDead)
{
ld49 &roGame = ld49::GetInstance();
Arena *poArena = roGame.GetObject<Arena>(u64ArenaID);
if(poArena && !poArena->bIsGameOver)
{
// Push config section
PushConfigSection();
// Select input set
const orxSTRING zSet = orxInput_GetCurrentSet();
orxInput_SelectSet(orxConfig_GetString("Input"));
// Move
orxVECTOR vMove =
{
(orxInput_HasBeenActivated("MoveRight") ? orxFLOAT_1 : orxFLOAT_0) - (orxInput_HasBeenActivated("MoveLeft") ? orxFLOAT_1 : orxFLOAT_0),
(orxInput_HasBeenActivated("MoveDown") ? orxFLOAT_1 : orxFLOAT_0) - (orxInput_HasBeenActivated("MoveUp") ? orxFLOAT_1 : orxFLOAT_0), orxFLOAT_0
};
if(!orxVector_IsNull(&vMove))
{
poArena->MovePlayer(u32ID, s32X + orxF2S(vMove.fX), s32Y + orxF2S(vMove.fY));
}
// Attack
orxVECTOR vDirection;
orxFLOAT fAttack = (((fEnergy < orxFLOAT_1) && (fEnergy >= -fMaxEnergy + orxFLOAT_1))
&& (orxInput_HasBeenActivated("AttackLeft") || orxInput_HasBeenActivated("AttackRight") || orxInput_HasBeenActivated("AttackUp") || orxInput_HasBeenActivated("AttackDown")))
? orxMath_GetRandomFloat(orxFLOAT_0, orxFLOAT_1)
: 2.0f;
orxBOOL bTargeted = orxFALSE;
orxS32 s32BulletX= s32X, s32BulletY = s32Y, s32Distance = 1;
if(fAttack <= orxFLOAT_1)
{
Player *poPlayer = poArena->GetPlayer();
if(poPlayer == this)
{
poPlayer = poArena->GetPlayer();
}
if(poPlayer != this)
{
s32Distance = orxMath_GetRandomS32(2, 3);
bTargeted = orxTRUE;
fAttack = 2.0f;
}
s32BulletX = poPlayer->s32X;
s32BulletY = poPlayer->s32Y;
}
if((((fEnergy >= orxFLOAT_1) || bTargeted) && orxInput_HasBeenActivated("AttackLeft")) || (fAttack <= 0.25f))
{
poArena->ShootBullet(u32ID, s32BulletX - s32Distance, s32BulletY - s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 3, &vDirection));
poArena->ShootBullet(u32ID, s32BulletX - s32Distance, s32BulletY, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 4, &vDirection));
poArena->ShootBullet(u32ID, s32BulletX - s32Distance, s32BulletY + s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 5, &vDirection));
fEnergy -= orxFLOAT_1;
}
else if((((fEnergy >= orxFLOAT_1) || bTargeted) && orxInput_HasBeenActivated("AttackRight")) || (fAttack <= 0.5f))
{
poArena->ShootBullet(u32ID, s32BulletX + s32Distance, s32BulletY - s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 1, &vDirection));
poArena->ShootBullet(u32ID, s32BulletX + s32Distance, s32BulletY, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 0, &vDirection));
poArena->ShootBullet(u32ID, s32BulletX + s32Distance, s32BulletY + s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 7, &vDirection));
fEnergy -= orxFLOAT_1;
}
else if((((fEnergy >= orxFLOAT_1) || bTargeted) && orxInput_HasBeenActivated("AttackUp")) || (fAttack <= 0.75f))
{
poArena->ShootBullet(u32ID, s32BulletX - s32Distance, s32BulletY - s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 3, &vDirection));
poArena->ShootBullet(u32ID, s32BulletX, s32BulletY - s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 2, &vDirection));
poArena->ShootBullet(u32ID, s32BulletX + s32Distance, s32BulletY - s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 1, &vDirection));
fEnergy -= orxFLOAT_1;
}
else if((((fEnergy >= orxFLOAT_1) || bTargeted) && orxInput_HasBeenActivated("AttackDown")) || (fAttack <= 1.0f))
{
poArena->ShootBullet(u32ID, s32BulletX - s32Distance, s32BulletY + s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 5, &vDirection));
poArena->ShootBullet(u32ID, s32BulletX, s32BulletY + s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 6, &vDirection));
poArena->ShootBullet(u32ID, s32BulletX + s32Distance, s32BulletY + s32Distance, (fEnergy < orxFLOAT_1) ? *orxConfig_GetVector("Direction", &vDirection) : *orxConfig_GetListVector("Direction", 7, &vDirection));
fEnergy -= orxFLOAT_1;
}
// Set anim (energy indicator)
if(fEnergy == fMaxEnergy)
{
SetAnim("100%");
}
else if(fEnergy >= 0.5f * fMaxEnergy)
{
SetAnim("75%");
}
else if (fEnergy >= orxFLOAT_0)
{
SetAnim("50%");
}
else if (fEnergy >= -0.5f * fMaxEnergy)
{
SetAnim("25%");
}
else
{
SetAnim("0%");
}
// Update status
bUnstable = (fEnergy < orxFLOAT_1) ? orxTRUE : orxFALSE;
// Deselect input set
orxInput_SelectSet(zSet);
// Pop config section
PopConfigSection();
}
}
}
|
1dfe20448832d26991f725ffa01526c6bb27498e | 16aadfb24be9bf2b5795bc2e02cadb9d0fe709b3 | /utility/stale/runtime/PriorityScheduler.cc | 7ae2707cb199b3f162d34b7a4c59f8220792bdbf | [] | no_license | dhu/conger | 7c44a9747db6deaa25c6819c7aad4a9f9fbfa995 | b8268ef672c6d232c3d3466efc723534f77d79e1 | refs/heads/master | 2021-01-16T21:01:00.088263 | 2014-02-16T10:05:30 | 2014-02-16T10:05:30 | 2,466,404 | 1 | 0 | null | 2014-02-16T10:05:30 | 2011-09-27T08:35:51 | C++ | UTF-8 | C++ | false | false | 17,735 | cc | PriorityScheduler.cc | #include "PriorityScheduler.h"
#include "AuroraNode.h"
#include "QBox.h"
#include "LockHolder.h"
#include <fstream>
BOREALIS_NAMESPACE_BEGIN
AURORA_DEFINE_SCHEDULER(PriorityScheduler);
PriorityScheduler::PriorityScheduler() :
Scheduler(true, true),
_die(false),
_draining(false)
{
}
void PriorityScheduler::start()
{
setup_listeners();
INFO << "Launching priority-scheduler with " << node().repr();
// Start the work thread
pthread_create(&_ps_thread, 0, &PriorityScheduler::launch, this);
INFO << "Started priority-scheduler";
}
////////////////////////////////////////////////////////////////////////////////
//
void PriorityScheduler::setup_listeners()
{
CatalogStream *input;
set<ptr<QBox> >::const_iterator i;
//..............................................................................
// Set up listeners
set<ptr<QBox> > boxes = node().get_boxes();
for ( i = boxes.begin(); i != boxes.end(); ++i)
{
QBox *box = i->get();
if ( !_setup_boxes.insert( box ).second ) // IF already setup
{ continue;
}
// Set up box data
ptr<MyBoxData> box_data( new MyBoxData(*box) );
set_box_data(*box, box_data);
INFO << "Box " << box->get_name()
<< " has priority " << box_data->_priority
<< " and weight " << box_data->_weight;
for ( uint32 j = 0; j < box->get_num_inputs(); ++j )
{
DEBUG << "Adding listener to " << box->get_name() << " #" << j;
TupleQueue *q = box->get_input_queue( j );
input = box->get_input( j ).get_local_stream();
DEBUG << " - its input stream is " << input->get_stream_name();
if ( !input->is_input_stream() )
{
DEBUG << " - which is from box "
<< input->get_stream_source()->get_port_box()->get_box_name();
ptr<MyBoxTupleQueueListener> tql( new MyBoxTupleQueueListener );
tql->_ps = this;
tql->set_box(box);
_tqlisteners.push_back(tql);
q->add_listener(tql.get());
}
else
{
DEBUG << " - which is an input stream";
ptr<MyInputTupleQueueListener> tql( new MyInputTupleQueueListener );
tql->_ps = this;
tql->set_box(box);
_tqlisteners.push_back(tql);
q->add_listener(tql.get());
}
}
}
}
void PriorityScheduler::init_sched_stats( int window_size, int history_size )
{
/*for (set<ptr<QBox> >::const_iterator i = node().getBoxes().begin();
i != node().getBoxes().end(); ++i)
{
string box_name = i->get()->getName();
_sched_stats._box_costs[ box_name ] = deque<double>( historySize );
}*/
//_sched_stats._selectivities = 1;
//_sched_stats._box_costs = 0;
//_sched_stats._avg_queue_length = 0;
}
void PriorityScheduler::shutdown()
{
if (_ps_thread)
{
INFO << "Terminating scheduler thread...";
{
_die = true;
LockHolder hold(_ps_lock);
_ps_condition.signal();
}
pthread_join(_ps_thread, 0);
INFO << "Scheduler thread has terminated. Hasta la vista, baby.";
}
}
PriorityScheduler::MyBoxData::MyBoxData(QBox& box) :
_box(&box), _priority(0), _weight(100), _scheduled(false), _in_pending(false), _running_time(0)
{
try
{ box.typed_param("qos:priority", _priority);
}
catch (AuroraBadEntityException& e)
{ WARN << e;
}
try
{ box.typed_param("qos:weight", _weight);
}
catch (AuroraBadEntityException& e)
{ WARN << e;
}
}
void PriorityScheduler::schedule_box(MyBoxData& box)
{
if (box._scheduled)
{
DEBUG << "Not scheduling box " << box._box->get_name() << " (already scheduled)";
return;
}
DEBUG << "Scheduling box " << box._box->get_name();
PriorityLevel& pri = _schedules[box._priority];
if (!pri._scheduled)
{
DEBUG << " - adding priority " << box._priority << " to list of running priority levels";
_priorities_to_run.push(box._priority);
pri._scheduled = true;
}
pri._boxes_next.push_back(&box);
box._scheduled = true;
}
void PriorityScheduler::schedule_pending()
{
for (vector<MyBoxData*>::iterator i = _ext_boxes_to_run.begin();
i != _ext_boxes_to_run.end();
++i)
{
(*i)->_in_pending = false;
schedule_box(**i);
}
_ext_boxes_to_run.clear();
}
void PriorityScheduler::run()
{
// Never run a box for less than MIN_SLICE_MSEC ms
static const int MIN_SLICE_MSEC = 5;
// Never run a box for more than MAX_SLICE_MSEC ms
static const int MAX_SLICE_MSEC = 100;
// Run each box at least every CYCLE_MSEC ms
static const int CYCLE_MSEC = 500;
NOTICE << "Priority Scheduler running";
QBoxInvocation inv;
vector<QBox*> boxes_to_run;
Tasks tasks;
while (1)
{
tasks.clear();
boxes_to_run.clear();
{
LockHolder hold(_ps_lock);
ASSERT(check_rep());
while (_priorities_to_run.empty() && _ext_boxes_to_run.empty() && _tasks.empty() && !_die)
{
if (_draining)
{
INFO << "Network is drained; exiting";
_die = true;
break;
}
DEBUG << "Nothing to do - scheduler is napping";
if (_event_handler)
_event_handler->handle_idle_time();
_ps_lock.wait_cond(_ps_condition);
}
if (_die)
{
// Still have to run any outstanding tasks
DEBUG << "Scheduler: that's all folks";
for (Tasks::iterator i = _tasks.begin(); i != _tasks.end(); ++i)
{
DEBUG << "Running a task before dying";
(*i)->run();
}
return;
}
// save tasks to run
tasks.swap(_tasks);
// merge in pending tasks
schedule_pending();
ASSERT(check_rep());
// release lock
}
// run tasks
for (Tasks::iterator i = tasks.begin(); i != tasks.end(); ++i)
{
DEBUG << "Running a task " << typeid(**i);
(*i)->run();
DEBUG << "Done running task " << typeid(**i);
}
if (_priorities_to_run.empty())
continue;
int priority_to_run = _priorities_to_run.top();
PriorityLevel& level = _schedules[priority_to_run];
if (level._boxes_to_run.empty())
{
DEBUG << "Setting up priority level " << priority_to_run << " ("
<< level._boxes_next.size() << " boxes)";
level._boxes_next.swap(level._boxes_to_run);
int total_weights = 0;
for (vector<MyBoxData*>::const_iterator i = level._boxes_to_run.begin();
i != level._boxes_to_run.end();
++i)
{
total_weights += (*i)->_weight;
}
DEBUG << " - total weights: " << total_weights;
for (vector<MyBoxData*>::iterator i = level._boxes_to_run.begin();
i != level._boxes_to_run.end();
++i)
{
(*i)->_running_time = max(MIN_SLICE_MSEC, (*i)->_weight * CYCLE_MSEC / total_weights);
DEBUG << " - will run " << (*i)->_box->get_name() << " for " << (*i)->_running_time << " ms";
}
} else
{
DEBUG << "Resuming priority level " << priority_to_run << " ("
<< level._boxes_to_run.size() << " left)";
}
while (1)
{
ASSERT(priority_to_run == _priorities_to_run.top());
if (level._boxes_to_run.empty())
{
DEBUG << "Done running stuff in level " << priority_to_run;
if (level._boxes_next.empty())
{
DEBUG << " - nothing scheduled in the future either; unscheduling this level";
level._scheduled = false;
_priorities_to_run.pop();
}
break;
}
MyBoxData* d = level._boxes_to_run.back();
level._boxes_to_run.front();
QBoxInvocation inv;
int running_time_now = min(MAX_SLICE_MSEC, d->_running_time);
INFO << "Running box " << d->_box->get_name() << " for " << running_time_now << " ms ("
<< d->_running_time << " ms left this cycle)";
d->_running_time -= running_time_now;
inv._end_time = Scheduler::ticks() + running_time_now * 1000 / Scheduler::ticks_per_second();
d->_box->run(inv);
// TODO: charge box for amount of time actually run
bool box_done = true;
unsigned int num_inputs = d->_box->get_num_inputs();
for (unsigned int j = 0; box_done && j < num_inputs; ++j)
if (d->_box->get_input_queue(j)->size())
{
DEBUG << " - input " << j << " not done; will run again";
box_done = false;
}
if (box_done)
{
DEBUG << " - all done";
d->_scheduled = false;
ASSERT(level._boxes_to_run.back() == d);
level._boxes_to_run.pop_back();
} else if (d->_running_time)
{
DEBUG << " - need to run it again; will do so right now";
} else
{
DEBUG << " - need to run it again; will do so next cycle";
ASSERT(level._boxes_to_run.back() == d);
level._boxes_to_run.pop_back();
level._boxes_next.push_back(d);
}
// need to schedule any pending boxes in case anything
// higher-priority came up
{
LockHolder hold(_ps_lock);
schedule_pending();
}
if (priority_to_run != _priorities_to_run.top())
{
DEBUG << "Preempted by level " << _priorities_to_run.top() << "!";
// something higher-priority came up!
break;
}
}
}
}
/*
void PriorityScheduler::addBoxes( )
{
// is this it? add boxes needs no paramters, assumed that catalog has been updated already.
topologyChanged();
}
*/
void PriorityScheduler::invalidate_boxes( vector<string> boxNames )
{}
void PriorityScheduler::update_listeners( vector<string> boxNames, bool add )
{}
/*
Removes a set of boxes from the running network
*/
/*
void PriorityScheduler::removeBoxes( vector<string> boxNames )
{
// check if dynamic removal/addition is supported?
// this has to change, but for now lock the operation for box movement.
// problem is, box could be either currently exucution or be in a similar precarious state.
{
LockHolder hold(_ps_lock);
//bool box_exists = false;
for(vector<string>::iterator i = boxNames.begin(); i != boxNames.end(); i++)
{
string box = (*i);
DEBUG << "Removing box " << box;
box_exists = false;
for ( vector<string>::iterator iter = _disabled_boxes.begin();
iter != _disabled_boxes.end(); iter++ )
{
if ( (*iter) == box )
{
cerr << "WARNING: disabling an already disabled box " << box;
box_exists = true;
}
if ( !box_exists )
_disabled_boxes.push_back( box );
}
// check the currently scheduled boxes and remove as well
// don't see a convinient way to lookup box by name. Need to write it or to find it.
PriorityLevel& pri = _schedules[ 0 ];
for (vector<MyBoxData*>::iterator it = pri._boxes_next.begin(); it != pri._boxes_next.end(); it ++ )
if ( (*it)->_box->getName() == box )
{
pri._boxes_next.erase( it );
break;
}
for (vector<MyBoxData*>::iterator it = pri._boxes_to_run.begin(); it != pri._boxes_to_run.end(); it ++ )
if ( (*it)->_box->getName() == box )
{
pri._boxes_to_run.erase( it );
break;
}
// check all listeners, which may have pointers to our box.
for (TQListeners::iterator i = _tqlisteners.begin(); i != _tqlisteners.end(); )
{
if ( (*i)->getBox() )
{
QBox* b = (*i)->getBox();
if ( b->getName() == box)
{
for (unsigned int j = 0; j < b->getNumInputs(); ++j)
{
TupleQueue *q = b->getInputQueue(j);
q->removeListener((*i).get());
}
i = _tqlisteners.erase(i);
} else { i++; }
} else { i++; }
}
}
}
}
void PriorityScheduler::activateBoxes()
{
// for now just call topology changed (and clear the disabled boxes)
//_disabled_boxes.clear();
topologyChanged();
}
*/
void PriorityScheduler::drain()
{
_draining = true;
ASSERT(_ps_thread);
INFO << "Scheduler draining...";
{
LockHolder hold(_ps_lock);
_ps_condition.signal();
}
pthread_join(_ps_thread, 0);
_ps_thread = 0;
}
void PriorityScheduler::topology_changed()
{
INFO << "Topology changed";
setup_listeners();
}
void PriorityScheduler::MyBoxTupleQueueListener::notify(const TupleQueue&)
{
// DEBUG << "Notifying scheduler (from scheduler thread) that it has to run " << _box_to_run->getName();
_ps->schedule_box(_ps->get_my_box_data(*_box_to_run));
}
void PriorityScheduler::MyInputTupleQueueListener::notify(const TupleQueue&)
{
// DEBUG << "Notifying scheduler (from input) that it has to run " << _box_to_run->getName();
LockHolder hold(_ps->_ps_lock);
MyBoxData& box = _ps->get_my_box_data(*_box_to_run);
if (!box._scheduled && !box._in_pending)
{
box._in_pending = true;
_ps->_ext_boxes_to_run.push_back(&_ps->get_my_box_data(*_box_to_run));
_ps->_ps_condition.signal();
}
}
void PriorityScheduler::schedule_exclusive_task(ptr<SchedulerTask> task)
{
LockHolder hold(_ps_lock);
_tasks.push_back(task);
DEBUG << "Scheduled " << typeid(*task);
_ps_condition.signal();
}
bool PriorityScheduler::check_rep() const
{
// Make sure that each priority occurs only once,
// and that level._scheduled <=> level in _priorities_to_run
priorities_to_run prirun_copy(_priorities_to_run);
set<int> prirun_set;
while (!prirun_copy.empty())
{
int pri = prirun_copy.top();
if (!prirun_set.insert(pri).second)
WARN << "checkRep: Multiple copies of priority " << pri << " in _priorities_to_run";
if (_schedules.find(pri) == _schedules.end())
WARN << "checkRep: Unknown priority " << pri << " in _priorities_to_run";
prirun_copy.pop();
}
for (map<int, PriorityLevel>::const_iterator i = _schedules.begin(); i != _schedules.end(); ++i)
{
bool in_set = prirun_set.count(i->first);
if (i->second._scheduled != in_set)
WARN << "checkRep: Level " << i->first << ": _scheduled="
<< i->second._scheduled << "; in _priorities_to_run is " << in_set;
}
// Check box data stuff
set<MyBoxData*> pending_set;
for (vector<MyBoxData*>::const_iterator i = _ext_boxes_to_run.begin(); i != _ext_boxes_to_run.end(); ++i)
if (!pending_set.insert(*i).second)
WARN << "checkRep: Multiple copies of " << (*i)->_box->get_name() << " in _ext_boxes_to_run";
for (set<QBox*>::const_iterator i = _setup_boxes.begin(); i != _setup_boxes.end(); ++i)
{
MyBoxData& d = get_my_box_data(**i);
bool in_pending = pending_set.count(&d);
if (d._in_pending != in_pending)
WARN << "checkRep: Box " << d._box->get_name() << ": _in_pending="
<< d._in_pending << "; in _ext_boxes_to_run is " << in_pending;
map<int, PriorityLevel>::const_iterator j = _schedules.find(d._priority);
if (j == _schedules.end())
{
if (d._scheduled)
{
WARN << "checkRep: Box " << d._box->get_name() << ": scheduled but no priority level "
<< d._priority;
}
continue;
}
const PriorityLevel& l = j->second;
int boxes_next_count = count(l._boxes_next.begin(), l._boxes_next.end(), &d);
int boxes_to_run_count = count(l._boxes_to_run.begin(), l._boxes_to_run.end(), &d);
int correct_count = d._scheduled ? 1 : 0;
if (boxes_next_count + boxes_to_run_count != correct_count)
{
WARN << "checkRep: Box " << d._box->get_name() << ": "
<< (d._scheduled ? "scheduled" : "unscheduled")
<< " box box appears in _boxes_next "
<< boxes_next_count << " times and _boxes_to_run_count " << boxes_to_run_count << " times"
<< " (should be " << correct_count << " total)";
}
}
return true;
// Could return false if something catastrophic happened
}
string PriorityScheduler::to_string()
{
return "STRING2";
}
BOREALIS_NAMESPACE_END
|
b05fdc611052b9a3c49abc6974a8f21aa8ff9052 | 2727f231c7700ea16a4dc0724dc370210461bdd7 | /c++core/009_Circle.cpp | 8363578e4a46d677e9ef0db157a4a4967c1b2480 | [] | no_license | qinlei1992/CppLearning | a1fb15cab2735d79a54ba0d56332edcb0143d76e | 18812cb55098c8f78c82ac87e7229fbc7df27be5 | refs/heads/main | 2023-04-16T19:43:11.306209 | 2021-04-27T08:24:29 | 2021-04-27T08:24:29 | 357,489,974 | 0 | 0 | null | 2021-04-21T04:17:03 | 2021-04-13T09:05:37 | C++ | UTF-8 | C++ | false | false | 272 | cpp | 009_Circle.cpp | #include "009_Point.h"
#include "009_Circle.h"
void Circle::set_radius(double radius){
this->radius = radius;
}
double Circle::get_radius(){
return radius;
}
void Circle::set_center(Point p){
center = p;
}
Point Circle::get_center(){
return center;
}
|
ad9393c6b06ea82b327660a5ad087b729f70d6a5 | 157fd7fe5e541c8ef7559b212078eb7a6dbf51c6 | /TRiAS/TRiAS/Obsolete/DBase/CodeBase DLL/D4XGOEOF.CXX | 83e1d115ac028e15decfadacfc32c7bdc697a62e | [] | no_license | 15831944/TRiAS | d2bab6fd129a86fc2f06f2103d8bcd08237c49af | 840946b85dcefb34efc219446240e21f51d2c60d | refs/heads/master | 2020-09-05T05:56:39.624150 | 2012-11-11T02:24:49 | 2012-11-11T02:24:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cxx | D4XGOEOF.CXX | // d4xgoeof.c (c)Copyright Sequiter Software Inc., 1990-1991. All rights reserved.
#include "d4all.h"
int DataIndex::go_eof()
{
int rc ;
if ( (rc = flush_record()) != 0 ) return rc ;
long count = reccount() ; if ( count < 0 ) return -1 ;
rec_num = count+1L ;
eof_flag = 1 ;
if ( rec_num == 1 ) bof_flag = 1 ;
record.set( ' ' ) ;
return r4eof ;
}
|
a5b3540aaa55d0916dd6ffadcd65a158e6faa043 | 4bd300d451a4dc2f1df37243fcd3047b5564a914 | /02 数据类型/06 布尔类型 bool.cpp | d2344cd481967eaa42c5f72392a624aaa2ba2f0b | [
"MIT"
] | permissive | AlicePolk/cpp- | 24c865ca70a11a931c42192db4ebdb4924cf72e8 | 5bc3b1ea7fde780d0c45632fad083d583d65fb66 | refs/heads/master | 2022-12-14T16:39:02.316754 | 2020-09-12T01:46:51 | 2020-09-12T01:46:51 | 224,430,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | cpp | 06 布尔类型 bool.cpp | //#include<iostream>
//using namespace std;
//
//
//int main() {
//
// bool flag = true;
// cout << flag << endl; // 1
//
// flag = false;
// cout << flag << endl; // 0
//
// cout << "size of bool = " << sizeof(bool) << endl; //1
//
// system("pause");
//
// return 0;
//} |
e71980d5c93fee00a8b200db9520148153bd41b2 | 4d0300263d28fb461f285cc2c3dfd7c51621cb4d | /platform/windows/Corona.Native.Library.Win32/Rtt/Rtt_WinAudioRecorder.cpp | 89a497b804be9294469857097e1fe4610e5cde82 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown"
] | permissive | coronalabs/corona | 6a108e8bfc8026e8c85e6768cdd8590b5a83bdc2 | 5e853b590f6857f43f4d1eb98ee2b842f67eef0d | refs/heads/master | 2023-08-30T14:29:19.542726 | 2023-08-22T15:18:29 | 2023-08-22T15:18:29 | 163,527,358 | 2,487 | 326 | MIT | 2023-09-02T16:46:40 | 2018-12-29T17:05:15 | C++ | UTF-8 | C++ | false | false | 14,599 | cpp | Rtt_WinAudioRecorder.cpp | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "WinString.h"
#include "Core/Rtt_Build.h"
#include "Rtt_WinAudioRecorder.h"
#include "Rtt_LuaContext.h"
namespace Rtt
{
#pragma region Constructors and Destructors
/// Creates a new audio recorder.
/// @param file The path and file name to record audio to. Set to NULL to not record to file.
WinAudioRecorder::WinAudioRecorder(const ResourceHandle<lua_State> &handle, Rtt_Allocator &allocator, const char *file)
: PlatformAudioRecorder( handle, allocator, file ),
fFilename(&allocator)
{
fFilename.Set(file);
memset(&fWaveFormatEx, 0x00, sizeof(fWaveFormatEx));
fWaveFormatEx.wFormatTag = WAVE_FORMAT_PCM;
fWaveFormatEx.nChannels = 1;
fWaveFormatEx.wBitsPerSample = 16;
fWaveFormatEx.cbSize = 0;
fWaveFormatEx.nSamplesPerSec = 22050; // default
fFileWriter = NULL;
fRecordingHandle = 0;
fBufferCount = 0;
}
/// Destructor. Stops recording and destroys this object.
WinAudioRecorder::~WinAudioRecorder()
{
Stop();
if (fFileWriter)
{
delete fFileWriter;
}
}
#pragma endregion
#pragma region Callbacks
/// C function called on another thread by the WaveIn functions.
/// @param dwInstance Provides a pointer to the WinAudioRecord object that handles audio recording.
void CALLBACK OnCallbackBlock(HWAVEIN hwl, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
WinAudioRecorder *pCallback = (WinAudioRecorder*)dwInstance;
if (pCallback)
{
pCallback->OnSoundBlock(hwl, uMsg, dwInstance, dwParam1, dwParam2);
}
}
#pragma endregion
#pragma region Public Audio Functions
/// Starts recording audio.
void WinAudioRecorder::Start()
{
WAVEINCAPS deviceInfo;
MMRESULT mmReturn;
bool canRecord;
// Do not continue if already recording.
if (fIsRunning)
{
return;
}
// Allocate a CWriteSoundFile object on first use.
if ((NULL == fFileWriter) && fFilename.GetString())
{
fFileWriter = new CWriteSoundFile();
}
// Fetch the audio recording device's capabilities.
mmReturn = ::waveInGetDevCaps(WAVE_MAPPER, &deviceInfo, sizeof(deviceInfo));
if (mmReturn)
{
LogWaveInError(mmReturn);
return;
}
// Update recorder configuration "fWaveFormatEx" to something the current device supports.
// If the device does not support the current configuration, then this function will
// downgrade the audio quality to something the device does support.
canRecord = UpdateFormatSettingsAccordingTo(&deviceInfo);
if (!canRecord)
{
Rtt_LogException( "Unable to find a recording format that the current device supports.\n" );
return;
}
// Open a connection to the audio recording device.
mmReturn = ::waveInOpen(
&fRecordingHandle, WAVE_MAPPER, &fWaveFormatEx, (DWORD)&OnCallbackBlock,
(DWORD)this, CALLBACK_FUNCTION);
if (mmReturn)
{
LogWaveInError(mmReturn);
return;
}
// Start recording.
AllocateBuffers(MAXINPUTBUFFERS);
mmReturn = ::waveInStart(fRecordingHandle);
if (mmReturn)
{
LogWaveInError(mmReturn);
return;
}
fIsRunning = true;
// Create the audio file to record to if enabled.
if (fFileWriter)
{
WinString convertedFileName;
convertedFileName.SetUTF8(fFilename.GetString());
fFileWriter->CreateWaveFile(convertedFileName.GetTCHAR(), &fWaveFormatEx);
}
}
/// Stops recording audio.
void WinAudioRecorder::Stop()
{
MMRESULT mmReturn = 0;
// Do not continue if already stopped.
if (!fIsRunning)
{
return;
}
// Stop recording.
fIsRunning = false;
mmReturn = ::waveInStop(fRecordingHandle);
mmReturn = ::waveInReset(fRecordingHandle);
// Wait up to 1 second for the other thread to free its allocated buffers.
int endTime = (int)::GetTickCount() + 1000;
while ((fBufferCount > 0) && ((endTime - (int)::GetTickCount()) > 0))
{
::Sleep(10);
}
// Close the connection to the audio recording device.
if (!mmReturn)
{
mmReturn = ::waveInClose(fRecordingHandle);
}
// Close the file being recording to, if enabled.
if (fFileWriter)
{
fFileWriter->CloseSoundFile();
}
}
#pragma endregion
#pragma region Protected Audio Functions
/// Logs an error message for the given result object returned by a Microsoft "waveIn" function.
/// @param mmResult The result object returned by a Microsoft waveIn function.
void WinAudioRecorder::LogWaveInError(MMRESULT mmResult)
{
WinString message;
message.Expand(MAX_PATH);
waveInGetErrorText(mmResult, message.GetBuffer(), MAX_PATH);
Rtt_LogException( "Error while recording:%x:%s\n", mmResult, message.GetUTF8() );
}
/// Updates the audio recorder's configuration "fWaveFormatEx" to something that the given device supports.
/// If not supported, then this function will downgrade the configuration to the next best quality level.
/// @param deviceInfoPointer Pointer to information about an audio input device. Cannot be NULL.
/// This information can be retrieved via the waveInGetDevCaps() function.
/// @return Returns TRUE if the recorder configuration has been updated and is ready to record.
/// Returns FALSE if unable to configure this recorder to something that the given devices
/// supports, in which case this object should not attempt to record anything.
bool WinAudioRecorder::UpdateFormatSettingsAccordingTo(WAVEINCAPS *deviceInfoPointer)
{
// Validate.
if (!deviceInfoPointer)
{
return false;
}
// Find the next best recording format that the given device supports. (Default to mono.)
fWaveFormatEx.nChannels = 1;
for (fWaveFormatEx.wBitsPerSample = 16;
fWaveFormatEx.wBitsPerSample >= 8;
fWaveFormatEx.wBitsPerSample -= 8)
{
fWaveFormatEx.nSamplesPerSec = GetSampleRate();
while (fWaveFormatEx.nSamplesPerSec > 0)
{
// If the device supports the current recording format, then stop here.
if (IsFormatSettingsSupportedBy(deviceInfoPointer))
{
fWaveFormatEx.nAvgBytesPerSec =
fWaveFormatEx.nSamplesPerSec * (fWaveFormatEx.wBitsPerSample / 8);
fWaveFormatEx.nBlockAlign =
(fWaveFormatEx.wBitsPerSample / 8) * fWaveFormatEx.nChannels;
return true;
}
// Downgrade to the next best frequency.
if (fWaveFormatEx.nSamplesPerSec > 44100)
{
fWaveFormatEx.nSamplesPerSec = 44100;
}
else if (fWaveFormatEx.nSamplesPerSec > 22050)
{
fWaveFormatEx.nSamplesPerSec = 22050;
}
else if (fWaveFormatEx.nSamplesPerSec > 11025)
{
fWaveFormatEx.nSamplesPerSec = 11025;
}
else
{
break;
}
}
}
// Failed to find a format that the given device supports.
// Give up and inform the caller to not record audio.
return false;
}
/// Determines if the current audio recorder configuration "fWaveFormatEx" is supported
/// by the given audio input device.
/// @param deviceInfoPointer Information about an audio input device. Cannot be NULL.
/// @return Returns TRUE if the current configuration is supported. Returns FALSE if not.
bool WinAudioRecorder::IsFormatSettingsSupportedBy(WAVEINCAPS *deviceInfoPointer)
{
bool isSupported = false;
// Validate.
if (!deviceInfoPointer)
{
return false;
}
// Determine if the given device supports the current audio recorder configuration.
switch (fWaveFormatEx.nSamplesPerSec)
{
case 11025:
if ((1 == fWaveFormatEx.nChannels) && (8 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_1M08) != 0);
}
else if ((1 == fWaveFormatEx.nChannels) && (16 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_1M16) != 0);
}
if ((2 == fWaveFormatEx.nChannels) && (8 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_1S08) != 0);
}
else if ((2 == fWaveFormatEx.nChannels) && (16 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_1S16) != 0);
}
break;
case 22050:
if ((1 == fWaveFormatEx.nChannels) && (8 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_2M08) != 0);
}
else if ((1 == fWaveFormatEx.nChannels) && (16 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_2M16) != 0);
}
if ((2 == fWaveFormatEx.nChannels) && (8 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_2S08) != 0);
}
else if ((2 == fWaveFormatEx.nChannels) && (16 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_2S16) != 0);
}
break;
case 44100:
if ((1 == fWaveFormatEx.nChannels) && (8 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_4M08) != 0);
}
else if ((1 == fWaveFormatEx.nChannels) && (16 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_4M16) != 0);
}
if ((2 == fWaveFormatEx.nChannels) && (8 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_4S08) != 0);
}
else if ((2 == fWaveFormatEx.nChannels) && (16 == fWaveFormatEx.wBitsPerSample))
{
isSupported = ((deviceInfoPointer->dwFormats & WAVE_FORMAT_4S16) != 0);
}
break;
}
return isSupported;
}
/// Allocates buffer to store audio data from another thread.
/// @param nBuffers The number of buffers to allocate.
void WinAudioRecorder::AllocateBuffers(int nBuffers)
{
int i;
for(i=0; i < nBuffers; i++)
{
LPWAVEHDR lpWaveHdr = CreateWaveHeader();
::waveInPrepareHeader(fRecordingHandle, lpWaveHdr, sizeof(WAVEHDR));
::waveInAddBuffer(fRecordingHandle, lpWaveHdr, sizeof(WAVEHDR));
fBufferCount++;
}
}
/// Creates header data to be applied to an audio buffer. Called by the AllocateBuffers() function.
LPWAVEHDR WinAudioRecorder::CreateWaveHeader()
{
LPWAVEHDR lpWaveHdr = new WAVEHDR;
ZeroMemory(lpWaveHdr, sizeof(WAVEHDR));
BYTE* lpByte = new BYTE[(fWaveFormatEx.nBlockAlign * SOUNDSAMPLES)];
lpWaveHdr->lpData = (char*)lpByte;
lpWaveHdr->dwBufferLength = (fWaveFormatEx.nBlockAlign * SOUNDSAMPLES);
return lpWaveHdr;
}
/// Swaps the bytes in the given buffer.
/// @param buffer The buffer to have its bytes swapped. Cannot be NULL.
/// @param bufferLength The number of bytes in the given buffer. Must be at least 2.
void WinAudioRecorder::SwapBytes(BYTE *buffer, int bufferLength)
{
BYTE value;
int index;
// Validate arguments.
if (!buffer || (bufferLength < 2))
{
return;
}
// If the number of bytes is odd, then ignore the last byte since it can't swap with anything.
if (bufferLength % 2)
{
bufferLength--;
}
// Swap all bytes in the given buffer.
for (index = 0; index < bufferLength; index += 2)
{
value = buffer[index];
buffer[index] = buffer[index + 1];
buffer[index + 1] = value;
}
}
/// To be invoked by the WaveIn function on another thread when a new sound block has been recorded.
/// NOTE: Once waveInReset() has been called, you cannot call waveInUnprepareHeader() on the sound
/// blocks returned. You must be careful what you call in the callback once waveInReset() has
/// been called in the stop function.
/// @param dwInstance Provides a pointer to the WinAudioRecorder object this session belongs to.
/// @param dwParam1 Provides a pointer to audio data that was just recorded.
void WinAudioRecorder::OnSoundBlock(
HWAVEIN hwl,UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
LPWAVEHDR lpWaveHdr = (LPWAVEHDR)dwParam1;
if(lpWaveHdr && uMsg == WIM_DATA)
{
BYTE *lpInt = (BYTE*)lpWaveHdr->lpData;
DWORD iRecorded = lpWaveHdr->dwBytesRecorded;
if (fIsRunning)
{
::waveInUnprepareHeader(fRecordingHandle, lpWaveHdr, sizeof(WAVEHDR));
}
if (fIsRunning && fFileWriter)
{
WAVEHDR* pWriteHdr = new WAVEHDR;
memcpy(pWriteHdr, lpWaveHdr, sizeof(WAVEHDR));
BYTE * pSound = new BYTE[lpWaveHdr->dwBufferLength];
if (!pSound)
{
delete pWriteHdr;
return;
}
memcpy(pSound, lpWaveHdr->lpData ,lpWaveHdr->dwBufferLength);
pWriteHdr->lpData = (char*)pSound;
if (fFileWriter)
{
fFileWriter->WriteToSoundFile(GetCurrentThreadId(), (LPARAM)pWriteHdr);
}
}
delete lpInt;
delete lpWaveHdr;
fBufferCount--;
if (fIsRunning)
{
AllocateBuffers(1);
}
}
}
#pragma endregion
#pragma region CWriteSoundFile
/////////////////////////////////////////////////////////////////////////////
// CWriteSoundFile class
CWriteSoundFile::CWriteSoundFile()
{
m_hFile = 0;
}
CWriteSoundFile::~CWriteSoundFile()
{
CloseSoundFile();
}
// consult Microsoft Knowledge Base Article 551005
// previously known under E10955
// http://www.microsoft.com/intlkb/SPAIN/E10/9/55.ASP
//
bool CWriteSoundFile::CreateWaveFile( const TCHAR *sFilename, WAVEFORMATEX *pWaveFormatEx)
{
int cbWaveFormatEx = sizeof(WAVEFORMATEX) + pWaveFormatEx->cbSize;
m_hFile = ::mmioOpen((LPWSTR)sFilename,NULL, MMIO_CREATE|MMIO_WRITE|MMIO_EXCLUSIVE | MMIO_ALLOCBUF);
if(!m_hFile)
return false;
ZeroMemory(&m_MMCKInfoParent, sizeof(MMCKINFO));
m_MMCKInfoParent.fccType = mmioFOURCC('W','A','V','E');
MMRESULT mmResult = ::mmioCreateChunk( m_hFile,&m_MMCKInfoParent,
MMIO_CREATERIFF);
ZeroMemory(&m_MMCKInfoChild, sizeof(MMCKINFO));
m_MMCKInfoChild.ckid = mmioFOURCC('f','m','t',' ');
m_MMCKInfoChild.cksize = cbWaveFormatEx;
mmResult = ::mmioCreateChunk(m_hFile, &m_MMCKInfoChild, 0);
mmResult = ::mmioWrite(m_hFile, (char*)pWaveFormatEx, cbWaveFormatEx);
mmResult = ::mmioAscend(m_hFile, &m_MMCKInfoChild, 0);
m_MMCKInfoChild.ckid = mmioFOURCC('d', 'a', 't', 'a');
mmResult = ::mmioCreateChunk(m_hFile, &m_MMCKInfoChild, 0);
return true;
}
void CWriteSoundFile::WriteToSoundFile(WPARAM wParam, LPARAM lParam)
{
LPWAVEHDR lpHdr = (LPWAVEHDR) lParam;
int cbLength = lpHdr->dwBufferLength;
if(lpHdr)
{
char *soundbuffer = (char*) lpHdr->lpData;
if(m_hFile && soundbuffer)
::mmioWrite(m_hFile, soundbuffer, cbLength);
if(soundbuffer)
delete (BYTE*) soundbuffer;
if(lpHdr)
delete lpHdr;
}
}
void CWriteSoundFile::CloseSoundFile()
{
if(m_hFile)
{
::mmioAscend(m_hFile, &m_MMCKInfoChild, 0);
::mmioAscend(m_hFile, &m_MMCKInfoParent, 0);
::mmioClose(m_hFile, 0);
m_hFile = NULL;
}
}
#pragma endregion
} // namespace Rtt
|
9755ef516e3c8be2418d45c19c69f3b48aff372f | 6501a0232db2c9fe370fdbbc24746114a6f37ea4 | /d24.cpp | 619405fecc48280db92e1f3b0da8dcfb148d27a5 | [] | no_license | blackkama/joblab | 3b6cee917a5fce9c36bb56b7bd2c996fcf97d0ad | abc1a0caebf12a7807c4dc708c13d3a02d86015a | refs/heads/master | 2020-12-28T23:34:56.083655 | 2016-03-05T08:00:34 | 2016-03-05T08:00:34 | 53,197,995 | 0 | 1 | null | 2016-03-05T11:23:54 | 2016-03-05T11:23:54 | null | WINDOWS-1251 | C++ | false | false | 459 | cpp | d24.cpp | #include <iostream>
#include <climits>
using namespace std;
int main()
{
cout.setf(ios_base::fixed, ios_base::floatfield);
float tub = 10.0 / 3.0;
double mint = 10.0 / 3.0;
const float million = 1.0e6;
cout<<"tub= "<<tub;
cout<<"Миллион= "<<million*tub;
cout<<",\nand ten million tubs = ";
cout<<10*million*tub<<endl;
cout<<"miny = "<<mint<<"и миллион mints =";
cout<<million*mint<<endl;
system("Pause");
return 0;
}
|
911171c7b17cbf9b2ebb42ec9741e8fd9c2d6944 | adba93157daccb869ba22caffb142e633f4a8afc | /src/engine/systems/TweenSystem.h | 574aca30987908cf5c35ba15fcda14eeaa4f1765 | [
"Apache-2.0"
] | permissive | Cosmin-B/Sealed | 333cb80e3eeaddaf16db724c8ef0353db5e697b4 | 637946ccb1c8af2e95033533cb2a84dd3b5e22af | refs/heads/master | 2022-01-07T09:35:16.621365 | 2019-05-18T20:08:29 | 2019-05-18T20:08:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 319 | h | TweenSystem.h | //
// Created by xCocoDev on 2019-03-04.
//
#ifndef SAXION_Y2Q2_RENDERING_TWEENSYSTEM_H
#define SAXION_Y2Q2_RENDERING_TWEENSYSTEM_H
#include "System.h"
namespace en {
class TweenSystem : public System {
public:
void update(float dt) override;
};
}
#endif //SAXION_Y2Q2_RENDERING_TWEENSYSTEM_H
|
56ccc31987005a1589be88499f07e112e5e98f1d | f8372ab7eaae820219f2bb0aed97319c472be9a0 | /fitness.cpp | b5c695bf6986c42b3663c80835c501a679fb2509 | [] | no_license | rafaelsdellama/algGen_Bin | 938aa1686ffde936d915f5a07638a4ff777f4944 | 27ef4c30ed98d034b8112a44129d2e2284358ac1 | refs/heads/master | 2021-08-07T18:15:57.669590 | 2017-11-08T17:23:55 | 2017-11-08T17:23:55 | 110,004,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | cpp | fitness.cpp | /******************************************************************************\
* Fitness: *
\******************************************************************************/
#include "defTipo.h"
#include <cstdlib>
#include <cmath>
/******************************************************************************\
* Calculo Fitness *
\******************************************************************************/
double calcFitness(alelo *indiv, int gen)
{
double Fitness = 0;
for(int i = 0; i < lcrom; i++)
Fitness = Fitness + indiv[i];
return Fitness;
}
|
e130b505dd1d3bd4cd90c0bb1756353f21c131e1 | 0225a1fb4e8bfd022a992a751c9ae60722f9ca0d | /openlr/candidate_points_getter.hpp | 02c16c0b87e20c0cd72c1d4236b395a582cec1e6 | [
"Apache-2.0"
] | permissive | organicmaps/organicmaps | fb2d86ea12abf5aab09cd8b7c55d5d5b98f264a1 | 76016d6ce0be42bfb6ed967868b9bd7d16b79882 | refs/heads/master | 2023-08-16T13:58:16.223655 | 2023-08-15T20:16:15 | 2023-08-15T20:16:15 | 324,829,379 | 6,981 | 782 | Apache-2.0 | 2023-09-14T21:30:12 | 2020-12-27T19:02:26 | C++ | UTF-8 | C++ | false | false | 1,150 | hpp | candidate_points_getter.hpp | #pragma once
#include "openlr/graph.hpp"
#include "openlr/stats.hpp"
#include "indexer/data_source.hpp"
#include "geometry/point2d.hpp"
#include <cstddef>
#include <functional>
#include <vector>
namespace openlr
{
class CandidatePointsGetter
{
public:
CandidatePointsGetter(size_t const maxJunctionCandidates, size_t const maxProjectionCandidates,
DataSource const & dataSource, Graph & graph)
: m_maxJunctionCandidates(maxJunctionCandidates)
, m_maxProjectionCandidates(maxProjectionCandidates)
, m_dataSource(dataSource)
, m_graph(graph)
{
}
void GetCandidatePoints(m2::PointD const & p, std::vector<m2::PointD> & candidates)
{
FillJunctionPointCandidates(p, candidates);
EnrichWithProjectionPoints(p, candidates);
}
private:
void FillJunctionPointCandidates(m2::PointD const & p, std::vector<m2::PointD> & candidates);
void EnrichWithProjectionPoints(m2::PointD const & p, std::vector<m2::PointD> & candidates);
size_t const m_maxJunctionCandidates;
size_t const m_maxProjectionCandidates;
DataSource const & m_dataSource;
Graph & m_graph;
};
} // namespace openlr
|
8fb5a3ee52e7e62067b98a7182c4a184ca069fe1 | c1d20b9b69033e71b113c1f948b7c45e300a2584 | /Lab08/OrderedLinkedList.h | 67db2677da0fec4321509c590fc67bbe2617fdd8 | [] | no_license | snyderks/data-structures | aa31de0f36b7d4eba84c6fb4eb2a17e051df817e | b8713d94405a323b875d219ea3ff090d64fbeee8 | refs/heads/master | 2021-01-24T18:38:32.487906 | 2017-04-10T19:44:22 | 2017-04-10T19:44:22 | 84,462,196 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,306 | h | OrderedLinkedList.h | //
// Created by Kristian Snyder
//
#ifndef LAB08_ORDEREDLINKEDLIST_H
#define LAB08_ORDEREDLINKEDLIST_H
#include <iostream>
class Node;
template <class T>
class OrderedLinkedList {
private:
template<class U>
class Node {
public:
U* data;
Node* next;
/// \brief constructor
/// \param nextNode
/// \param nodeData
Node(U* nodeData, Node* nextNode = nullptr) {
data = nodeData;
next = nextNode;
};
~Node() {
delete data;
data = nullptr;
delete next;
next = nullptr;
}
bool operator< (U &rhs) const {
return rhs > *data;
};
bool operator> (U &rhs) const {
return !(*this < rhs);
};
bool operator== (U &rhs) const {
return *data == rhs;
}
bool operator!= (U &rhs) const {
return !(*this == rhs);
}
};
Node<T>* head;
int length;
/// Node used for tracking SeeNext
Node<T>* current;
bool atBeginning;
/// \brief get the end of the list
/// \returns pointer to end of the list
Node<T>* tail();
public:
class NotFoundException {};
class EmptyListException {};
class IndexException {};
OrderedLinkedList();
~OrderedLinkedList();
/// \brief initialize the list with a given item
/// \param item
OrderedLinkedList(T* item);
/// \brief add an item to the list
/// \param item
void AddItem(T* item);
/// \brief get an item from the list
/// \param item
/// \returns item in the list if it exists, otherwise nullptr.
T* GetItem(T* item);
/// \brief get the next item after the previously returned item in the list
/// Memorizes its state, so multiple calls will result in different results.
/// State is altered if the next item to be returned is removed.
/// \returns the next item in the list
/// \throws EmptyListException
T* SeeNext();
/// \brief return the item at that index without removal
/// Also sets next item returned to SeeNext to the item after the index returned.
/// \param index
/// \returns item at that index
/// \throws IndexException
T* SeeAt(int index);
/// \brief returns next item to be returned by SeeNext() to the beginning
/// of the list.
void Reset();
/// \brief determine if an item is in the list
/// \param item
/// \returns if the item is in the list
bool IsInList(T* item);
/// \brief determine if the list is empty
/// \returns whether the list is empty
bool IsEmpty();
/// \brief get the length of the list
/// \returns the length of the list
int Size();
/// \brief print the contents of the list
void PrintList();
};
/// Private functions
template<class T>
OrderedLinkedList<T>::Node<T>* OrderedLinkedList<T>::tail() {
// tail is null if the list is empty
if (head == nullptr) {
return head;
}
Node<T>* next = head;
while (next->next != nullptr) {
next = next->next;
}
return next;
}
/// Public functions
template<class T>
OrderedLinkedList<T>::OrderedLinkedList() {
length = 0;
head = nullptr;
current = head;
atBeginning = true;
}
template<class T>
OrderedLinkedList<T>::~OrderedLinkedList() {
delete head;
}
template<class T>
OrderedLinkedList<T>::OrderedLinkedList(T* item) {
head = new Node<T>(item);
length = 1;
}
template<class T>
void OrderedLinkedList<T>::PrintList() {
Node<T>* next = head;
while (next != nullptr) {
std::cout << *next->data << std::endl;
next = next->next;
}
}
template<class T>
void OrderedLinkedList<T>::AddItem(T* item) {
Node<T>* node = new Node<T>(item);
if (head == nullptr) {
head = node;
} else if (*head > *item) {
node->next = head;
head = node;
} else {
Node<T>* next = head;
while (next->next != nullptr && *next->next < *item) {
next = next->next;
}
node->next = next->next;
next->next = node;
}
length++;
}
template<class T>
T* OrderedLinkedList<T>::GetItem(T* item) {
if (IsEmpty()) {
return nullptr;
} else {
Node<T>* next = head;
Node<T>* retval;
// always keep the pointer one space behind the item we're looking for
while (next->next != nullptr && *next->next != *item) {
next = next->next;
}
if (next == head) {
// shift head up one space
head = next->next;
// we have to change the next item to return from
// SeeNext, since it now points to something no longer
// in the list. Choosing to shift right by 1.
if (current != nullptr && current == head) {
current = next->next;
}
retval = next;
retval->next = nullptr;
length--;
return retval->data;
} else if (next->next == nullptr) {
// didn't find it
return nullptr;
} else {
// next value is the one we want
// take the node before it and point it to
// the node after the one we want
retval = next->next;
// we have to change the next item to return from
// SeeNext, since it now points to something no longer
// in the list. Choosing to shift right by 1.
if (current != nullptr && current == retval) {
current = next->next->next;
}
next->next = next->next->next;
retval->next = nullptr;
length--;
return retval->data;
}
}
}
template<class T>
T* OrderedLinkedList<T>::SeeNext() {
if (IsEmpty()) {
throw EmptyListException();
} else if (current == nullptr && !atBeginning) {
return nullptr;
} else {
if (atBeginning) {
current = head;
atBeginning = false;
}
T* data = current->data;
current = current->next;
return data;
}
}
template<class T>
T* OrderedLinkedList<T>::SeeAt(int index) {
if (index >= length) {
throw IndexException();
} else {
int i = 0;
Node<T>* retval = head;
while (i < index) {
retval = retval->next;
i++;
}
// set next value to return from SeeNext()
current = retval->next;
return retval->data;
}
}
template<class T>
void OrderedLinkedList<T>::Reset() {
atBeginning = true;
current = head;
}
template<class T>
bool OrderedLinkedList<T>::IsInList(T* item) {
if (IsEmpty()) {
return false;
} else {
Node<T>* node = head;
// return true as soon as we find it
while (node != nullptr) {
if (*node->data == *item) {
return true;
}
node = node->next;
}
// didn't find it
return false;
}
}
template<class T>
int OrderedLinkedList<T>::Size() {
return length;
}
template<class T>
bool OrderedLinkedList<T>::IsEmpty() {
return length == 0;
}
#endif //LAB08_ORDEREDLINKEDLIST_H
|
1de5c6b4c6739d457b82a97bd85d3030f8f1f9e7 | ea778356c49fd9b5f983376a802efdeb360be47a | /include/Util/JMapUtil.h | 22903a1cfead6d6fda3b9fb34d1eeebcc33d2e31 | [] | no_license | Evanbowl/Legacy-SMG2-Project-Template | 59702034fd1e2054ace33487c667df92267de8b0 | 7129565c797746d950fe11aab9fb2c9a1204d5d9 | refs/heads/main | 2023-04-18T03:15:03.798809 | 2021-04-27T23:56:28 | 2021-04-27T23:56:28 | 361,564,344 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,770 | h | JMapUtil.h | #pragma once
#include "JMap/JMapInfoIter.h"
namespace MR
{
bool getJMapInfoArg0NoInit(const JMapInfoIter &iter, s32 *out);
bool getJMapInfoArg0NoInit(const JMapInfoIter &iter, f32 *out);
bool getJMapInfoArg0NoInit(const JMapInfoIter &iter, bool *out);
bool getJMapInfoArg1NoInit(const JMapInfoIter &iter, s32 *out);
bool getJMapInfoArg1NoInit(const JMapInfoIter &iter, f32 *out);
bool getJMapInfoArg1NoInit(const JMapInfoIter &iter, bool *out);
bool getJMapInfoArg2NoInit(const JMapInfoIter &iter, s32 *out);
bool getJMapInfoArg2NoInit(const JMapInfoIter &iter, f32 *out);
bool getJMapInfoArg2NoInit(const JMapInfoIter &iter, bool *out);
bool getJMapInfoArg3NoInit(const JMapInfoIter &iter, s32 *out);
bool getJMapInfoArg3NoInit(const JMapInfoIter &iter, f32 *out);
bool getJMapInfoArg3NoInit(const JMapInfoIter &iter, bool *out);
bool getJMapInfoArg4NoInit(const JMapInfoIter &iter, s32 *out);
bool getJMapInfoArg4NoInit(const JMapInfoIter &iter, f32 *out);
bool getJMapInfoArg4NoInit(const JMapInfoIter &iter, bool *out);
bool getJMapInfoArg5NoInit(const JMapInfoIter &iter, s32 *out);
bool getJMapInfoArg5NoInit(const JMapInfoIter &iter, f32 *out);
bool getJMapInfoArg5NoInit(const JMapInfoIter &iter, bool *out);
bool getJMapInfoArg6NoInit(const JMapInfoIter &iter, s32 *out);
bool getJMapInfoArg6NoInit(const JMapInfoIter &iter, f32 *out);
bool getJMapInfoArg6NoInit(const JMapInfoIter &iter, bool *out);
bool getJMapInfoArg7NoInit(const JMapInfoIter &iter, s32 *out);
bool getJMapInfoArg7NoInit(const JMapInfoIter &iter, f32 *out);
bool getJMapInfoArg7NoInit(const JMapInfoIter &iter, bool *out);
bool isObjectName(const JMapInfoIter &, const char *);
}; |
655447b1f0cd3f903dbe564c402a2025aa01664f | d26a93001382cd60dd9fa4002c25fee289c3e80c | /Leetcode/Graph_Theory/BFS/Max_Width_Binary_Tree.cpp | 48b5dd5d7a822b0c0a5a8d7382f6b74471fded20 | [] | no_license | veedee2000/Competitive-Programming | cfb0e38d5534252f65eb266c24b19fd6c9f5124b | cebf93a994e10faf02138726435bb11b5b8ff807 | refs/heads/master | 2021-09-05T08:21:11.344179 | 2021-08-07T08:57:48 | 2021-08-07T08:57:48 | 207,164,471 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | cpp | Max_Width_Binary_Tree.cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if(!root) return 0;
queue<pair<TreeNode*,int>>q;
q.push({root,0});
int ans = 1;
while(!q.empty()){
int sz = q.size(),minL,maxL,c = 0;
while(sz--){
pair<TreeNode*,int>curr = q.front();
q.pop();
if(!c) c = !c,minL = maxL = curr.second;
else{
minL = min(minL,curr.second);
maxL = max(maxL,curr.second);
ans = max(ans,maxL - minL + 1);
}
TreeNode* node = curr.first;
if(node -> left) q.push({node -> left,2 * curr.second + 1});
if(node -> right) q.push({node -> right,2 * curr.second});
}
}
return ans;
}
};
|
d94cfe4363c592064719dd5c9d74bb0ad9b74a5c | c39862dcbc5b9ad65f582752bcfd0c5eb9be463e | /dev/external/wxWidgets-3.1.0/include/wx/wxcrt.h | dbf556310c42a47fbac97fbaa6a6555379868d4e | [
"MIT"
] | permissive | rexdex/recompiler | 5f1138adf5d02a052c8b37c290296d5cf5faadc2 | 7cd1d5a33d6c02a13f972c6564550ea816fc8b5b | refs/heads/master | 2023-08-16T16:24:37.810517 | 2022-02-12T21:20:21 | 2022-02-12T21:20:21 | 81,953,901 | 1,714 | 120 | MIT | 2022-02-12T21:20:22 | 2017-02-14T14:32:17 | C++ | UTF-8 | C++ | false | false | 49,187 | h | wxcrt.h | ///////////////////////////////////////////////////////////////////////////////
// Name: wx/wxcrt.h
// Purpose: Type-safe ANSI and Unicode builds compatible wrappers for
// CRT functions
// Author: Joel Farley, Ove Kaaven
// Modified by: Vadim Zeitlin, Robert Roebling, Ron Lee, Vaclav Slavik
// Created: 1998/06/12
// Copyright: (c) 1998-2006 wxWidgets dev team
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_WXCRT_H_
#define _WX_WXCRT_H_
#include "wx/wxcrtbase.h"
#include "wx/string.h"
#ifndef __WX_SETUP_H__
// For non-configure builds assume vsscanf is available, if not Visual C
#if !defined (__VISUALC__)
#define HAVE_VSSCANF 1
#endif
#endif
// ============================================================================
// misc functions
// ============================================================================
/* checks whether the passed in pointer is NULL and if the string is empty */
inline bool wxIsEmpty(const char *s) { return !s || !*s; }
inline bool wxIsEmpty(const wchar_t *s) { return !s || !*s; }
inline bool wxIsEmpty(const wxScopedCharBuffer& s) { return wxIsEmpty(s.data()); }
inline bool wxIsEmpty(const wxScopedWCharBuffer& s) { return wxIsEmpty(s.data()); }
inline bool wxIsEmpty(const wxString& s) { return s.empty(); }
inline bool wxIsEmpty(const wxCStrData& s) { return s.AsString().empty(); }
/* multibyte to wide char conversion functions and macros */
/* multibyte<->widechar conversion */
WXDLLIMPEXP_BASE size_t wxMB2WC(wchar_t *buf, const char *psz, size_t n);
WXDLLIMPEXP_BASE size_t wxWC2MB(char *buf, const wchar_t *psz, size_t n);
#if wxUSE_UNICODE
#define wxMB2WX wxMB2WC
#define wxWX2MB wxWC2MB
#define wxWC2WX wxStrncpy
#define wxWX2WC wxStrncpy
#else
#define wxMB2WX wxStrncpy
#define wxWX2MB wxStrncpy
#define wxWC2WX wxWC2MB
#define wxWX2WC wxMB2WC
#endif
// RN: We could do the usual tricky compiler detection here,
// and use their variant (such as wmemchr, etc.). The problem
// is that these functions are quite rare, even though they are
// part of the current POSIX standard. In addition, most compilers
// (including even MSC) inline them just like we do right in their
// headers.
//
#include <string.h>
#if wxUSE_UNICODE
//implement our own wmem variants
inline wxChar* wxTmemchr(const wxChar* s, wxChar c, size_t l)
{
for(;l && *s != c;--l, ++s) {}
if(l)
return const_cast<wxChar*>(s);
return NULL;
}
inline int wxTmemcmp(const wxChar* sz1, const wxChar* sz2, size_t len)
{
for(; *sz1 == *sz2 && len; --len, ++sz1, ++sz2) {}
if(len)
return *sz1 < *sz2 ? -1 : *sz1 > *sz2;
else
return 0;
}
inline wxChar* wxTmemcpy(wxChar* szOut, const wxChar* szIn, size_t len)
{
return (wxChar*) memcpy(szOut, szIn, len * sizeof(wxChar));
}
inline wxChar* wxTmemmove(wxChar* szOut, const wxChar* szIn, size_t len)
{
return (wxChar*) memmove(szOut, szIn, len * sizeof(wxChar));
}
inline wxChar* wxTmemset(wxChar* szOut, wxChar cIn, size_t len)
{
wxChar* szRet = szOut;
while (len--)
*szOut++ = cIn;
return szRet;
}
#endif /* wxUSE_UNICODE */
// provide trivial wrappers for char* versions for both ANSI and Unicode builds
// (notice that these intentionally return "char *" and not "void *" unlike the
// standard memxxx() for symmetry with the wide char versions):
inline char* wxTmemchr(const char* s, char c, size_t len)
{ return (char*)memchr(s, c, len); }
inline int wxTmemcmp(const char* sz1, const char* sz2, size_t len)
{ return memcmp(sz1, sz2, len); }
inline char* wxTmemcpy(char* szOut, const char* szIn, size_t len)
{ return (char*)memcpy(szOut, szIn, len); }
inline char* wxTmemmove(char* szOut, const char* szIn, size_t len)
{ return (char*)memmove(szOut, szIn, len); }
inline char* wxTmemset(char* szOut, char cIn, size_t len)
{ return (char*)memset(szOut, cIn, len); }
// ============================================================================
// wx wrappers for CRT functions in both char* and wchar_t* versions
// ============================================================================
// A few notes on implementation of these wrappers:
//
// We need both char* and wchar_t* versions of functions like wxStrlen() for
// compatibility with both ANSI and Unicode builds.
//
// This makes passing wxString or c_str()/mb_str()/wc_str() result to them
// ambiguous, so we need to provide overrides for that as well (in cases where
// it makes sense).
//
// We can do this without problems for some functions (wxStrlen()), but in some
// cases, we can't stay compatible with both ANSI and Unicode builds, e.g. for
// wxStrcpy(const wxString&), which can only return either char* or wchar_t*.
// In these cases, we preserve ANSI build compatibility by returning char*.
// ----------------------------------------------------------------------------
// locale functions
// ----------------------------------------------------------------------------
// NB: we can't provide const wchar_t* (= wxChar*) overload, because calling
// wxSetlocale(category, NULL) -- which is a common thing to do -- would be
// ambiguous
WXDLLIMPEXP_BASE char* wxSetlocale(int category, const char *locale);
inline char* wxSetlocale(int category, const wxScopedCharBuffer& locale)
{ return wxSetlocale(category, locale.data()); }
inline char* wxSetlocale(int category, const wxString& locale)
{ return wxSetlocale(category, locale.mb_str()); }
inline char* wxSetlocale(int category, const wxCStrData& locale)
{ return wxSetlocale(category, locale.AsCharBuf()); }
// ----------------------------------------------------------------------------
// string functions
// ----------------------------------------------------------------------------
/* safe version of strlen() (returns 0 if passed NULL pointer) */
// NB: these are defined in wxcrtbase.h, see the comment there
// inline size_t wxStrlen(const char *s) { return s ? strlen(s) : 0; }
// inline size_t wxStrlen(const wchar_t *s) { return s ? wxCRT_Strlen_(s) : 0; }
inline size_t wxStrlen(const wxScopedCharBuffer& s) { return wxStrlen(s.data()); }
inline size_t wxStrlen(const wxScopedWCharBuffer& s) { return wxStrlen(s.data()); }
inline size_t wxStrlen(const wxString& s) { return s.length(); }
inline size_t wxStrlen(const wxCStrData& s) { return s.AsString().length(); }
// this is a function new in 2.9 so we don't care about backwards compatibility and
// so don't need to support wxScopedCharBuffer/wxScopedWCharBuffer overloads
#if defined(wxCRT_StrnlenA)
inline size_t wxStrnlen(const char *str, size_t maxlen) { return wxCRT_StrnlenA(str, maxlen); }
#else
inline size_t wxStrnlen(const char *str, size_t maxlen)
{
size_t n;
for ( n = 0; n < maxlen; n++ )
if ( !str[n] )
break;
return n;
}
#endif
#if defined(wxCRT_StrnlenW)
inline size_t wxStrnlen(const wchar_t *str, size_t maxlen) { return wxCRT_StrnlenW(str, maxlen); }
#else
inline size_t wxStrnlen(const wchar_t *str, size_t maxlen)
{
size_t n;
for ( n = 0; n < maxlen; n++ )
if ( !str[n] )
break;
return n;
}
#endif
// NB: these are defined in wxcrtbase.h, see the comment there
// inline char* wxStrdup(const char *s) { return wxStrdupA(s); }
// inline wchar_t* wxStrdup(const wchar_t *s) { return wxStrdupW(s); }
inline char* wxStrdup(const wxScopedCharBuffer& s) { return wxStrdup(s.data()); }
inline wchar_t* wxStrdup(const wxScopedWCharBuffer& s) { return wxStrdup(s.data()); }
inline char* wxStrdup(const wxString& s) { return wxStrdup(s.mb_str()); }
inline char* wxStrdup(const wxCStrData& s) { return wxStrdup(s.AsCharBuf()); }
inline char *wxStrcpy(char *dest, const char *src)
{ return wxCRT_StrcpyA(dest, src); }
inline wchar_t *wxStrcpy(wchar_t *dest, const wchar_t *src)
{ return wxCRT_StrcpyW(dest, src); }
inline char *wxStrcpy(char *dest, const wxString& src)
{ return wxCRT_StrcpyA(dest, src.mb_str()); }
inline char *wxStrcpy(char *dest, const wxCStrData& src)
{ return wxCRT_StrcpyA(dest, src.AsCharBuf()); }
inline char *wxStrcpy(char *dest, const wxScopedCharBuffer& src)
{ return wxCRT_StrcpyA(dest, src.data()); }
inline wchar_t *wxStrcpy(wchar_t *dest, const wxString& src)
{ return wxCRT_StrcpyW(dest, src.wc_str()); }
inline wchar_t *wxStrcpy(wchar_t *dest, const wxCStrData& src)
{ return wxCRT_StrcpyW(dest, src.AsWCharBuf()); }
inline wchar_t *wxStrcpy(wchar_t *dest, const wxScopedWCharBuffer& src)
{ return wxCRT_StrcpyW(dest, src.data()); }
inline char *wxStrcpy(char *dest, const wchar_t *src)
{ return wxCRT_StrcpyA(dest, wxConvLibc.cWC2MB(src)); }
inline wchar_t *wxStrcpy(wchar_t *dest, const char *src)
{ return wxCRT_StrcpyW(dest, wxConvLibc.cMB2WC(src)); }
inline char *wxStrncpy(char *dest, const char *src, size_t n)
{ return wxCRT_StrncpyA(dest, src, n); }
inline wchar_t *wxStrncpy(wchar_t *dest, const wchar_t *src, size_t n)
{ return wxCRT_StrncpyW(dest, src, n); }
inline char *wxStrncpy(char *dest, const wxString& src, size_t n)
{ return wxCRT_StrncpyA(dest, src.mb_str(), n); }
inline char *wxStrncpy(char *dest, const wxCStrData& src, size_t n)
{ return wxCRT_StrncpyA(dest, src.AsCharBuf(), n); }
inline char *wxStrncpy(char *dest, const wxScopedCharBuffer& src, size_t n)
{ return wxCRT_StrncpyA(dest, src.data(), n); }
inline wchar_t *wxStrncpy(wchar_t *dest, const wxString& src, size_t n)
{ return wxCRT_StrncpyW(dest, src.wc_str(), n); }
inline wchar_t *wxStrncpy(wchar_t *dest, const wxCStrData& src, size_t n)
{ return wxCRT_StrncpyW(dest, src.AsWCharBuf(), n); }
inline wchar_t *wxStrncpy(wchar_t *dest, const wxScopedWCharBuffer& src, size_t n)
{ return wxCRT_StrncpyW(dest, src.data(), n); }
inline char *wxStrncpy(char *dest, const wchar_t *src, size_t n)
{ return wxCRT_StrncpyA(dest, wxConvLibc.cWC2MB(src), n); }
inline wchar_t *wxStrncpy(wchar_t *dest, const char *src, size_t n)
{ return wxCRT_StrncpyW(dest, wxConvLibc.cMB2WC(src), n); }
// this is a function new in 2.9 so we don't care about backwards compatibility and
// so don't need to support wchar_t/char overloads
inline size_t wxStrlcpy(char *dest, const char *src, size_t n)
{
const size_t len = wxCRT_StrlenA(src);
if ( n )
{
if ( n-- > len )
n = len;
wxCRT_StrncpyA(dest, src, n);
dest[n] = '\0';
}
return len;
}
inline size_t wxStrlcpy(wchar_t *dest, const wchar_t *src, size_t n)
{
const size_t len = wxCRT_StrlenW(src);
if ( n )
{
if ( n-- > len )
n = len;
wxCRT_StrncpyW(dest, src, n);
dest[n] = L'\0';
}
return len;
}
inline char *wxStrcat(char *dest, const char *src)
{ return wxCRT_StrcatA(dest, src); }
inline wchar_t *wxStrcat(wchar_t *dest, const wchar_t *src)
{ return wxCRT_StrcatW(dest, src); }
inline char *wxStrcat(char *dest, const wxString& src)
{ return wxCRT_StrcatA(dest, src.mb_str()); }
inline char *wxStrcat(char *dest, const wxCStrData& src)
{ return wxCRT_StrcatA(dest, src.AsCharBuf()); }
inline char *wxStrcat(char *dest, const wxScopedCharBuffer& src)
{ return wxCRT_StrcatA(dest, src.data()); }
inline wchar_t *wxStrcat(wchar_t *dest, const wxString& src)
{ return wxCRT_StrcatW(dest, src.wc_str()); }
inline wchar_t *wxStrcat(wchar_t *dest, const wxCStrData& src)
{ return wxCRT_StrcatW(dest, src.AsWCharBuf()); }
inline wchar_t *wxStrcat(wchar_t *dest, const wxScopedWCharBuffer& src)
{ return wxCRT_StrcatW(dest, src.data()); }
inline char *wxStrcat(char *dest, const wchar_t *src)
{ return wxCRT_StrcatA(dest, wxConvLibc.cWC2MB(src)); }
inline wchar_t *wxStrcat(wchar_t *dest, const char *src)
{ return wxCRT_StrcatW(dest, wxConvLibc.cMB2WC(src)); }
inline char *wxStrncat(char *dest, const char *src, size_t n)
{ return wxCRT_StrncatA(dest, src, n); }
inline wchar_t *wxStrncat(wchar_t *dest, const wchar_t *src, size_t n)
{ return wxCRT_StrncatW(dest, src, n); }
inline char *wxStrncat(char *dest, const wxString& src, size_t n)
{ return wxCRT_StrncatA(dest, src.mb_str(), n); }
inline char *wxStrncat(char *dest, const wxCStrData& src, size_t n)
{ return wxCRT_StrncatA(dest, src.AsCharBuf(), n); }
inline char *wxStrncat(char *dest, const wxScopedCharBuffer& src, size_t n)
{ return wxCRT_StrncatA(dest, src.data(), n); }
inline wchar_t *wxStrncat(wchar_t *dest, const wxString& src, size_t n)
{ return wxCRT_StrncatW(dest, src.wc_str(), n); }
inline wchar_t *wxStrncat(wchar_t *dest, const wxCStrData& src, size_t n)
{ return wxCRT_StrncatW(dest, src.AsWCharBuf(), n); }
inline wchar_t *wxStrncat(wchar_t *dest, const wxScopedWCharBuffer& src, size_t n)
{ return wxCRT_StrncatW(dest, src.data(), n); }
inline char *wxStrncat(char *dest, const wchar_t *src, size_t n)
{ return wxCRT_StrncatA(dest, wxConvLibc.cWC2MB(src), n); }
inline wchar_t *wxStrncat(wchar_t *dest, const char *src, size_t n)
{ return wxCRT_StrncatW(dest, wxConvLibc.cMB2WC(src), n); }
#define WX_STR_DECL(name, T1, T2) name(T1 s1, T2 s2)
#define WX_STR_CALL(func, a1, a2) func(a1, a2)
// This macro defines string function for all possible variants of arguments,
// except for those taking wxString or wxCStrData as second argument.
// Parameters:
// rettype - return type
// name - name of the (overloaded) function to define
// crtA - function to call for char* versions (takes two arguments)
// crtW - ditto for wchar_t* function
// forString - function to call when the *first* argument is wxString;
// the second argument can be any string type, so this is
// typically a template
#define WX_STR_FUNC_NO_INVERT(rettype, name, crtA, crtW, forString) \
inline rettype WX_STR_DECL(name, const char *, const char *) \
{ return WX_STR_CALL(crtA, s1, s2); } \
inline rettype WX_STR_DECL(name, const char *, const wchar_t *) \
{ return WX_STR_CALL(forString, wxString(s1), wxString(s2)); } \
inline rettype WX_STR_DECL(name, const char *, const wxScopedCharBuffer&) \
{ return WX_STR_CALL(crtA, s1, s2.data()); } \
inline rettype WX_STR_DECL(name, const char *, const wxScopedWCharBuffer&) \
{ return WX_STR_CALL(forString, wxString(s1), s2.data()); } \
\
inline rettype WX_STR_DECL(name, const wchar_t *, const wchar_t *) \
{ return WX_STR_CALL(crtW, s1, s2); } \
inline rettype WX_STR_DECL(name, const wchar_t *, const char *) \
{ return WX_STR_CALL(forString, wxString(s1), wxString(s2)); } \
inline rettype WX_STR_DECL(name, const wchar_t *, const wxScopedWCharBuffer&) \
{ return WX_STR_CALL(crtW, s1, s2.data()); } \
inline rettype WX_STR_DECL(name, const wchar_t *, const wxScopedCharBuffer&) \
{ return WX_STR_CALL(forString, wxString(s1), s2.data()); } \
\
inline rettype WX_STR_DECL(name, const wxScopedCharBuffer&, const char *) \
{ return WX_STR_CALL(crtA, s1.data(), s2); } \
inline rettype WX_STR_DECL(name, const wxScopedCharBuffer&, const wchar_t *) \
{ return WX_STR_CALL(forString, wxString(s1), wxString(s2)); } \
inline rettype WX_STR_DECL(name, const wxScopedCharBuffer&, const wxScopedCharBuffer&)\
{ return WX_STR_CALL(crtA, s1.data(), s2.data()); } \
inline rettype WX_STR_DECL(name, const wxScopedCharBuffer&, const wxScopedWCharBuffer&) \
{ return WX_STR_CALL(forString, wxString(s1), wxString(s2)); } \
\
inline rettype WX_STR_DECL(name, const wxScopedWCharBuffer&, const wchar_t *) \
{ return WX_STR_CALL(crtW, s1.data(), s2); } \
inline rettype WX_STR_DECL(name, const wxScopedWCharBuffer&, const char *) \
{ return WX_STR_CALL(forString, wxString(s1), wxString(s2)); } \
inline rettype WX_STR_DECL(name, const wxScopedWCharBuffer&, const wxScopedWCharBuffer&) \
{ return WX_STR_CALL(crtW, s1.data(), s2.data()); } \
inline rettype WX_STR_DECL(name, const wxScopedWCharBuffer&, const wxScopedCharBuffer&) \
{ return WX_STR_CALL(forString, wxString(s1), wxString(s2)); } \
\
inline rettype WX_STR_DECL(name, const wxString&, const char*) \
{ return WX_STR_CALL(forString, s1, s2); } \
inline rettype WX_STR_DECL(name, const wxString&, const wchar_t*) \
{ return WX_STR_CALL(forString, s1, s2); } \
inline rettype WX_STR_DECL(name, const wxString&, const wxScopedCharBuffer&) \
{ return WX_STR_CALL(forString, s1, s2); } \
inline rettype WX_STR_DECL(name, const wxString&, const wxScopedWCharBuffer&) \
{ return WX_STR_CALL(forString, s1, s2); } \
inline rettype WX_STR_DECL(name, const wxString&, const wxString&) \
{ return WX_STR_CALL(forString, s1, s2); } \
inline rettype WX_STR_DECL(name, const wxString&, const wxCStrData&) \
{ return WX_STR_CALL(forString, s1, s2); } \
\
inline rettype WX_STR_DECL(name, const wxCStrData&, const char*) \
{ return WX_STR_CALL(forString, s1.AsString(), s2); } \
inline rettype WX_STR_DECL(name, const wxCStrData&, const wchar_t*) \
{ return WX_STR_CALL(forString, s1.AsString(), s2); } \
inline rettype WX_STR_DECL(name, const wxCStrData&, const wxScopedCharBuffer&) \
{ return WX_STR_CALL(forString, s1.AsString(), s2); } \
inline rettype WX_STR_DECL(name, const wxCStrData&, const wxScopedWCharBuffer&) \
{ return WX_STR_CALL(forString, s1.AsString(), s2); } \
inline rettype WX_STR_DECL(name, const wxCStrData&, const wxString&) \
{ return WX_STR_CALL(forString, s1.AsString(), s2); } \
inline rettype WX_STR_DECL(name, const wxCStrData&, const wxCStrData&) \
{ return WX_STR_CALL(forString, s1.AsString(), s2); }
// This defines strcmp-like function, i.e. one returning the result of
// comparison; see WX_STR_FUNC_NO_INVERT for explanation of the arguments
#define WX_STRCMP_FUNC(name, crtA, crtW, forString) \
WX_STR_FUNC_NO_INVERT(int, name, crtA, crtW, forString) \
\
inline int WX_STR_DECL(name, const char *, const wxCStrData&) \
{ return -WX_STR_CALL(forString, s2.AsString(), s1); } \
inline int WX_STR_DECL(name, const char *, const wxString&) \
{ return -WX_STR_CALL(forString, s2, s1); } \
\
inline int WX_STR_DECL(name, const wchar_t *, const wxCStrData&) \
{ return -WX_STR_CALL(forString, s2.AsString(), s1); } \
inline int WX_STR_DECL(name, const wchar_t *, const wxString&) \
{ return -WX_STR_CALL(forString, s2, s1); } \
\
inline int WX_STR_DECL(name, const wxScopedCharBuffer&, const wxCStrData&) \
{ return -WX_STR_CALL(forString, s2.AsString(), s1.data()); } \
inline int WX_STR_DECL(name, const wxScopedCharBuffer&, const wxString&) \
{ return -WX_STR_CALL(forString, s2, s1.data()); } \
\
inline int WX_STR_DECL(name, const wxScopedWCharBuffer&, const wxCStrData&) \
{ return -WX_STR_CALL(forString, s2.AsString(), s1.data()); } \
inline int WX_STR_DECL(name, const wxScopedWCharBuffer&, const wxString&) \
{ return -WX_STR_CALL(forString, s2, s1.data()); }
// This defines a string function that is *not* strcmp-like, i.e. doesn't
// return the result of comparison and so if the second argument is a string,
// it has to be converted to char* or wchar_t*
#define WX_STR_FUNC(rettype, name, crtA, crtW, forString) \
WX_STR_FUNC_NO_INVERT(rettype, name, crtA, crtW, forString) \
\
inline rettype WX_STR_DECL(name, const char *, const wxCStrData&) \
{ return WX_STR_CALL(crtA, s1, s2.AsCharBuf()); } \
inline rettype WX_STR_DECL(name, const char *, const wxString&) \
{ return WX_STR_CALL(crtA, s1, s2.mb_str()); } \
\
inline rettype WX_STR_DECL(name, const wchar_t *, const wxCStrData&) \
{ return WX_STR_CALL(crtW, s1, s2.AsWCharBuf()); } \
inline rettype WX_STR_DECL(name, const wchar_t *, const wxString&) \
{ return WX_STR_CALL(crtW, s1, s2.wc_str()); } \
\
inline rettype WX_STR_DECL(name, const wxScopedCharBuffer&, const wxCStrData&) \
{ return WX_STR_CALL(crtA, s1.data(), s2.AsCharBuf()); } \
inline rettype WX_STR_DECL(name, const wxScopedCharBuffer&, const wxString&) \
{ return WX_STR_CALL(crtA, s1.data(), s2.mb_str()); } \
\
inline rettype WX_STR_DECL(name, const wxScopedWCharBuffer&, const wxCStrData&) \
{ return WX_STR_CALL(crtW, s1.data(), s2.AsWCharBuf()); } \
inline rettype WX_STR_DECL(name, const wxScopedWCharBuffer&, const wxString&) \
{ return WX_STR_CALL(crtW, s1.data(), s2.wc_str()); }
template<typename T>
inline int wxStrcmp_String(const wxString& s1, const T& s2)
{ return s1.compare(s2); }
WX_STRCMP_FUNC(wxStrcmp, wxCRT_StrcmpA, wxCRT_StrcmpW, wxStrcmp_String)
template<typename T>
inline int wxStricmp_String(const wxString& s1, const T& s2)
{ return s1.CmpNoCase(s2); }
WX_STRCMP_FUNC(wxStricmp, wxCRT_StricmpA, wxCRT_StricmpW, wxStricmp_String)
#if defined(wxCRT_StrcollA) && defined(wxCRT_StrcollW)
// GCC 3.4 and other compilers have a bug that causes it to fail compilation if
// the template's implementation uses overloaded function declared later (see
// the wxStrcoll() call in wxStrcoll_String<T>()), so we have to
// forward-declare the template and implement it below WX_STRCMP_FUNC. OTOH,
// this causes problems with GCC visibility in newer GCC versions.
#if !(wxCHECK_GCC_VERSION(3,5) && !wxCHECK_GCC_VERSION(4,7)) || defined(__clang__)
#define wxNEEDS_DECL_BEFORE_TEMPLATE
#endif
#ifdef wxNEEDS_DECL_BEFORE_TEMPLATE
template<typename T>
inline int wxStrcoll_String(const wxString& s1, const T& s2);
WX_STRCMP_FUNC(wxStrcoll, wxCRT_StrcollA, wxCRT_StrcollW, wxStrcoll_String)
#endif // wxNEEDS_DECL_BEFORE_TEMPLATE
template<typename T>
inline int wxStrcoll_String(const wxString& s1, const T& s2)
{
#if wxUSE_UNICODE
// NB: strcoll() doesn't work correctly on UTF-8 strings, so we have to use
// wc_str() even if wxUSE_UNICODE_UTF8; the (const wchar_t*) cast is
// there just as optimization to avoid going through
// wxStrcoll<wxScopedWCharBuffer>:
return wxStrcoll((const wchar_t*)s1.wc_str(), s2);
#else
return wxStrcoll((const char*)s1.mb_str(), s2);
#endif
}
#ifndef wxNEEDS_DECL_BEFORE_TEMPLATE
// this is exactly the same WX_STRCMP_FUNC line as above, insde the
// wxNEEDS_DECL_BEFORE_TEMPLATE case
WX_STRCMP_FUNC(wxStrcoll, wxCRT_StrcollA, wxCRT_StrcollW, wxStrcoll_String)
#endif
#endif // defined(wxCRT_Strcoll[AW])
template<typename T>
inline size_t wxStrspn_String(const wxString& s1, const T& s2)
{
size_t pos = s1.find_first_not_of(s2);
return pos == wxString::npos ? s1.length() : pos;
}
WX_STR_FUNC(size_t, wxStrspn, wxCRT_StrspnA, wxCRT_StrspnW, wxStrspn_String)
template<typename T>
inline size_t wxStrcspn_String(const wxString& s1, const T& s2)
{
size_t pos = s1.find_first_of(s2);
return pos == wxString::npos ? s1.length() : pos;
}
WX_STR_FUNC(size_t, wxStrcspn, wxCRT_StrcspnA, wxCRT_StrcspnW, wxStrcspn_String)
#undef WX_STR_DECL
#undef WX_STR_CALL
#define WX_STR_DECL(name, T1, T2) name(T1 s1, T2 s2, size_t n)
#define WX_STR_CALL(func, a1, a2) func(a1, a2, n)
template<typename T>
inline int wxStrncmp_String(const wxString& s1, const T& s2, size_t n)
{ return s1.compare(0, n, s2, 0, n); }
WX_STRCMP_FUNC(wxStrncmp, wxCRT_StrncmpA, wxCRT_StrncmpW, wxStrncmp_String)
template<typename T>
inline int wxStrnicmp_String(const wxString& s1, const T& s2, size_t n)
{ return s1.substr(0, n).CmpNoCase(wxString(s2).substr(0, n)); }
WX_STRCMP_FUNC(wxStrnicmp, wxCRT_StrnicmpA, wxCRT_StrnicmpW, wxStrnicmp_String)
#undef WX_STR_DECL
#undef WX_STR_CALL
#undef WX_STRCMP_FUNC
#undef WX_STR_FUNC
#undef WX_STR_FUNC_NO_INVERT
#if defined(wxCRT_StrxfrmA) && defined(wxCRT_StrxfrmW)
inline size_t wxStrxfrm(char *dest, const char *src, size_t n)
{ return wxCRT_StrxfrmA(dest, src, n); }
inline size_t wxStrxfrm(wchar_t *dest, const wchar_t *src, size_t n)
{ return wxCRT_StrxfrmW(dest, src, n); }
template<typename T>
inline size_t wxStrxfrm(T *dest, const wxScopedCharTypeBuffer<T>& src, size_t n)
{ return wxStrxfrm(dest, src.data(), n); }
inline size_t wxStrxfrm(char *dest, const wxString& src, size_t n)
{ return wxCRT_StrxfrmA(dest, src.mb_str(), n); }
inline size_t wxStrxfrm(wchar_t *dest, const wxString& src, size_t n)
{ return wxCRT_StrxfrmW(dest, src.wc_str(), n); }
inline size_t wxStrxfrm(char *dest, const wxCStrData& src, size_t n)
{ return wxCRT_StrxfrmA(dest, src.AsCharBuf(), n); }
inline size_t wxStrxfrm(wchar_t *dest, const wxCStrData& src, size_t n)
{ return wxCRT_StrxfrmW(dest, src.AsWCharBuf(), n); }
#endif // defined(wxCRT_Strxfrm[AW])
inline char *wxStrtok(char *str, const char *delim, char **saveptr)
{ return wxCRT_StrtokA(str, delim, saveptr); }
inline wchar_t *wxStrtok(wchar_t *str, const wchar_t *delim, wchar_t **saveptr)
{ return wxCRT_StrtokW(str, delim, saveptr); }
template<typename T>
inline T *wxStrtok(T *str, const wxScopedCharTypeBuffer<T>& delim, T **saveptr)
{ return wxStrtok(str, delim.data(), saveptr); }
inline char *wxStrtok(char *str, const wxCStrData& delim, char **saveptr)
{ return wxCRT_StrtokA(str, delim.AsCharBuf(), saveptr); }
inline wchar_t *wxStrtok(wchar_t *str, const wxCStrData& delim, wchar_t **saveptr)
{ return wxCRT_StrtokW(str, delim.AsWCharBuf(), saveptr); }
inline char *wxStrtok(char *str, const wxString& delim, char **saveptr)
{ return wxCRT_StrtokA(str, delim.mb_str(), saveptr); }
inline wchar_t *wxStrtok(wchar_t *str, const wxString& delim, wchar_t **saveptr)
{ return wxCRT_StrtokW(str, delim.wc_str(), saveptr); }
inline const char *wxStrstr(const char *haystack, const char *needle)
{ return wxCRT_StrstrA(haystack, needle); }
inline const wchar_t *wxStrstr(const wchar_t *haystack, const wchar_t *needle)
{ return wxCRT_StrstrW(haystack, needle); }
inline const char *wxStrstr(const char *haystack, const wxString& needle)
{ return wxCRT_StrstrA(haystack, needle.mb_str()); }
inline const wchar_t *wxStrstr(const wchar_t *haystack, const wxString& needle)
{ return wxCRT_StrstrW(haystack, needle.wc_str()); }
// these functions return char* pointer into the non-temporary conversion buffer
// used by c_str()'s implicit conversion to char*, for ANSI build compatibility
inline const char *wxStrstr(const wxString& haystack, const wxString& needle)
{ return wxCRT_StrstrA(haystack.c_str(), needle.mb_str()); }
inline const char *wxStrstr(const wxCStrData& haystack, const wxString& needle)
{ return wxCRT_StrstrA(haystack, needle.mb_str()); }
inline const char *wxStrstr(const wxCStrData& haystack, const wxCStrData& needle)
{ return wxCRT_StrstrA(haystack, needle.AsCharBuf()); }
// if 'needle' is char/wchar_t, then the same is probably wanted as return value
inline const char *wxStrstr(const wxString& haystack, const char *needle)
{ return wxCRT_StrstrA(haystack.c_str(), needle); }
inline const char *wxStrstr(const wxCStrData& haystack, const char *needle)
{ return wxCRT_StrstrA(haystack, needle); }
inline const wchar_t *wxStrstr(const wxString& haystack, const wchar_t *needle)
{ return wxCRT_StrstrW(haystack.c_str(), needle); }
inline const wchar_t *wxStrstr(const wxCStrData& haystack, const wchar_t *needle)
{ return wxCRT_StrstrW(haystack, needle); }
inline const char *wxStrchr(const char *s, char c)
{ return wxCRT_StrchrA(s, c); }
inline const wchar_t *wxStrchr(const wchar_t *s, wchar_t c)
{ return wxCRT_StrchrW(s, c); }
inline const char *wxStrrchr(const char *s, char c)
{ return wxCRT_StrrchrA(s, c); }
inline const wchar_t *wxStrrchr(const wchar_t *s, wchar_t c)
{ return wxCRT_StrrchrW(s, c); }
inline const char *wxStrchr(const char *s, const wxUniChar& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrchrA(s, c) : NULL; }
inline const wchar_t *wxStrchr(const wchar_t *s, const wxUniChar& c)
{ return wxCRT_StrchrW(s, (wchar_t)c); }
inline const char *wxStrrchr(const char *s, const wxUniChar& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrrchrA(s, c) : NULL; }
inline const wchar_t *wxStrrchr(const wchar_t *s, const wxUniChar& c)
{ return wxCRT_StrrchrW(s, (wchar_t)c); }
inline const char *wxStrchr(const char *s, const wxUniCharRef& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrchrA(s, c) : NULL; }
inline const wchar_t *wxStrchr(const wchar_t *s, const wxUniCharRef& c)
{ return wxCRT_StrchrW(s, (wchar_t)c); }
inline const char *wxStrrchr(const char *s, const wxUniCharRef& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrrchrA(s, c) : NULL; }
inline const wchar_t *wxStrrchr(const wchar_t *s, const wxUniCharRef& c)
{ return wxCRT_StrrchrW(s, (wchar_t)c); }
template<typename T>
inline const T* wxStrchr(const wxScopedCharTypeBuffer<T>& s, T c)
{ return wxStrchr(s.data(), c); }
template<typename T>
inline const T* wxStrrchr(const wxScopedCharTypeBuffer<T>& s, T c)
{ return wxStrrchr(s.data(), c); }
template<typename T>
inline const T* wxStrchr(const wxScopedCharTypeBuffer<T>& s, const wxUniChar& c)
{ return wxStrchr(s.data(), (T)c); }
template<typename T>
inline const T* wxStrrchr(const wxScopedCharTypeBuffer<T>& s, const wxUniChar& c)
{ return wxStrrchr(s.data(), (T)c); }
template<typename T>
inline const T* wxStrchr(const wxScopedCharTypeBuffer<T>& s, const wxUniCharRef& c)
{ return wxStrchr(s.data(), (T)c); }
template<typename T>
inline const T* wxStrrchr(const wxScopedCharTypeBuffer<T>& s, const wxUniCharRef& c)
{ return wxStrrchr(s.data(), (T)c); }
// these functions return char* pointer into the non-temporary conversion buffer
// used by c_str()'s implicit conversion to char*, for ANSI build compatibility
inline const char* wxStrchr(const wxString& s, char c)
{ return wxCRT_StrchrA((const char*)s.c_str(), c); }
inline const char* wxStrrchr(const wxString& s, char c)
{ return wxCRT_StrrchrA((const char*)s.c_str(), c); }
inline const char* wxStrchr(const wxString& s, int c)
{ return wxCRT_StrchrA((const char*)s.c_str(), c); }
inline const char* wxStrrchr(const wxString& s, int c)
{ return wxCRT_StrrchrA((const char*)s.c_str(), c); }
inline const char* wxStrchr(const wxString& s, const wxUniChar& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrchrA(s.c_str(), c) : NULL; }
inline const char* wxStrrchr(const wxString& s, const wxUniChar& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrrchrA(s.c_str(), c) : NULL; }
inline const char* wxStrchr(const wxString& s, const wxUniCharRef& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrchrA(s.c_str(), c) : NULL; }
inline const char* wxStrrchr(const wxString& s, const wxUniCharRef& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrrchrA(s.c_str(), c) : NULL; }
inline const wchar_t* wxStrchr(const wxString& s, wchar_t c)
{ return wxCRT_StrchrW((const wchar_t*)s.c_str(), c); }
inline const wchar_t* wxStrrchr(const wxString& s, wchar_t c)
{ return wxCRT_StrrchrW((const wchar_t*)s.c_str(), c); }
inline const char* wxStrchr(const wxCStrData& s, char c)
{ return wxCRT_StrchrA(s.AsChar(), c); }
inline const char* wxStrrchr(const wxCStrData& s, char c)
{ return wxCRT_StrrchrA(s.AsChar(), c); }
inline const char* wxStrchr(const wxCStrData& s, int c)
{ return wxCRT_StrchrA(s.AsChar(), c); }
inline const char* wxStrrchr(const wxCStrData& s, int c)
{ return wxCRT_StrrchrA(s.AsChar(), c); }
inline const char* wxStrchr(const wxCStrData& s, const wxUniChar& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrchrA(s, c) : NULL; }
inline const char* wxStrrchr(const wxCStrData& s, const wxUniChar& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrrchrA(s, c) : NULL; }
inline const char* wxStrchr(const wxCStrData& s, const wxUniCharRef& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrchrA(s, c) : NULL; }
inline const char* wxStrrchr(const wxCStrData& s, const wxUniCharRef& uc)
{ char c; return uc.GetAsChar(&c) ? wxCRT_StrrchrA(s, c) : NULL; }
inline const wchar_t* wxStrchr(const wxCStrData& s, wchar_t c)
{ return wxCRT_StrchrW(s.AsWChar(), c); }
inline const wchar_t* wxStrrchr(const wxCStrData& s, wchar_t c)
{ return wxCRT_StrrchrW(s.AsWChar(), c); }
inline const char *wxStrpbrk(const char *s, const char *accept)
{ return wxCRT_StrpbrkA(s, accept); }
inline const wchar_t *wxStrpbrk(const wchar_t *s, const wchar_t *accept)
{ return wxCRT_StrpbrkW(s, accept); }
inline const char *wxStrpbrk(const char *s, const wxString& accept)
{ return wxCRT_StrpbrkA(s, accept.mb_str()); }
inline const char *wxStrpbrk(const char *s, const wxCStrData& accept)
{ return wxCRT_StrpbrkA(s, accept.AsCharBuf()); }
inline const wchar_t *wxStrpbrk(const wchar_t *s, const wxString& accept)
{ return wxCRT_StrpbrkW(s, accept.wc_str()); }
inline const wchar_t *wxStrpbrk(const wchar_t *s, const wxCStrData& accept)
{ return wxCRT_StrpbrkW(s, accept.AsWCharBuf()); }
inline const char *wxStrpbrk(const wxString& s, const wxString& accept)
{ return wxCRT_StrpbrkA(s.c_str(), accept.mb_str()); }
inline const char *wxStrpbrk(const wxString& s, const char *accept)
{ return wxCRT_StrpbrkA(s.c_str(), accept); }
inline const wchar_t *wxStrpbrk(const wxString& s, const wchar_t *accept)
{ return wxCRT_StrpbrkW(s.wc_str(), accept); }
inline const char *wxStrpbrk(const wxString& s, const wxCStrData& accept)
{ return wxCRT_StrpbrkA(s.c_str(), accept.AsCharBuf()); }
inline const char *wxStrpbrk(const wxCStrData& s, const wxString& accept)
{ return wxCRT_StrpbrkA(s.AsChar(), accept.mb_str()); }
inline const char *wxStrpbrk(const wxCStrData& s, const char *accept)
{ return wxCRT_StrpbrkA(s.AsChar(), accept); }
inline const wchar_t *wxStrpbrk(const wxCStrData& s, const wchar_t *accept)
{ return wxCRT_StrpbrkW(s.AsWChar(), accept); }
inline const char *wxStrpbrk(const wxCStrData& s, const wxCStrData& accept)
{ return wxCRT_StrpbrkA(s.AsChar(), accept.AsCharBuf()); }
template <typename S, typename T>
inline const T *wxStrpbrk(const S& s, const wxScopedCharTypeBuffer<T>& accept)
{ return wxStrpbrk(s, accept.data()); }
/* inlined non-const versions */
template <typename T>
inline char *wxStrstr(char *haystack, T needle)
{ return const_cast<char*>(wxStrstr(const_cast<const char*>(haystack), needle)); }
template <typename T>
inline wchar_t *wxStrstr(wchar_t *haystack, T needle)
{ return const_cast<wchar_t*>(wxStrstr(const_cast<const wchar_t*>(haystack), needle)); }
template <typename T>
inline char * wxStrchr(char *s, T c)
{ return const_cast<char*>(wxStrchr(const_cast<const char*>(s), c)); }
template <typename T>
inline wchar_t * wxStrchr(wchar_t *s, T c)
{ return (wchar_t *)wxStrchr((const wchar_t *)s, c); }
template <typename T>
inline char * wxStrrchr(char *s, T c)
{ return const_cast<char*>(wxStrrchr(const_cast<const char*>(s), c)); }
template <typename T>
inline wchar_t * wxStrrchr(wchar_t *s, T c)
{ return const_cast<wchar_t*>(wxStrrchr(const_cast<const wchar_t*>(s), c)); }
template <typename T>
inline char * wxStrpbrk(char *s, T accept)
{ return const_cast<char*>(wxStrpbrk(const_cast<const char*>(s), accept)); }
template <typename T>
inline wchar_t * wxStrpbrk(wchar_t *s, T accept)
{ return const_cast<wchar_t*>(wxStrpbrk(const_cast<const wchar_t*>(s), accept)); }
// ----------------------------------------------------------------------------
// stdio.h functions
// ----------------------------------------------------------------------------
// NB: using fn_str() for mode is a hack to get the same type (char*/wchar_t*)
// as needed, the conversion itself doesn't matter, it's ASCII
inline FILE *wxFopen(const wxString& path, const wxString& mode)
{ return wxCRT_Fopen(path.fn_str(), mode.fn_str()); }
inline FILE *wxFreopen(const wxString& path, const wxString& mode, FILE *stream)
{ return wxCRT_Freopen(path.fn_str(), mode.fn_str(), stream); }
inline int wxRemove(const wxString& path)
{ return wxCRT_Remove(path.fn_str()); }
inline int wxRename(const wxString& oldpath, const wxString& newpath)
{ return wxCRT_Rename(oldpath.fn_str(), newpath.fn_str()); }
extern WXDLLIMPEXP_BASE int wxPuts(const wxString& s);
extern WXDLLIMPEXP_BASE int wxFputs(const wxString& s, FILE *stream);
extern WXDLLIMPEXP_BASE void wxPerror(const wxString& s);
extern WXDLLIMPEXP_BASE int wxFputc(const wxUniChar& c, FILE *stream);
#define wxPutc(c, stream) wxFputc(c, stream)
#define wxPutchar(c) wxFputc(c, stdout)
#define wxFputchar(c) wxPutchar(c)
// NB: We only provide ANSI version of fgets() because fgetws() interprets the
// stream according to current locale, which is rarely what is desired.
inline char *wxFgets(char *s, int size, FILE *stream)
{ return wxCRT_FgetsA(s, size, stream); }
// This version calls ANSI version and converts the string using wxConvLibc
extern WXDLLIMPEXP_BASE wchar_t *wxFgets(wchar_t *s, int size, FILE *stream);
#define wxGets(s) wxGets_is_insecure_and_dangerous_use_wxFgets_instead
// NB: We only provide ANSI versions of this for the same reasons as in the
// case of wxFgets() above
inline int wxFgetc(FILE *stream) { return wxCRT_FgetcA(stream); }
inline int wxUngetc(int c, FILE *stream) { return wxCRT_UngetcA(c, stream); }
#define wxGetc(stream) wxFgetc(stream)
#define wxGetchar() wxFgetc(stdin)
#define wxFgetchar() wxGetchar()
// ----------------------------------------------------------------------------
// stdlib.h functions
// ----------------------------------------------------------------------------
#ifdef wxCRT_AtoiW
inline int wxAtoi(const wxString& str) { return wxCRT_AtoiW(str.wc_str()); }
#else
inline int wxAtoi(const wxString& str) { return wxCRT_AtoiA(str.mb_str()); }
#endif
#ifdef wxCRT_AtolW
inline long wxAtol(const wxString& str) { return wxCRT_AtolW(str.wc_str()); }
#else
inline long wxAtol(const wxString& str) { return wxCRT_AtolA(str.mb_str()); }
#endif
#ifdef wxCRT_AtofW
inline double wxAtof(const wxString& str) { return wxCRT_AtofW(str.wc_str()); }
#else
inline double wxAtof(const wxString& str) { return wxCRT_AtofA(str.mb_str()); }
#endif
inline double wxStrtod(const char *nptr, char **endptr)
{ return wxCRT_StrtodA(nptr, endptr); }
inline double wxStrtod(const wchar_t *nptr, wchar_t **endptr)
{ return wxCRT_StrtodW(nptr, endptr); }
template<typename T>
inline double wxStrtod(const wxScopedCharTypeBuffer<T>& nptr, T **endptr)
{ return wxStrtod(nptr.data(), endptr); }
// We implement wxStrto*() like this so that the code compiles when NULL is
// passed in - - if we had just char** and wchar_t** overloads for 'endptr', it
// would be ambiguous. The solution is to use a template so that endptr can be
// any type: when NULL constant is used, the type will be int and we can handle
// that case specially. Otherwise, we infer the type that 'nptr' should be
// converted to from the type of 'endptr'. We need wxStrtoxCharType<T> template
// to make the code compile even for T=int (that's the case when it's not going
// to be ever used, but it still has to compile).
template<typename T> struct wxStrtoxCharType {};
template<> struct wxStrtoxCharType<char**>
{
typedef const char* Type;
static char** AsPointer(char **p) { return p; }
};
template<> struct wxStrtoxCharType<wchar_t**>
{
typedef const wchar_t* Type;
static wchar_t** AsPointer(wchar_t **p) { return p; }
};
template<> struct wxStrtoxCharType<int>
{
typedef const char* Type; /* this one is never used */
static char** AsPointer(int WXUNUSED_UNLESS_DEBUG(p))
{
wxASSERT_MSG( p == 0, "passing non-NULL int is invalid" );
return NULL;
}
};
template<typename T>
inline double wxStrtod(const wxString& nptr, T endptr)
{
if ( endptr == 0 )
{
// when we don't care about endptr, use the string representation that
// doesn't require any conversion (it doesn't matter for this function
// even if its UTF-8):
return wxStrtod(nptr.wx_str(), (wxStringCharType**)NULL);
}
else
{
// note that it is important to use c_str() here and not mb_str() or
// wc_str(), because we store the pointer into (possibly converted)
// buffer in endptr and so it must be valid even when wxStrtod() returns
typedef typename wxStrtoxCharType<T>::Type CharType;
return wxStrtod((CharType)nptr.c_str(),
wxStrtoxCharType<T>::AsPointer(endptr));
}
}
template<typename T>
inline double wxStrtod(const wxCStrData& nptr, T endptr)
{ return wxStrtod(nptr.AsString(), endptr); }
#define WX_STRTOX_FUNC(rettype, name, implA, implW) \
/* see wxStrtod() above for explanation of this code: */ \
inline rettype name(const char *nptr, char **endptr, int base) \
{ return implA(nptr, endptr, base); } \
inline rettype name(const wchar_t *nptr, wchar_t **endptr, int base) \
{ return implW(nptr, endptr, base); } \
template<typename T> \
inline rettype name(const wxScopedCharTypeBuffer<T>& nptr, T **endptr, int)\
{ return name(nptr.data(), endptr); } \
template<typename T> \
inline rettype name(const wxString& nptr, T endptr, int base) \
{ \
if ( endptr == 0 ) \
return name(nptr.wx_str(), (wxStringCharType**)NULL, base); \
else \
{ \
typedef typename wxStrtoxCharType<T>::Type CharType; \
return name((CharType)nptr.c_str(), \
wxStrtoxCharType<T>::AsPointer(endptr), \
base); \
} \
} \
template<typename T> \
inline rettype name(const wxCStrData& nptr, T endptr, int base) \
{ return name(nptr.AsString(), endptr, base); }
WX_STRTOX_FUNC(long, wxStrtol, wxCRT_StrtolA, wxCRT_StrtolW)
WX_STRTOX_FUNC(unsigned long, wxStrtoul, wxCRT_StrtoulA, wxCRT_StrtoulW)
#ifdef wxLongLong_t
WX_STRTOX_FUNC(wxLongLong_t, wxStrtoll, wxCRT_StrtollA, wxCRT_StrtollW)
WX_STRTOX_FUNC(wxULongLong_t, wxStrtoull, wxCRT_StrtoullA, wxCRT_StrtoullW)
#endif // wxLongLong_t
#undef WX_STRTOX_FUNC
// mingw32 doesn't provide _tsystem() even though it provides other stdlib.h
// functions in their wide versions
#ifdef wxCRT_SystemW
inline int wxSystem(const wxString& str) { return wxCRT_SystemW(str.wc_str()); }
#else
inline int wxSystem(const wxString& str) { return wxCRT_SystemA(str.mb_str()); }
#endif
inline char* wxGetenv(const char *name) { return wxCRT_GetenvA(name); }
inline wchar_t* wxGetenv(const wchar_t *name) { return wxCRT_GetenvW(name); }
inline char* wxGetenv(const wxString& name) { return wxCRT_GetenvA(name.mb_str()); }
inline char* wxGetenv(const wxCStrData& name) { return wxCRT_GetenvA(name.AsCharBuf()); }
inline char* wxGetenv(const wxScopedCharBuffer& name) { return wxCRT_GetenvA(name.data()); }
inline wchar_t* wxGetenv(const wxScopedWCharBuffer& name) { return wxCRT_GetenvW(name.data()); }
// ----------------------------------------------------------------------------
// time.h functions
// ----------------------------------------------------------------------------
inline size_t wxStrftime(char *s, size_t max,
const wxString& format, const struct tm *tm)
{ return wxCRT_StrftimeA(s, max, format.mb_str(), tm); }
inline size_t wxStrftime(wchar_t *s, size_t max,
const wxString& format, const struct tm *tm)
{ return wxCRT_StrftimeW(s, max, format.wc_str(), tm); }
// NB: we can't provide both char* and wchar_t* versions for obvious reasons
// and returning wxString wouldn't work either (it would be immediately
// destroyed and if assigned to char*/wchar_t*, the pointer would be
// invalid), so we only keep ASCII version, because the returned value
// is always ASCII anyway
#define wxAsctime asctime
#define wxCtime ctime
// ----------------------------------------------------------------------------
// ctype.h functions
// ----------------------------------------------------------------------------
// FIXME-UTF8: we'd be better off implementing these ourselves, as the CRT
// version is locale-dependent
// FIXME-UTF8: these don't work when EOF is passed in because of wxUniChar,
// is this OK or not?
inline bool wxIsalnum(const wxUniChar& c) { return wxCRT_IsalnumW(c) != 0; }
inline bool wxIsalpha(const wxUniChar& c) { return wxCRT_IsalphaW(c) != 0; }
inline bool wxIscntrl(const wxUniChar& c) { return wxCRT_IscntrlW(c) != 0; }
inline bool wxIsdigit(const wxUniChar& c) { return wxCRT_IsdigitW(c) != 0; }
inline bool wxIsgraph(const wxUniChar& c) { return wxCRT_IsgraphW(c) != 0; }
inline bool wxIslower(const wxUniChar& c) { return wxCRT_IslowerW(c) != 0; }
inline bool wxIsprint(const wxUniChar& c) { return wxCRT_IsprintW(c) != 0; }
inline bool wxIspunct(const wxUniChar& c) { return wxCRT_IspunctW(c) != 0; }
inline bool wxIsspace(const wxUniChar& c) { return wxCRT_IsspaceW(c) != 0; }
inline bool wxIsupper(const wxUniChar& c) { return wxCRT_IsupperW(c) != 0; }
inline bool wxIsxdigit(const wxUniChar& c) { return wxCRT_IsxdigitW(c) != 0; }
inline wxUniChar wxTolower(const wxUniChar& c) { return wxCRT_TolowerW(c); }
inline wxUniChar wxToupper(const wxUniChar& c) { return wxCRT_ToupperW(c); }
#if WXWIN_COMPATIBILITY_2_8
// we had goofed and defined wxIsctrl() instead of (correct) wxIscntrl() in the
// initial versions of this header -- now it is too late to remove it so
// although we fixed the function/macro name above, still provide the
// backwards-compatible synonym.
wxDEPRECATED( inline int wxIsctrl(const wxUniChar& c) );
inline int wxIsctrl(const wxUniChar& c) { return wxIscntrl(c); }
#endif // WXWIN_COMPATIBILITY_2_8
inline bool wxIsascii(const wxUniChar& c) { return c.IsAscii(); }
#endif /* _WX_WXCRT_H_ */
|
29fbd6673081d1f9146d6b690a7036bf28d5140e | f90b4cccaac205833413af237cab9d89ec80fd1d | /creatures.h | bd96f26bfec27e5f3b639f8fd7c4bc58b1b9413c | [] | no_license | perquam/duzajaskinia | bc4eed98bfdee86d7d9cdeebdbfdca3b734af6e4 | d7e44ad6d8fdcfe3faea626793b60ad5b2940393 | refs/heads/master | 2021-01-13T03:39:20.793358 | 2016-12-28T18:11:44 | 2016-12-28T18:11:44 | 77,257,609 | 2 | 2 | null | 2016-12-24T21:00:36 | 2016-12-24T00:30:51 | C++ | UTF-8 | C++ | false | false | 1,131 | h | creatures.h | #include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "game_object.h"
class Player : public sf::Drawable, sf::Transformable, Game_Object
{
sf::Texture player;
sf::Sprite player_r;
sf::Clock frameTime;
sf::Clock time;
int p_width, p_height;
int p_posx, p_posy;
//MOTION_PARAMETERS
float vx = 2.5;
float g = -1.0, vp = -14, vy = 0;
//ANIMATIONS
int act_frame = 0;
virtual void Player::draw(sf::RenderTarget &target, sf::RenderStates states) const;
enum StatusX { MOVEX, STOPX };
enum StatusY { MOVEY, STOPY };
StatusX statusx;
StatusY statusy;
float t;
bool left = false, right = false, up = false;
bool ch_s;
public:
Player(const static int width = 35, const static int height = 55, const static int posx = 80, const static int posy = 420);
~Player();
void move();
void updatex();
void updatey();
void stopx();
void stopy();
void startxy();
void change_speed(float speed);
void fall(); //FALLING
void play(); //ANIMATIONS
sf::Vector2f moving();
sf::Vector2f getPosition();
sf::FloatRect getBoundingBox();
sf::Vector2f getSpeed();
sf::Vector2f getWH();
};
|
235c002506f4b9ada5cb742f36a303e9caec270c | e9e74fdbdede5f39b26782df201780f2a5d10ed9 | /cpp/TestStaticLib/staticlib.h | 6ac1df4105015a42a4fb9a4de91ed6183d7d73ec | [
"Apache-2.0"
] | permissive | wangxiaobai-dd/MyRep | d6258f4d472243f82540fbb0c750117059dc1c0c | f33132868d8520971174bdfd8976587309c4faef | refs/heads/master | 2023-04-09T12:32:59.987183 | 2022-10-16T08:41:20 | 2022-10-16T08:41:20 | 248,949,848 | 0 | 0 | Apache-2.0 | 2023-02-25T07:31:23 | 2020-03-21T10:06:33 | C++ | UTF-8 | C++ | false | false | 62 | h | staticlib.h | #include <iostream>
struct Test
{
int a = 0;
int b= 0;
};
|
460fdd2420fa20de0ecf130e4d91cd82842d288b | 4d27e90f74ef452619a3abba488b902389b6a733 | /mesh.cpp | 7b2088c91f02aa710fcfe1fce853a7462d449867 | [] | no_license | tshih5/CS130-raytracer | e4414c1e8bb8f626d8a098cb02cc1ca7764342cd | 5b238c6c103bc85f3c93958aab65de9a90a83612 | refs/heads/master | 2020-12-19T10:49:22.694235 | 2020-10-13T20:33:17 | 2020-10-13T20:33:17 | 235,711,180 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,516 | cpp | mesh.cpp | #include "mesh.h"
#include <fstream>
#include <string>
#include <limits>
// Consider a triangle to intersect a ray if the ray intersects the plane of the
// triangle with barycentric weights in [-weight_tolerance, 1+weight_tolerance]
static const double weight_tolerance = 1e-4;
// Read in a mesh from an obj file. Populates the bounding box and registers
// one part per triangle (by setting number_parts).
void Mesh::Read_Obj(const char* file)
{
std::ifstream fin(file);
if(!fin)
{
exit(EXIT_FAILURE);
}
std::string line;
ivec3 e;
vec3 v;
box.Make_Empty();
while(fin)
{
getline(fin,line);
if(sscanf(line.c_str(), "v %lg %lg %lg", &v[0], &v[1], &v[2]) == 3)
{
vertices.push_back(v);
box.Include_Point(v);
}
if(sscanf(line.c_str(), "f %d %d %d", &e[0], &e[1], &e[2]) == 3)
{
for(int i=0;i<3;i++) e[i]--;
triangles.push_back(e);
}
}
number_parts=triangles.size();
}
// Check for an intersection against the ray. See the base class for details.
Hit Mesh::Intersection(const Ray& ray, int part) const
{
double dist = 0;
if(part >= 0){ //check specified part
if(debug_pixel){
std::cout << "entered mesh intersection" << std::endl;
}
if(Intersect_Triangle(ray, part, dist)){
return {this, dist, part};
}
}else{ //check against all parts and return intersected hit
for(unsigned i = 0; i < triangles.size(); ++i){
if(Intersect_Triangle(ray, i, dist)){
return {this, dist, (int)i};
}
}
return {NULL, 0, 0};
}
return {NULL, 0 , 0};
}
// Compute the normal direction for the triangle with index part.
vec3 Mesh::Normal(const vec3& point, int part) const
{
assert(part>=0);
vec3 a = vertices[triangles[part][0]];
vec3 b = vertices[triangles[part][1]];
vec3 c = vertices[triangles[part][2]];
vec3 ab = b - a; //get two edge vectors and calculate cross product for the normal
vec3 ac = c - a;
if(debug_pixel){
std::cout << "a: " << a << " b: " << b << " c: " << c <<std::endl;
std::cout << "ab: " << ab << " ac: " << ac << std::endl;
std::cout << "normal: " << cross(ab, ac).normalized() << std::endl;
}
return cross(ab, ac).normalized();
}
// This is a helper routine whose purpose is to simplify the implementation
// of the Intersection routine. It should test for an intersection between
// the ray and the triangle with index tri. If an intersection exists,
// record the distance and return true. Otherwise, return false.
// This intersection should be computed by determining the intersection of
// the ray and the plane of the triangle. From this, determine (1) where
// along the ray the intersection point occurs (dist) and (2) the barycentric
// coordinates within the triangle where the intersection occurs. The
// triangle intersects the ray if dist>small_t and the barycentric weights are
// larger than -weight_tolerance. The use of small_t avoid the self-shadowing
// bug, and the use of weight_tolerance prevents rays from passing in between
// two triangles.
bool Mesh::Intersect_Triangle(const Ray& ray, int tri, double& dist) const
{
TODO;
vec3 x(0, 0, 0);
ivec3 triangle = triangles[tri];
vec3 normal = Normal(x, tri);
vec3 a, b, c, ab, ac;
a = vertices[triangle[0]];
b = vertices[triangle[1]];
c = vertices[triangle[2]];
ab = b - a; //get two edge vectors
ac = c - a;
//calculate if ray intersects triangle.
double dotp = dot(ray.direction, normal);
if((dotp <= -1.0 * small_t || dotp >= small_t) && dot((a - ray.endpoint), normal) / dot(ray.direction, normal) >= small_t){ //ray intersects plane created by the triangle.
double t = (dot(a - ray.endpoint, normal)) / dot(ray.direction, normal);
vec3 intersection_point = ray.endpoint + t * ray.direction; // this is point p for barycentric coordinates
vec3 w = intersection_point - a;
double bet, gam;
bet = dot(w, cross(normal, ac)) / dot(ab, cross(normal, ac));
gam = dot(w, cross(normal, ab)) / dot(ac, cross(normal, ab));
if(bet > -weight_tolerance && gam > -weight_tolerance && (1 - bet - gam) > -weight_tolerance){
dist = t;
return true;
}
}else{
return false;
}
return false;
}
// Compute the bounding box. Return the bounding box of only the triangle whose
// index is part.
Box Mesh::Bounding_Box(int part) const
{
Box b;
TODO;
return b;
}
|
4c4205c2cd8edbc682510be15cf589d706dc30a1 | ad408c6244d3474d7631acbbf38476a16ff80730 | /LaonSill/src/sess/MessageHeader.h | 8d1a7acc2c724bff9d7be5b8a9753b2fc41a5aed | [
"Apache-2.0"
] | permissive | alice965/LaonSillv2 | e229cc9351bd4befb23a50820108f489125e18e7 | 826f664d5fd8a8625f2abfb9cd566e4f700c16d1 | refs/heads/main | 2023-02-16T16:57:06.699971 | 2020-11-30T06:44:43 | 2020-11-30T06:44:43 | 354,684,554 | 1 | 0 | null | 2021-04-05T01:25:49 | 2021-04-05T01:25:43 | null | UTF-8 | C++ | false | false | 1,511 | h | MessageHeader.h | /**
* @file MessageHeader.h
* @date 2016-10-20
* @author moonhoen lee
* @brief
* @details
*/
#ifndef MESSAGEHEADER_H
#define MESSAGEHEADER_H
#include "common.h"
// Serialize시 packet 구성
// |---------+--------+------------------------------------------|
// | MsgType | MsgLen | MsgBody |
// | int(4) | int(4) | variable size => MsgLen - 8 byte |
// |---------+--------+------------------------------------------|
// |<-- msg header -->|
class MessageHeader {
public:
static const int MESSAGE_HEADER_SIZE = 8;
static const int MESSAGE_DEFAULT_SIZE = 1452;
// usual MTU size(1500) - IP header(20) - TCP header(20) - vpn header(8)
// 물론 MTU 크기를 변경하면 더 큰값을 설정해도 된다..
// 하지만.. 다른 네트워크의 MTU 크기가 작다면 성능상 문제가 발생할 수 밖에 없다.
enum MsgType : int {
Welcome = 0,
WelcomeReply,
PushJob = 10,
PushJobReply,
GoodBye = 90,
HaltMachine = 100,
};
MessageHeader() {}
virtual ~MessageHeader() {}
int getMsgLen() { return this->msgLen; }
MsgType getMsgType() { return this->msgType; }
void setMsgType(MsgType msgType) { this->msgType = msgType; }
void setMsgLen(int msgLen) { this->msgLen = msgLen; }
private:
MsgType msgType;
int msgLen;
};
#endif /* MESSAGEHEADER_H */
|
3b57ed334754cc287c44c3da46681c5cb10e0a6a | 310f141298e1ef654cc0bf008f3d7302d204bf15 | /main.cpp | 181b5858a486e63b5fb5fc7afa8a9bba09ebf6a6 | [] | no_license | AnaCrisOliver/System_API | dc5217e6f7ddeade1d5ebbe8ab1f6f4785949482 | 3590b477f3e15bd25cc80ed412590c39d8533f52 | refs/heads/master | 2023-04-12T00:46:08.535354 | 2021-04-28T21:32:51 | 2021-04-28T21:32:51 | 186,177,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp | main.cpp | #include <iostream>
#include "system.h"
#include "systemimpl.h"
#include "modelimpl.h"
#include "flowimpl.h"
#include "systemimpltest.h"
#include "modelimpltest.h"
using namespace std;
int main()
{
SystemImplTest test1;
ModelImplTest test2;
System *s = new SystemImpl();
test1.unit_set_energy();
test1.unit_get_energy();
test1.unit_constructor();
test2.unit_add_flow();
test2.unit_add_system();
test2.unit_remove_flow();
test2.unit_remove_system();
cout << "Hello World!" << endl;
return 0;
}
|
81b7c584227a5d01fff7102df250a08b64ab0fe2 | 9c3f589331082b47ac3cba22e199a377c39ce186 | /stickman_drawer/stickman.hpp | 30e3fcd7a64174c2e1c5743c729abf60543fc565 | [
"MIT"
] | permissive | JustLuoxi/textured_avatars | 204bc7b1c1c3292e81fa8cf8e520bc8810da33c0 | 114e94e92ee0a84e2757a4223edfe8b2b4de3ec5 | refs/heads/master | 2022-04-27T03:57:15.148538 | 2020-03-20T18:50:11 | 2020-03-20T18:50:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,808 | hpp | stickman.hpp | #include <iostream>
#include "lists.hpp"
#include <math.h>
#include <algorithm>
#include <array>
//#define GLOBAL_Z_MIN 100
//#define GLOBAL_Z_MAX 500
using namespace std;
struct PointT {
float x, y;
};
struct LineT {
float x1, x2, y1, y2, z1, z2;
};
class StickmanData_C {
int _n = 4;
// int _len[4]={19,70,21,21};
int _shift3[4] = {0, 19 * 3, 19 * 3 + 70 * 3, 19 * 3 + 70 * 3 + 21 * 3};
int _shift4[4] = {0, 19 * 4, 19 * 4 + 70 * 4, 19 * 4 + 70 * 4 + 21 * 4};
std::string _fields[4] = {"pose_keypoints_3d", "face_keypoints_3d", "hand_left_keypoints_3d",
"hand_right_keypoints_3d"};
std::vector<bool> _valid;
std::vector<float> _extracted_data;
float _faceMean = 0.0f;
std::vector<std::vector<int>> pose_edge_list;
int pose_edges_num;
int face_edges_num;
std::vector<std::vector<int>> face_edge_list;
int hand_map_num, face_map_num;
public:
std::vector<float> _data;
bool is_07, is_separate_hands, is_separate_face, is_earneck, draw_face_pupils, draw_face_contour, draw_face_inner_mouth;
int global_z_min, global_z_max;
StickmanData_C(
bool is_07=true, bool is_separate_hands=false, bool is_separate_face=false, bool is_earneck=false,
bool draw_face_pupils=false, bool draw_face_contour=false, bool draw_face_inner_mouth=false,
int global_z_min=100, int global_z_max=500) : is_07(is_07),
is_separate_hands(is_separate_hands),
is_separate_face(is_separate_face),
is_earneck(is_earneck),
draw_face_pupils(draw_face_pupils),
draw_face_contour(draw_face_contour),
draw_face_inner_mouth(draw_face_inner_mouth),
global_z_min(global_z_min),
global_z_max(global_z_max) {
pose_edges_num = -1;
const index_pair *pose_arr_ptr;
if (!is_07) {
for (int i = 1; i < 4; i++) {
_shift3[i] += 6 * 3;
_shift4[i] += 6 * 4;
}
pose_edges_num = pose_edges_num_12;
pose_arr_ptr = &(pose_edge_list_12[0]);
if (is_earneck) {
pose_edges_num = pose_edges_num_12_earneck;
pose_arr_ptr = &(pose_edge_list_12_earneck[0]);
}
} else {
pose_edges_num = pose_edges_num_07;
pose_arr_ptr = &(pose_edge_list_07[0]);
if (is_earneck) {
pose_edges_num = pose_edges_num_07_earneck;
pose_arr_ptr = &(pose_edge_list_07_earneck[0]);
}
}
for (int i = 0; i < pose_edges_num; i++) {
std::vector<int> edge_pair;
for (int j = 0; j < 2; j++) {
edge_pair.push_back(pose_arr_ptr[i][j]);
}
pose_edge_list.push_back(edge_pair);
}
face_edges_num = face_inner_edges_num;
const index_pair * face_inner_arr_ptr = &(face_inner_edge_list[0]);
for (int i = 0; i < face_inner_edges_num; i++)
{
std::vector<int> edge_pair;
for (int j = 0; j < 2; j++) {
edge_pair.push_back(face_inner_arr_ptr[i][j]);
}
face_edge_list.push_back(edge_pair);
}
if (draw_face_pupils)
{
face_edges_num += face_pupils_edges_num;
const index_pair * face_pupils_arr_ptr = &(face_pupils_edge_list[0]);
for (int i = 0; i < face_pupils_edges_num; i++)
{
std::vector<int> edge_pair;
for (int j = 0; j < 2; j++) {
edge_pair.push_back(face_pupils_arr_ptr[i][j]);
}
face_edge_list.push_back(edge_pair);
}
}
if (draw_face_contour)
{
face_edges_num += face_contour_edges_num;
const index_pair * face_contour_arr_ptr = &(face_contour_edge_list[0]);
for (int i = 0; i < face_contour_edges_num; i++)
{
std::vector<int> edge_pair;
for (int j = 0; j < 2; j++) {
edge_pair.push_back(face_contour_arr_ptr[i][j]);
}
face_edge_list.push_back(edge_pair);
}
}
if (draw_face_inner_mouth)
{
face_edges_num += face_inner_mouth_edges_num;
const index_pair * face_inner_mouth_arr_ptr = &(face_inner_mouth_edge_list[0]);
for (int i = 0; i < face_inner_mouth_edges_num; i++)
{
std::vector<int> edge_pair;
for (int j = 0; j < 2; j++) {
edge_pair.push_back(face_inner_mouth_arr_ptr[i][j]);
}
face_edge_list.push_back(edge_pair);
}
}
if (is_separate_hands)
{
hand_map_num = hand_edges_num;
} else {
hand_map_num = 1;
}
if (is_separate_face) {
face_map_num = face_edges_num;
} else {
face_map_num = 1;
}
}
~StickmanData_C() {}
int size() {
return _data.size();
}
int extracted_size() {
return _extracted_data.size();
}
float get(int i) {
return _data[i];
}
float get_extracted(int i) {
return _extracted_data[i];
}
float *data() {
return _data.data();
}
bool valid(int i) {
return _valid[i];
}
float calcFaceMean() {
float res = 0.0f;
float cnt = 0.0;
for (int i = 0; i < 70; ++i) {
if (_extracted_data[i * 3 + _shift3[1]] > 0) {
res += _extracted_data[i * 3 + _shift3[1] + 2];
cnt += 1.0;
}
}
res /= cnt;
_faceMean = res;
return res;
}
void print() {
std::cout << size() << "\n";
std::cout << "_data_size " << size() << "\n";
std::cout << "_data" << "\n";
for (int i = 0; i + 3 < size(); i += 4)
std::cout << _data[i] << "\t" << _data[i + 1] << "\t" << _data[i + 2] << "\t" << _data[i + 3] << "\n";
std::cout << "_extracted_data_size " << extracted_size() << "\n";
std::cout << "_extracted_data" << "\n";
for (int i = 0; i + 2 < extracted_size(); i += 3)
std::cout << _extracted_data[i] << "\t" << _extracted_data[i + 1] << "\t" << _extracted_data[i + 2] << "\n";
}
void add_hand(int j, float thre, int *edges_num, float *input) {
// thre=kp_threshold;//0.0f;
for (int i_f = 0; i_f < edges_num[j] / 4; ++i_f) //if - number of a finger
{
bool add_finger = true;
for (int i = 4 * i_f; i < 4 * i_f + 4; i++) {
int idx1 = hand_edge_list[i][0];
int idx2 = hand_edge_list[i][1];
float conf1 = input[idx1 * 4 + 3 + _shift4[j]];
float conf2 = input[idx2 * 4 + 3 + _shift4[j]];
if ((conf1 < thre) || (conf2 < thre)) {
add_finger = false;
}
}
if (!add_finger) {
continue;
}
for (int i = 4 * i_f; i < 4 * i_f + 4; i++) {
int idx1 = hand_edge_list[i][0];
int idx2 = hand_edge_list[i][1];
_valid[i + _shift4[j] / 4] = true;
_extracted_data[idx1 * 3 + _shift3[j]] = input[idx1 * 4 +
_shift4[j]]; //insert values
_extracted_data[idx1 * 3 + _shift3[j] + 1] = input[idx1 * 4 + _shift4[j] + 1];
_extracted_data[idx1 * 3 + _shift3[j] + 2] = input[idx1 * 4 + _shift4[j] + 2];
_extracted_data[idx2 * 3 + _shift3[j]] = input[idx2 * 4 +
_shift4[j]]; //insert values
_extracted_data[idx2 * 3 + _shift3[j] + 1] = input[idx2 * 4 + _shift4[j] + 1];
_extracted_data[idx2 * 3 + _shift3[j] + 2] = input[idx2 * 4 + _shift4[j] + 2];
}
}
}
void extract_valid_keypoints(float kp_threshold, float *input, int sz) {
_extracted_data.clear();
_valid.clear();
_extracted_data.resize(3 * (sz / 4));
_valid.resize(pose_edges_num + face_edges_num + hand_edges_num + hand_edges_num);
fill(_valid.begin(), _valid.end(), false);
fill(_extracted_data.begin(), _extracted_data.end(), 0.0f);
float thre = kp_threshold;//0.0f;
int edges_num[4] = {pose_edges_num, face_edges_num, hand_edges_num, hand_edges_num};
int j = 0;
for (int i = 0; i < edges_num[j]; ++i) {
int idx1 = pose_edge_list[i][0];
int idx2 = pose_edge_list[i][1];
float conf1 = input[idx1 * 4 + 3 + _shift4[j]];
float conf2 = input[idx2 * 4 + 3 + _shift4[j]];
if ((conf1 > thre) && (conf2 > thre)) {
_valid[i + _shift4[j] / 4] = true;
_extracted_data[idx1 * 3 + _shift3[j]] = input[idx1 * 4 +
_shift4[j]]; //insert values
_extracted_data[idx1 * 3 + _shift3[j] + 1] = input[idx1 * 4 + _shift4[j] + 1];
_extracted_data[idx1 * 3 + _shift3[j] + 2] = input[idx1 * 4 + _shift4[j] + 2];
_extracted_data[idx2 * 3 + _shift3[j]] = input[idx2 * 4 +
_shift4[j]]; //insert values
_extracted_data[idx2 * 3 + _shift3[j] + 1] = input[idx2 * 4 + _shift4[j] + 1];
_extracted_data[idx2 * 3 + _shift3[j] + 2] = input[idx2 * 4 + _shift4[j] + 2];
}
}
j = 1;
thre = 0.0;
for (int i = 0; i < edges_num[j]; ++i) {
//std::cout<<i<<"\n";
int idx1 = face_edge_list[i][0];
int idx2 = face_edge_list[i][1];
float conf1 = input[idx1 * 4 + 3 + _shift4[j]];
float conf2 = input[idx2 * 4 + 3 + _shift4[j]];
if ((conf1 > thre) && (conf2 > thre)) {
_valid[i + _shift4[j] / 4] = true;
_extracted_data[idx1 * 3 + _shift3[j]] = input[idx1 * 4 +
_shift4[j]]; //insert values
_extracted_data[idx1 * 3 + _shift3[j] + 1] = input[idx1 * 4 + _shift4[j] + 1];
_extracted_data[idx1 * 3 + _shift3[j] + 2] = input[idx1 * 4 + _shift4[j] + 2];
_extracted_data[idx2 * 3 + _shift3[j]] = input[idx2 * 4 +
_shift4[j]]; //insert values
_extracted_data[idx2 * 3 + _shift3[j] + 1] = input[idx2 * 4 + _shift4[j] + 1];
_extracted_data[idx2 * 3 + _shift3[j] + 2] = input[idx2 * 4 + _shift4[j] + 2];
}
}
j = 2;
add_hand(j, kp_threshold, edges_num, input);
j = 3;
add_hand(j, kp_threshold, edges_num, input);
}
bool getLineCoords(int i, LineT &result) {
if (i < pose_edges_num) {
result.x1 = _extracted_data[3 * pose_edge_list[i][0] + _shift3[0]];
result.y1 = _extracted_data[3 * pose_edge_list[i][0] + _shift3[0] + 1];
result.x2 = _extracted_data[3 * pose_edge_list[i][1] + _shift3[0]];
result.y2 = _extracted_data[3 * pose_edge_list[i][1] + _shift3[0] + 1];
result.z1 = _extracted_data[3 * pose_edge_list[i][0] + _shift3[0] + 2];
result.z2 = _extracted_data[3 * pose_edge_list[i][1] + _shift3[0] + 2];
return (result.x1 > 0 && result.x2 > 0);
}
i -= pose_edges_num;
if (i < face_edges_num) {
result.x1 = _extracted_data[3 * face_edge_list[i][0] + _shift3[1]];
result.y1 = _extracted_data[3 * face_edge_list[i][0] + _shift3[1] + 1];
result.x2 = _extracted_data[3 * face_edge_list[i][1] + _shift3[1]];
result.y2 = _extracted_data[3 * face_edge_list[i][1] + _shift3[1] + 1];
result.z1 = _extracted_data[3 * face_edge_list[i][0] + _shift3[1] + 2];
result.z2 = _extracted_data[3 * face_edge_list[i][1] + _shift3[1] + 2];
return (result.x1 > 0 && result.x2 > 0);
}
i -= face_edges_num;
if (i < hand_edges_num) {
result.x1 = _extracted_data[3 * hand_edge_list[i][0] + _shift3[2]];
result.y1 = _extracted_data[3 * hand_edge_list[i][0] + _shift3[2] + 1];
result.x2 = _extracted_data[3 * hand_edge_list[i][1] + _shift3[2]];
result.y2 = _extracted_data[3 * hand_edge_list[i][1] + _shift3[2] + 1];
result.z1 = _extracted_data[3 * hand_edge_list[i][0] + _shift3[2] + 2];
result.z2 = _extracted_data[3 * hand_edge_list[i][1] + _shift3[2] + 2];
return (result.x1 > 0 && result.x2 > 0);
}
i -= hand_edges_num;
if (i < hand_edges_num) {
result.x1 = _extracted_data[3 * hand_edge_list[i][0] + _shift3[3]];
result.y1 = _extracted_data[3 * hand_edge_list[i][0] + _shift3[3] + 1];
result.x2 = _extracted_data[3 * hand_edge_list[i][1] + _shift3[3]];
result.y2 = _extracted_data[3 * hand_edge_list[i][1] + _shift3[3] + 1];
result.z1 = _extracted_data[3 * hand_edge_list[i][0] + _shift3[3] + 2];
result.z2 = _extracted_data[3 * hand_edge_list[i][1] + _shift3[3] + 2];
return (result.x1 > 0 && result.x2 > 0);
} else
return false;
}
float distance(float x0, float y0, float x1, float y1, float x, float y) {
if ((x0 == x1) && (y0 == y1))
return (sqrtf(powf(x0 - x, 2.0f) + powf(y0 - y, 2.0f)));
float numenator, denomenator;
numenator = (y0 - y1) * x + (x1 - x0) * y + (x0 * y1 - x1 * y0);
denomenator = sqrtf(powf(x1 - x0, 2.0f) + powf(y1 - y0, 2.0f));
return (fabsf(numenator / denomenator));
}
int clip(int x, int maxval) {
return std::max(std::min(x, maxval), 0);
}
int mmin(int x1, int x2, int bw) {
return min(x1, x2) - bw - 1;
}
int mmax(int x1, int x2, int bw) {
return max(x1, x2) + bw + 1;
}
void drawLine(const LineT &line, int channel, float bw, int w, int h, float val, float *output) {
int x1i = (int) floor(line.x1 + 0.5);
int y1i = (int) floor(line.y1 + 0.5);
int x2i = (int) floor(line.x2 + 0.5);
int y2i = (int) floor(line.y2 + 0.5);
float n[3];
n[0] = y1i - y2i;
n[1] = x2i - x1i;
n[2] = (x1i * y2i - x2i * y1i);
float s = sqrtf(n[0] * n[0] + n[1] * n[1]);
float deps = 1e-5;
n[0] /= (s + deps);
n[1] /= (s + deps);
n[2] /= (s + deps);
int bwi = (int) (bw + 1.0);
int fromi = clip(mmin(x1i, x2i, bwi), w);
int toi = clip(mmax(x1i, x2i, bwi), w);
int fromj = clip(mmin(y1i, y2i, bwi), h);
int toj = clip(mmax(y1i, y2i, bwi), h);
// std::cout << fromi << " " << toi << " " << fromj << " " << toj << " " << std::endl;
for (int j = fromj; j < toj; j++) {
for (int i = fromi; i < toi; i++) {
float signed_dist = i * n[0] + j * n[1] + n[2];
float dist_val = fabs(signed_dist);
float p_x = i - n[0] * signed_dist;
float p_y = j - n[1] * signed_dist;
if (dist_val >= bw + 1.0) {
continue;
}
if ((p_x - line.x1) * (p_x - line.x2) + (p_y - line.y1) * (p_y - line.y2) > 0) {
float d1 = sqrt((i - line.x1) * (i - line.x1) + (j - line.y1) * (j - line.y1));
float d2 = sqrt((i - line.x2) * (i - line.x2) + (j - line.y2) * (j - line.y2));
float ep_dist_val = std::min(d1, d2);
if (ep_dist_val >= bw + 1.0) {
continue;
}
dist_val = ep_dist_val;
}
int addr = i + j * w + channel * w * h;
if (dist_val <= bw) {
output[addr] = val;
} else {
if (dist_val < bw + 1.0) {
float gamma = bw + 1.0 - dist_val;
output[addr] = gamma * val + (1 - gamma) * output[addr];
}
}
}
}
}
void drawPose2(float *output, int w, int h, float bw = 3) {
LineT line;
for (int edge = 0; edge < pose_edges_num; ++edge) {
if (getLineCoords(edge, line)) {
float mean = (line.z1 + line.z2) / 2.0f;
drawLine(line, edge, bw, w, h, mean, output);
}
}
}
void drawPose(float *output, int w, int h, int bw = 3) {
LineT line;
for (int edge = 0; edge < pose_edges_num; ++edge) {
if (getLineCoords(edge, line)) {
int fromi = min(line.x1, line.x2);
int toi = max(line.x1, line.x2);
int fromj = min(line.y1, line.y2);
int toj = max(line.y1, line.y2);
float mean = (line.z1 + line.z2) / 2.0f;
for (int j = fromj; j <= toj; ++j) {
for (int i = fromi; i <= toi; ++i) {
#pragma unroll
for (int jp = -bw; jp <= bw; ++jp) {
#pragma unroll
for (int ip = -bw; ip <= bw; ++ip) {
if ((j + jp < 0) || (j + jp >= h) || (i + ip < 0) || (i + ip >= w))
continue;
else {
if (distance(line.x1, line.y1, line.x2, line.y2, i + ip, j + jp) <= bw) {
output[(i + ip + (j + jp) * w) + edge * w * h] = mean;//color[0];
//output[(i+ip+(j+jp)*w)+1+edge*w*h]=mean;//color[1];
//output[(i+ip+(j+jp)*w)+2+edge*w*h]=mean;//color[2];
}
}
}
}
}
}
}
}
}
void drawFace2(float *output, int w, int h, float bw = 3) {
calcFaceMean();
LineT line;
for (int edge = 0; edge < face_edges_num; ++edge) {
if (getLineCoords(edge + pose_edges_num, line)) {
// std::cout << pose_edges_num+2*hand_map_num << std::endl;
if (is_separate_face) {
drawLine(line, pose_edges_num + 2 * hand_map_num + edge, bw, w, h, _faceMean, output);
} else {
drawLine(line, pose_edges_num + 2 * hand_map_num, bw, w, h, _faceMean, output);
}
}
}
}
void drawFace(float *output, int w, int h, int bw = 3) {
calcFaceMean();
LineT line;
for (int edge = 0; edge < face_edges_num; ++edge) {
if (getLineCoords(edge + pose_edges_num, line)) {
int fromi = min(line.x1, line.x2);
int toi = max(line.x1, line.x2);
int fromj = min(line.y1, line.y2);
int toj = max(line.y1, line.y2);
for (int j = fromj; j <= toj; ++j) {
for (int i = fromi; i <= toi; ++i) {
#pragma unroll
for (int jp = -bw; jp <= bw; ++jp) {
#pragma unroll
for (int ip = -bw; ip <= bw; ++ip) {
if ((j + jp < 0) || (j + jp >= h) || (i + ip < 0) || (i + ip >= w))
continue;
else {
if (distance(line.x1, line.y1, line.x2, line.y2, i + ip, j + jp) <= bw) {
output[(i + ip + (j + jp) * w) +
(pose_edges_num + 2) * w * h] = _faceMean;//color[0];
//output[(i+ip+(j+jp)*w)+1+(pose_edges_num+2)*w*h]=_faceMean;//color[1];
// output[(i+ip+(j+jp)*w)+2+(pose_edges_num+2)*w*h]=_faceMean;//color[2];
}
}
}
}
}
}
}
}
}
void drawHands(float *output, int w, int h, int bw = 1) {
LineT line;
#pragma unroll
for (int ha = 0; ha < 2; ++ha) {
for (int edge = 0; edge < hand_edges_num; ++edge) {
int l = edge + pose_edges_num + face_edges_num;
if (ha > 0)
l += hand_edges_num;
if (getLineCoords(l, line)) {
int fromi = min(line.x1, line.x2);
int toi = max(line.x1, line.x2);
int fromj = min(line.y1, line.y2);
int toj = max(line.y1, line.y2);
float mean = (line.z1 + line.z2) / 2.0f;
for (int j = fromj; j <= toj; ++j) {
for (int i = fromi; i <= toi; ++i) {
#pragma unroll
for (int jp = -bw; jp <= bw; ++jp) {
#pragma unroll
for (int ip = -bw; ip <= bw; ++ip) {
if ((j + jp < 0) || (j + jp >= h) || (i + ip < 0) || (i + ip >= w))
continue;
else {
if (distance(line.x1, line.y1, line.x2, line.y2, i + ip, j + jp) <= bw) {
output[(i + ip + (j + jp) * w) +
(pose_edges_num + ha) * w * h] = mean;//color[0];
// output[(i+ip+(j+jp)*w)+1+(pose_edges_num+ha)*w*h]=mean;//color[1];
// output[(i+ip+(j+jp)*w)+2+(pose_edges_num+ha)*w*h]=mean;//color[2];
}
}
}
}
}
}
}
}
}
}
void drawHands2(float *output, int w, int h, float bw = 1) {
LineT line;
#pragma unroll
for (int ha = 0; ha < 2; ++ha) {
for (int edge = 0; edge < hand_edges_num; ++edge) {
int l = edge + pose_edges_num + face_edges_num;
if (ha > 0)
l += hand_edges_num;
if (getLineCoords(l, line)) {
float mean = (line.z1 + line.z2) / 2.0f;
if (is_separate_hands) {
drawLine(line, pose_edges_num + ha * hand_edges_num + edge, bw, w, h, mean, output);
} else {
drawLine(line, pose_edges_num + ha, bw, w, h, mean, output);
}
}
}
}
}
void drawStickman(float *output, int sz1, float *input, int sz2, int w, int h, int lineWidthPose = 3,
int lineWidthFaceHand = 3) {
int minDepth = input[2];
int maxDepth = input[2];
_data.resize(w * h);
for (int i = 0; i + 2 < sz2; i += 4) {
_data[i] = input[i];
_data[i + 1] = input[i + 1];
_data[i + 2] = input[i + 2];
_data[i + 3] = input[i + 3];
// if (minDepth>input[i+2])
// minDepth=input[i+2];
// if (maxDepth<input[i+2])
// maxDepth=input[i+2];
}
// float norm=maxDepth=0.0f;
// if (fabsf(maxDepth-minDepth)<1e-6)
// norm=maxDepth;
// else
// norm=maxDepth-minDepth;
for (int i = 0; i + 2 < sz2; i += 4) {
float temp = std::min(std::max((_data[i + 2] - global_z_min) / (global_z_max - global_z_min), (float) 0.0),
(float) 1.0) * 255;
_data[i + 2] = temp;
}
extract_valid_keypoints(0.05f, data(), sz2);
drawPose(output, w, h, lineWidthPose);
drawFace(output, w, h, lineWidthFaceHand);
drawHands(output, w, h, lineWidthFaceHand);
}
void drawStickman2(float *output, int sz1, float *input, int sz2, int w, int h, float lineWidthPose = 3,
float lineWidthFaceHand = 3) {
_data.resize(sz2);
for (int i = 0; i + 2 < sz2; i += 4) {
_data[i] = input[i];
_data[i + 1] = input[i + 1];
_data[i + 2] = input[i + 2];
_data[i + 3] = input[i + 3];
}
for (int i = 0; i + 2 < sz2; i += 4) {
float temp = std::min(std::max((_data[i + 2] - global_z_min) / (global_z_max - global_z_min), (float) 0.0),
(float) 1.0) * 255;
_data[i + 2] = temp;
}
extract_valid_keypoints(0.05f, data(), sz2);
// std::cout << " output size " << sz1 << std::endl;
// std::cout << "extracted keypoints " << std::endl;
drawPose2(output, w, h, lineWidthPose);
// std::cout << "drawn pose " << std::endl;
drawFace2(output, w, h, lineWidthFaceHand);
// std::cout << "drawn face " << std::endl;
drawHands2(output, w, h, lineWidthFaceHand);
// std::cout << "drawn hands " << std::endl;
}
};
|
74861f53012185d453f55527c178cc7c5fb70e0c | f8d4611e0d37cbe7a3fda574a2ffa338fc954486 | /Source/CatSandbox/Http/HttpRequest.h | 00bcb5c2eb909320d850781847879e2e6b421c9e | [] | no_license | blockspacer/UnrealEngineExamples | 15424bfad20373f8409d6d962a35802d2fbe043a | 88b4d75fbbaa9189d391317e76c38457f57d4e7f | refs/heads/master | 2021-01-05T07:30:53.806583 | 2018-07-02T12:45:10 | 2018-07-02T12:45:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,195 | h | HttpRequest.h | #pragma once
#include "Object.h"
#include "Runtime/Online/HTTP/Public/Http.h"
#include "HttpResponse.h"
#include "HttpRequest.generated.h"
UCLASS(BlueprintType, Blueprintable)
class CATSANDBOX_API UHttpRequest : public UObject
{
GENERATED_BODY()
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FHttpResponseDelegate, UHttpResponse*, Response);
DECLARE_MULTICAST_DELEGATE_OneParam(FHttpResponseDelegateNonDynamic, UHttpResponse*);
public:
UPROPERTY(BlueprintAssignable, Category = "Http|EventDispatchers")
FHttpResponseDelegate OnResponseDelegate;
FHttpResponseDelegateNonDynamic OnResponseReceivedDelegate;
bool IsExpired();
void Setup(TSharedPtr<IHttpRequest> internalRequest);
UFUNCTION(BlueprintCallable, Category = "HTTP")
void Send();
UFUNCTION(BlueprintCallable, Category = "HTTP")
UHttpRequest* WithHeader(FString headerName, FString headerValue);
UFUNCTION(BlueprintCallable, Category = "HTTP")
UHttpRequest* WithPayload(FString payload);
private:
TSharedPtr<IHttpRequest> _internalRequest;
void Resolve(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
bool _isResolved = false;
};
|
37215d43cf60089cc7cb6d94272726d179230849 | ff142cfb461d748846fab7a9779b6c2ab9fd29d0 | /src/chrono/physics/ChLinkLinActuator.h | c92fab5dd357df9a59d05548eb5421a0762c8fd4 | [
"BSD-3-Clause"
] | permissive | cecilysunday/chrono | f739749153d40973c262c5b060b1a7af7c5ce127 | 903463bd5b71aaba052d3981eb6ca8bf3c3eab4f | refs/heads/develop | 2022-10-17T05:48:56.406791 | 2022-05-04T16:00:10 | 2022-05-04T16:00:10 | 154,656,858 | 3 | 0 | BSD-3-Clause | 2020-11-04T17:47:40 | 2018-10-25T11:07:38 | C++ | UTF-8 | C++ | false | false | 4,268 | h | ChLinkLinActuator.h | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora, Radu Serban
// =============================================================================
#ifndef CHLINKLINACTUATOR_H
#define CHLINKLINACTUATOR_H
#include "chrono/physics/ChLinkLock.h"
namespace chrono {
/// Class for linear actuators between two markers,
/// as the actuator were joined with two spherical
/// bearing at the origin of the two markers.
/// **NOTE! THIS IS OBSOLETE**. Prefer using the new classes
/// inherited from chrono::ChLinkMotor.
class ChApi ChLinkLinActuator : public ChLinkLockLock {
protected:
std::shared_ptr<ChFunction> dist_funct; ///< distance function
bool learn; ///< if true, the actuator does not apply constraint, just records the motion into its dist_function.
bool learn_torque_rotation; ///< if true, the actuator records the torque and rotation.
double offset; ///< distance offset
double mot_tau; ///< motor: transmission ratio
double mot_eta; ///< motor: transmission efficiency
double mot_inertia; ///< motor: inertia (added to system)
std::shared_ptr<ChFunction> mot_torque; ///< motor: recorder of torque
std::shared_ptr<ChFunction> mot_rot; ///< motor: recorder of motor rotation
double mot_rerot; ///< current rotation (read only) before reducer
double mot_rerot_dt; ///< current ang speed (read only) before reducer
double mot_rerot_dtdt; ///< current ang acc (read only) before reducer
double mot_retorque; ///< current motor torque (read only) before reducer
public:
ChLinkLinActuator();
ChLinkLinActuator(const ChLinkLinActuator& other);
virtual ~ChLinkLinActuator() {}
/// "Virtual" copy constructor (covariant return type).
virtual ChLinkLinActuator* Clone() const override { return new ChLinkLinActuator(*this); }
// Updates motion laws, marker positions, etc.
virtual void UpdateTime(double mytime) override;
// data get/set
std::shared_ptr<ChFunction> Get_dist_funct() const { return dist_funct; }
std::shared_ptr<ChFunction> Get_motrot_funct() const { return mot_rot; }
std::shared_ptr<ChFunction> Get_mottorque_funct() const { return mot_torque; }
void Set_dist_funct(std::shared_ptr<ChFunction> mf) { dist_funct = mf; }
void Set_motrot_funct(std::shared_ptr<ChFunction> mf) { mot_rot = mf; }
void Set_mottorque_funct(std::shared_ptr<ChFunction> mf) { mot_torque = mf; }
bool Get_learn() const { return learn; }
void Set_learn(bool mset);
bool Get_learn_torque_rotaton() const { return learn_torque_rotation; }
void Set_learn_torque_rotaton(bool mset);
double Get_lin_offset() const { return offset; };
void Set_lin_offset(double mset) { offset = mset; }
void Set_mot_tau(double mtau) { mot_tau = mtau; }
double Get_mot_tau() const { return mot_tau; }
void Set_mot_eta(double meta) { mot_eta = meta; }
double Get_mot_eta() const { return mot_eta; }
void Set_mot_inertia(double min) { mot_inertia = min; }
double Get_mot_inertia() const { return mot_inertia; }
// easy fetching of motor-reduced moments or angle-speed-accel.
double Get_mot_rerot() const { return mot_rerot; }
double Get_mot_rerot_dt() const { return mot_rerot_dt; }
double Get_mot_rerot_dtdt() const { return mot_rerot_dtdt; }
double Get_mot_retorque() const { return mot_retorque; }
/// Method to allow serialization of transient data to archives.
virtual void ArchiveOUT(ChArchiveOut& marchive) override;
/// Method to allow deserialization of transient data from archives.
virtual void ArchiveIN(ChArchiveIn& marchive) override;
};
CH_CLASS_VERSION(ChLinkLinActuator,0)
} // end namespace chrono
#endif
|
e4b16a6af559308380beaf95724b89d188aed066 | 49891f785685ae24d60830d25a6275da7a792310 | /src/RcppExports.cpp | a0abccc2c913b5c5d7637656a731d294af6b63ba | [
"MIT"
] | permissive | rettopnivek/seqmodels | a8a7fb57fc22dac8fa12e093ef0ba82d3cbcc1b8 | 2fc1456074b030898f964f93d1edfb04191f198c | refs/heads/master | 2021-01-10T05:09:30.201092 | 2020-04-27T20:04:18 | 2020-04-27T20:04:18 | 52,176,011 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,324 | cpp | RcppExports.cpp | // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <Rcpp.h>
using namespace Rcpp;
// remg
Rcpp::NumericVector remg(int n, Rcpp::NumericVector mu, Rcpp::NumericVector sigma, Rcpp::NumericVector lambda);
RcppExport SEXP _seqmodels_remg(SEXP nSEXP, SEXP muSEXP, SEXP sigmaSEXP, SEXP lambdaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type n(nSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type mu(muSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type lambda(lambdaSEXP);
rcpp_result_gen = Rcpp::wrap(remg(n, mu, sigma, lambda));
return rcpp_result_gen;
END_RCPP
}
// demg
Rcpp::NumericVector demg(Rcpp::NumericVector x, Rcpp::NumericVector mu, Rcpp::NumericVector sigma, Rcpp::NumericVector lambda, bool ln);
RcppExport SEXP _seqmodels_demg(SEXP xSEXP, SEXP muSEXP, SEXP sigmaSEXP, SEXP lambdaSEXP, SEXP lnSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type x(xSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type mu(muSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type lambda(lambdaSEXP);
Rcpp::traits::input_parameter< bool >::type ln(lnSEXP);
rcpp_result_gen = Rcpp::wrap(demg(x, mu, sigma, lambda, ln));
return rcpp_result_gen;
END_RCPP
}
// pemg
Rcpp::NumericVector pemg(Rcpp::NumericVector q, Rcpp::NumericVector mu, Rcpp::NumericVector sigma, Rcpp::NumericVector lambda, bool ln, bool lower_tail);
RcppExport SEXP _seqmodels_pemg(SEXP qSEXP, SEXP muSEXP, SEXP sigmaSEXP, SEXP lambdaSEXP, SEXP lnSEXP, SEXP lower_tailSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type q(qSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type mu(muSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type lambda(lambdaSEXP);
Rcpp::traits::input_parameter< bool >::type ln(lnSEXP);
Rcpp::traits::input_parameter< bool >::type lower_tail(lower_tailSEXP);
rcpp_result_gen = Rcpp::wrap(pemg(q, mu, sigma, lambda, ln, lower_tail));
return rcpp_result_gen;
END_RCPP
}
// qemg
Rcpp::NumericVector qemg(Rcpp::NumericVector p, Rcpp::NumericVector mu, Rcpp::NumericVector sigma, Rcpp::NumericVector lambda, Rcpp::NumericVector bounds, double em_stop, double err);
RcppExport SEXP _seqmodels_qemg(SEXP pSEXP, SEXP muSEXP, SEXP sigmaSEXP, SEXP lambdaSEXP, SEXP boundsSEXP, SEXP em_stopSEXP, SEXP errSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type p(pSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type mu(muSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type lambda(lambdaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type bounds(boundsSEXP);
Rcpp::traits::input_parameter< double >::type em_stop(em_stopSEXP);
Rcpp::traits::input_parameter< double >::type err(errSEXP);
rcpp_result_gen = Rcpp::wrap(qemg(p, mu, sigma, lambda, bounds, em_stop, err));
return rcpp_result_gen;
END_RCPP
}
// memg
Rcpp::DataFrame memg(Rcpp::NumericVector mu, Rcpp::NumericVector sigma, Rcpp::NumericVector lambda);
RcppExport SEXP _seqmodels_memg(SEXP muSEXP, SEXP sigmaSEXP, SEXP lambdaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type mu(muSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type lambda(lambdaSEXP);
rcpp_result_gen = Rcpp::wrap(memg(mu, sigma, lambda));
return rcpp_result_gen;
END_RCPP
}
// dlevy
Rcpp::NumericVector dlevy(Rcpp::NumericVector x, Rcpp::NumericVector mu, Rcpp::NumericVector sigma, bool ln);
RcppExport SEXP _seqmodels_dlevy(SEXP xSEXP, SEXP muSEXP, SEXP sigmaSEXP, SEXP lnSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type x(xSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type mu(muSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< bool >::type ln(lnSEXP);
rcpp_result_gen = Rcpp::wrap(dlevy(x, mu, sigma, ln));
return rcpp_result_gen;
END_RCPP
}
// plevy
Rcpp::NumericVector plevy(Rcpp::NumericVector q, Rcpp::NumericVector mu, Rcpp::NumericVector sigma, bool lower_tail, bool ln);
RcppExport SEXP _seqmodels_plevy(SEXP qSEXP, SEXP muSEXP, SEXP sigmaSEXP, SEXP lower_tailSEXP, SEXP lnSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type q(qSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type mu(muSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< bool >::type lower_tail(lower_tailSEXP);
Rcpp::traits::input_parameter< bool >::type ln(lnSEXP);
rcpp_result_gen = Rcpp::wrap(plevy(q, mu, sigma, lower_tail, ln));
return rcpp_result_gen;
END_RCPP
}
// qlevy
Rcpp::NumericVector qlevy(Rcpp::NumericVector p, Rcpp::NumericVector mu, Rcpp::NumericVector sigma);
RcppExport SEXP _seqmodels_qlevy(SEXP pSEXP, SEXP muSEXP, SEXP sigmaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type p(pSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type mu(muSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
rcpp_result_gen = Rcpp::wrap(qlevy(p, mu, sigma));
return rcpp_result_gen;
END_RCPP
}
// rlevy
Rcpp::NumericVector rlevy(int n, Rcpp::NumericVector mu, Rcpp::NumericVector sigma);
RcppExport SEXP _seqmodels_rlevy(SEXP nSEXP, SEXP muSEXP, SEXP sigmaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type n(nSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type mu(muSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
rcpp_result_gen = Rcpp::wrap(rlevy(n, mu, sigma));
return rcpp_result_gen;
END_RCPP
}
// rinvgauss
Rcpp::NumericVector rinvgauss(int n, Rcpp::NumericVector kappa, Rcpp::NumericVector xi, Rcpp::NumericVector tau, Rcpp::NumericVector sigma);
RcppExport SEXP _seqmodels_rinvgauss(SEXP nSEXP, SEXP kappaSEXP, SEXP xiSEXP, SEXP tauSEXP, SEXP sigmaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type n(nSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type kappa(kappaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type xi(xiSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type tau(tauSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
rcpp_result_gen = Rcpp::wrap(rinvgauss(n, kappa, xi, tau, sigma));
return rcpp_result_gen;
END_RCPP
}
// dinvgauss
Rcpp::NumericVector dinvgauss(Rcpp::NumericVector t, Rcpp::NumericVector kappa, Rcpp::NumericVector xi, Rcpp::NumericVector tau, Rcpp::NumericVector sigma, bool ln);
RcppExport SEXP _seqmodels_dinvgauss(SEXP tSEXP, SEXP kappaSEXP, SEXP xiSEXP, SEXP tauSEXP, SEXP sigmaSEXP, SEXP lnSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type t(tSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type kappa(kappaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type xi(xiSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type tau(tauSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< bool >::type ln(lnSEXP);
rcpp_result_gen = Rcpp::wrap(dinvgauss(t, kappa, xi, tau, sigma, ln));
return rcpp_result_gen;
END_RCPP
}
// pinvgauss
Rcpp::NumericVector pinvgauss(Rcpp::NumericVector t, Rcpp::NumericVector kappa, Rcpp::NumericVector xi, Rcpp::NumericVector tau, Rcpp::NumericVector sigma, bool ln, bool lower_tail);
RcppExport SEXP _seqmodels_pinvgauss(SEXP tSEXP, SEXP kappaSEXP, SEXP xiSEXP, SEXP tauSEXP, SEXP sigmaSEXP, SEXP lnSEXP, SEXP lower_tailSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type t(tSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type kappa(kappaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type xi(xiSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type tau(tauSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< bool >::type ln(lnSEXP);
Rcpp::traits::input_parameter< bool >::type lower_tail(lower_tailSEXP);
rcpp_result_gen = Rcpp::wrap(pinvgauss(t, kappa, xi, tau, sigma, ln, lower_tail));
return rcpp_result_gen;
END_RCPP
}
// qinvgauss
Rcpp::NumericVector qinvgauss(Rcpp::NumericVector p, Rcpp::NumericVector kappa, Rcpp::NumericVector xi, Rcpp::NumericVector tau, Rcpp::NumericVector sigma, double bounds, double em_stop, double err);
RcppExport SEXP _seqmodels_qinvgauss(SEXP pSEXP, SEXP kappaSEXP, SEXP xiSEXP, SEXP tauSEXP, SEXP sigmaSEXP, SEXP boundsSEXP, SEXP em_stopSEXP, SEXP errSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type p(pSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type kappa(kappaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type xi(xiSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type tau(tauSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< double >::type bounds(boundsSEXP);
Rcpp::traits::input_parameter< double >::type em_stop(em_stopSEXP);
Rcpp::traits::input_parameter< double >::type err(errSEXP);
rcpp_result_gen = Rcpp::wrap(qinvgauss(p, kappa, xi, tau, sigma, bounds, em_stop, err));
return rcpp_result_gen;
END_RCPP
}
// minvgauss
Rcpp::DataFrame minvgauss(Rcpp::NumericVector kappa, Rcpp::NumericVector xi, Rcpp::NumericVector tau, Rcpp::NumericVector sigma);
RcppExport SEXP _seqmodels_minvgauss(SEXP kappaSEXP, SEXP xiSEXP, SEXP tauSEXP, SEXP sigmaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type kappa(kappaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type xi(xiSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type tau(tauSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
rcpp_result_gen = Rcpp::wrap(minvgauss(kappa, xi, tau, sigma));
return rcpp_result_gen;
END_RCPP
}
// dwiener
Rcpp::NumericVector dwiener(Rcpp::NumericVector rt, Rcpp::NumericVector ch, Rcpp::NumericVector alpha, Rcpp::NumericVector theta, Rcpp::NumericVector xi, Rcpp::NumericVector tau, Rcpp::NumericVector sigma, bool ln, bool joint, double eps, bool parYes);
RcppExport SEXP _seqmodels_dwiener(SEXP rtSEXP, SEXP chSEXP, SEXP alphaSEXP, SEXP thetaSEXP, SEXP xiSEXP, SEXP tauSEXP, SEXP sigmaSEXP, SEXP lnSEXP, SEXP jointSEXP, SEXP epsSEXP, SEXP parYesSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type rt(rtSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type ch(chSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type alpha(alphaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type theta(thetaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type xi(xiSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type tau(tauSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< bool >::type ln(lnSEXP);
Rcpp::traits::input_parameter< bool >::type joint(jointSEXP);
Rcpp::traits::input_parameter< double >::type eps(epsSEXP);
Rcpp::traits::input_parameter< bool >::type parYes(parYesSEXP);
rcpp_result_gen = Rcpp::wrap(dwiener(rt, ch, alpha, theta, xi, tau, sigma, ln, joint, eps, parYes));
return rcpp_result_gen;
END_RCPP
}
// pwiener
Rcpp::NumericVector pwiener(Rcpp::NumericVector rt, Rcpp::NumericVector ch, Rcpp::NumericVector alpha, Rcpp::NumericVector theta, Rcpp::NumericVector xi, Rcpp::NumericVector tau, Rcpp::NumericVector sigma, bool ln, bool joint, bool lower_tail, double eps, bool parYes);
RcppExport SEXP _seqmodels_pwiener(SEXP rtSEXP, SEXP chSEXP, SEXP alphaSEXP, SEXP thetaSEXP, SEXP xiSEXP, SEXP tauSEXP, SEXP sigmaSEXP, SEXP lnSEXP, SEXP jointSEXP, SEXP lower_tailSEXP, SEXP epsSEXP, SEXP parYesSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type rt(rtSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type ch(chSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type alpha(alphaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type theta(thetaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type xi(xiSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type tau(tauSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< bool >::type ln(lnSEXP);
Rcpp::traits::input_parameter< bool >::type joint(jointSEXP);
Rcpp::traits::input_parameter< bool >::type lower_tail(lower_tailSEXP);
Rcpp::traits::input_parameter< double >::type eps(epsSEXP);
Rcpp::traits::input_parameter< bool >::type parYes(parYesSEXP);
rcpp_result_gen = Rcpp::wrap(pwiener(rt, ch, alpha, theta, xi, tau, sigma, ln, joint, lower_tail, eps, parYes));
return rcpp_result_gen;
END_RCPP
}
// qwiener
Rcpp::NumericVector qwiener(Rcpp::NumericVector p, Rcpp::NumericVector ch, Rcpp::NumericVector alpha, Rcpp::NumericVector theta, Rcpp::NumericVector xi, Rcpp::NumericVector tau, Rcpp::NumericVector sigma, bool joint, double eps, double bounds, double em_stop, double err, bool parYes);
RcppExport SEXP _seqmodels_qwiener(SEXP pSEXP, SEXP chSEXP, SEXP alphaSEXP, SEXP thetaSEXP, SEXP xiSEXP, SEXP tauSEXP, SEXP sigmaSEXP, SEXP jointSEXP, SEXP epsSEXP, SEXP boundsSEXP, SEXP em_stopSEXP, SEXP errSEXP, SEXP parYesSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type p(pSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type ch(chSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type alpha(alphaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type theta(thetaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type xi(xiSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type tau(tauSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< bool >::type joint(jointSEXP);
Rcpp::traits::input_parameter< double >::type eps(epsSEXP);
Rcpp::traits::input_parameter< double >::type bounds(boundsSEXP);
Rcpp::traits::input_parameter< double >::type em_stop(em_stopSEXP);
Rcpp::traits::input_parameter< double >::type err(errSEXP);
Rcpp::traits::input_parameter< bool >::type parYes(parYesSEXP);
rcpp_result_gen = Rcpp::wrap(qwiener(p, ch, alpha, theta, xi, tau, sigma, joint, eps, bounds, em_stop, err, parYes));
return rcpp_result_gen;
END_RCPP
}
// rwiener
Rcpp::DataFrame rwiener(int n, Rcpp::NumericVector alpha, Rcpp::NumericVector theta, Rcpp::NumericVector xi, Rcpp::NumericVector tau, Rcpp::NumericVector sigma, double eps, double bounds, double em_stop, double err, bool parYes);
RcppExport SEXP _seqmodels_rwiener(SEXP nSEXP, SEXP alphaSEXP, SEXP thetaSEXP, SEXP xiSEXP, SEXP tauSEXP, SEXP sigmaSEXP, SEXP epsSEXP, SEXP boundsSEXP, SEXP em_stopSEXP, SEXP errSEXP, SEXP parYesSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type n(nSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type alpha(alphaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type theta(thetaSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type xi(xiSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type tau(tauSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< double >::type eps(epsSEXP);
Rcpp::traits::input_parameter< double >::type bounds(boundsSEXP);
Rcpp::traits::input_parameter< double >::type em_stop(em_stopSEXP);
Rcpp::traits::input_parameter< double >::type err(errSEXP);
Rcpp::traits::input_parameter< bool >::type parYes(parYesSEXP);
rcpp_result_gen = Rcpp::wrap(rwiener(n, alpha, theta, xi, tau, sigma, eps, bounds, em_stop, err, parYes));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_seqmodels_remg", (DL_FUNC) &_seqmodels_remg, 4},
{"_seqmodels_demg", (DL_FUNC) &_seqmodels_demg, 5},
{"_seqmodels_pemg", (DL_FUNC) &_seqmodels_pemg, 6},
{"_seqmodels_qemg", (DL_FUNC) &_seqmodels_qemg, 7},
{"_seqmodels_memg", (DL_FUNC) &_seqmodels_memg, 3},
{"_seqmodels_dlevy", (DL_FUNC) &_seqmodels_dlevy, 4},
{"_seqmodels_plevy", (DL_FUNC) &_seqmodels_plevy, 5},
{"_seqmodels_qlevy", (DL_FUNC) &_seqmodels_qlevy, 3},
{"_seqmodels_rlevy", (DL_FUNC) &_seqmodels_rlevy, 3},
{"_seqmodels_rinvgauss", (DL_FUNC) &_seqmodels_rinvgauss, 5},
{"_seqmodels_dinvgauss", (DL_FUNC) &_seqmodels_dinvgauss, 6},
{"_seqmodels_pinvgauss", (DL_FUNC) &_seqmodels_pinvgauss, 7},
{"_seqmodels_qinvgauss", (DL_FUNC) &_seqmodels_qinvgauss, 8},
{"_seqmodels_minvgauss", (DL_FUNC) &_seqmodels_minvgauss, 4},
{"_seqmodels_dwiener", (DL_FUNC) &_seqmodels_dwiener, 11},
{"_seqmodels_pwiener", (DL_FUNC) &_seqmodels_pwiener, 12},
{"_seqmodels_qwiener", (DL_FUNC) &_seqmodels_qwiener, 13},
{"_seqmodels_rwiener", (DL_FUNC) &_seqmodels_rwiener, 11},
{NULL, NULL, 0}
};
RcppExport void R_init_seqmodels(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
|
b3e227317f6cb7797cabf26423d162ad399f1e91 | bc82d84ac41ab082caa97b739f23bee6cbd613ac | /Massive/Massive/MyForm.h | 01323874583922d9cb5fa6ba73854eb0c0a252ff | [] | no_license | eliseev17/MyCode | 2b63e1fbcbf90155fe2282e723d6884903e38d17 | 0b104350b5285505be654af878fc9ddffb24b4f6 | refs/heads/master | 2020-04-07T18:10:47.033743 | 2018-11-21T20:11:54 | 2018-11-21T20:11:54 | 158,600,079 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 36,974 | h | MyForm.h | #pragma once
#include <random>
#include <cmath>
namespace Massive {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
/// <summary>
/// Сводка для MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: добавьте код конструктора
//
}
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::GroupBox^ groupBox1;
private: System::Windows::Forms::TextBox^ txtMax;
protected:
private: System::Windows::Forms::TextBox^ txtMin;
private: System::Windows::Forms::TextBox^ txtNum;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::GroupBox^ groupBox2;
private: System::Windows::Forms::RadioButton^ radDecrease;
private: System::Windows::Forms::RadioButton^ radIncrease;
private: System::Windows::Forms::RadioButton^ radOdd;
private: System::Windows::Forms::RadioButton^ radEven;
private: System::Windows::Forms::RadioButton^ radMax;
private: System::Windows::Forms::RadioButton^ radMin;
private: System::Windows::Forms::RadioButton^ radMid;
private: System::Windows::Forms::RadioButton^ radSum;
private: System::Windows::Forms::Label^ label4;
private: System::Windows::Forms::Label^ label5;
private: System::Windows::Forms::Button^ btnGenerate;
private: System::Windows::Forms::Label^ label6;
private: System::Windows::Forms::TextBox^ txtInput;
private: System::Windows::Forms::Button^ btnInput;
private: System::Windows::Forms::Button^ btnDo;
private: System::Windows::Forms::Label^ label7;
private: System::Windows::Forms::TextBox^ txtOutput;
private: System::Windows::Forms::Button^ btnSave;
private: System::Windows::Forms::Button^ btnClose;
private: System::Windows::Forms::OpenFileDialog^ openFD;
private: System::Windows::Forms::SaveFileDialog^ saveFD;
private: System::Windows::Forms::Label^ lblError;
private: System::Windows::Forms::RichTextBox^ txtMassiv;
private: System::Windows::Forms::RichTextBox^ txtResult;
private:
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
void InitializeComponent(void)
{
this->groupBox1 = (gcnew System::Windows::Forms::GroupBox());
this->txtMax = (gcnew System::Windows::Forms::TextBox());
this->txtMin = (gcnew System::Windows::Forms::TextBox());
this->txtNum = (gcnew System::Windows::Forms::TextBox());
this->label3 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label1 = (gcnew System::Windows::Forms::Label());
this->groupBox2 = (gcnew System::Windows::Forms::GroupBox());
this->radDecrease = (gcnew System::Windows::Forms::RadioButton());
this->radIncrease = (gcnew System::Windows::Forms::RadioButton());
this->radOdd = (gcnew System::Windows::Forms::RadioButton());
this->radEven = (gcnew System::Windows::Forms::RadioButton());
this->radMax = (gcnew System::Windows::Forms::RadioButton());
this->radMin = (gcnew System::Windows::Forms::RadioButton());
this->radMid = (gcnew System::Windows::Forms::RadioButton());
this->radSum = (gcnew System::Windows::Forms::RadioButton());
this->label4 = (gcnew System::Windows::Forms::Label());
this->label5 = (gcnew System::Windows::Forms::Label());
this->btnGenerate = (gcnew System::Windows::Forms::Button());
this->label6 = (gcnew System::Windows::Forms::Label());
this->txtInput = (gcnew System::Windows::Forms::TextBox());
this->btnInput = (gcnew System::Windows::Forms::Button());
this->btnDo = (gcnew System::Windows::Forms::Button());
this->label7 = (gcnew System::Windows::Forms::Label());
this->txtOutput = (gcnew System::Windows::Forms::TextBox());
this->btnSave = (gcnew System::Windows::Forms::Button());
this->btnClose = (gcnew System::Windows::Forms::Button());
this->openFD = (gcnew System::Windows::Forms::OpenFileDialog());
this->saveFD = (gcnew System::Windows::Forms::SaveFileDialog());
this->lblError = (gcnew System::Windows::Forms::Label());
this->txtMassiv = (gcnew System::Windows::Forms::RichTextBox());
this->txtResult = (gcnew System::Windows::Forms::RichTextBox());
this->groupBox1->SuspendLayout();
this->groupBox2->SuspendLayout();
this->SuspendLayout();
//
// groupBox1
//
this->groupBox1->Controls->Add(this->txtMax);
this->groupBox1->Controls->Add(this->txtMin);
this->groupBox1->Controls->Add(this->txtNum);
this->groupBox1->Controls->Add(this->label3);
this->groupBox1->Controls->Add(this->label2);
this->groupBox1->Controls->Add(this->label1);
this->groupBox1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->groupBox1->ForeColor = System::Drawing::SystemColors::HotTrack;
this->groupBox1->Location = System::Drawing::Point(12, 12);
this->groupBox1->Name = L"groupBox1";
this->groupBox1->Size = System::Drawing::Size(619, 198);
this->groupBox1->TabIndex = 0;
this->groupBox1->TabStop = false;
this->groupBox1->Text = L"Исходные данные";
//
// txtMax
//
this->txtMax->Location = System::Drawing::Point(379, 147);
this->txtMax->Name = L"txtMax";
this->txtMax->Size = System::Drawing::Size(211, 35);
this->txtMax->TabIndex = 5;
this->txtMax->TextChanged += gcnew System::EventHandler(this, &MyForm::txtMax_TextChanged);
//
// txtMin
//
this->txtMin->Location = System::Drawing::Point(379, 95);
this->txtMin->Name = L"txtMin";
this->txtMin->Size = System::Drawing::Size(211, 35);
this->txtMin->TabIndex = 4;
this->txtMin->TextChanged += gcnew System::EventHandler(this, &MyForm::txtMin_TextChanged);
//
// txtNum
//
this->txtNum->Location = System::Drawing::Point(379, 45);
this->txtNum->Name = L"txtNum";
this->txtNum->Size = System::Drawing::Size(211, 35);
this->txtNum->TabIndex = 3;
this->txtNum->TextChanged += gcnew System::EventHandler(this, &MyForm::txtNum_TextChanged);
//
// label3
//
this->label3->AutoSize = true;
this->label3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label3->ForeColor = System::Drawing::SystemColors::ControlText;
this->label3->Location = System::Drawing::Point(6, 153);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(351, 25);
this->label3->TabIndex = 2;
this->label3->Text = L"Максимальное значение диапазона:\r\n";
//
// label2
//
this->label2->AutoSize = true;
this->label2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label2->ForeColor = System::Drawing::SystemColors::ControlText;
this->label2->Location = System::Drawing::Point(6, 101);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(343, 25);
this->label2->TabIndex = 1;
this->label2->Text = L"Минимальное значение диапазона:";
//
// label1
//
this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label1->ForeColor = System::Drawing::SystemColors::ControlText;
this->label1->Location = System::Drawing::Point(6, 51);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(323, 25);
this->label1->TabIndex = 0;
this->label1->Text = L"Количество элементов массива:";
//
// groupBox2
//
this->groupBox2->Controls->Add(this->radDecrease);
this->groupBox2->Controls->Add(this->radIncrease);
this->groupBox2->Controls->Add(this->radOdd);
this->groupBox2->Controls->Add(this->radEven);
this->groupBox2->Controls->Add(this->radMax);
this->groupBox2->Controls->Add(this->radMin);
this->groupBox2->Controls->Add(this->radMid);
this->groupBox2->Controls->Add(this->radSum);
this->groupBox2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->groupBox2->ForeColor = System::Drawing::SystemColors::HotTrack;
this->groupBox2->Location = System::Drawing::Point(12, 313);
this->groupBox2->Name = L"groupBox2";
this->groupBox2->Size = System::Drawing::Size(619, 216);
this->groupBox2->TabIndex = 1;
this->groupBox2->TabStop = false;
this->groupBox2->Text = L"Операции с массивом";
//
// radDecrease
//
this->radDecrease->AutoSize = true;
this->radDecrease->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->radDecrease->ForeColor = System::Drawing::SystemColors::ControlText;
this->radDecrease->Location = System::Drawing::Point(303, 161);
this->radDecrease->Name = L"radDecrease";
this->radDecrease->Size = System::Drawing::Size(270, 29);
this->radDecrease->TabIndex = 7;
this->radDecrease->TabStop = true;
this->radDecrease->Text = L"Сортировка по убыванию";
this->radDecrease->UseVisualStyleBackColor = true;
this->radDecrease->CheckedChanged += gcnew System::EventHandler(this, &MyForm::radDecrease_CheckedChanged);
//
// radIncrease
//
this->radIncrease->AutoSize = true;
this->radIncrease->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->radIncrease->ForeColor = System::Drawing::SystemColors::ControlText;
this->radIncrease->Location = System::Drawing::Point(303, 121);
this->radIncrease->Name = L"radIncrease";
this->radIncrease->Size = System::Drawing::Size(301, 29);
this->radIncrease->TabIndex = 6;
this->radIncrease->TabStop = true;
this->radIncrease->Text = L"Сортировка по возрастанию";
this->radIncrease->UseVisualStyleBackColor = true;
this->radIncrease->CheckedChanged += gcnew System::EventHandler(this, &MyForm::radIncrease_CheckedChanged);
//
// radOdd
//
this->radOdd->AutoSize = true;
this->radOdd->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->radOdd->ForeColor = System::Drawing::SystemColors::ControlText;
this->radOdd->Location = System::Drawing::Point(303, 82);
this->radOdd->Name = L"radOdd";
this->radOdd->Size = System::Drawing::Size(235, 29);
this->radOdd->TabIndex = 5;
this->radOdd->TabStop = true;
this->radOdd->Text = L"Нечётные элементы";
this->radOdd->UseVisualStyleBackColor = true;
this->radOdd->CheckedChanged += gcnew System::EventHandler(this, &MyForm::radOdd_CheckedChanged);
//
// radEven
//
this->radEven->AutoSize = true;
this->radEven->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->radEven->ForeColor = System::Drawing::SystemColors::ControlText;
this->radEven->Location = System::Drawing::Point(303, 47);
this->radEven->Name = L"radEven";
this->radEven->Size = System::Drawing::Size(213, 29);
this->radEven->TabIndex = 4;
this->radEven->TabStop = true;
this->radEven->Text = L"Чётные элементы";
this->radEven->UseVisualStyleBackColor = true;
this->radEven->CheckedChanged += gcnew System::EventHandler(this, &MyForm::radEven_CheckedChanged);
//
// radMax
//
this->radMax->AutoSize = true;
this->radMax->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->radMax->ForeColor = System::Drawing::SystemColors::ControlText;
this->radMax->Location = System::Drawing::Point(24, 161);
this->radMax->Name = L"radMax";
this->radMax->Size = System::Drawing::Size(269, 29);
this->radMax->TabIndex = 3;
this->radMax->TabStop = true;
this->radMax->Text = L"Максимальный элемент";
this->radMax->UseVisualStyleBackColor = true;
this->radMax->CheckedChanged += gcnew System::EventHandler(this, &MyForm::radMax_CheckedChanged);
//
// radMin
//
this->radMin->AutoSize = true;
this->radMin->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->radMin->ForeColor = System::Drawing::SystemColors::ControlText;
this->radMin->Location = System::Drawing::Point(24, 121);
this->radMin->Name = L"radMin";
this->radMin->Size = System::Drawing::Size(261, 29);
this->radMin->TabIndex = 2;
this->radMin->TabStop = true;
this->radMin->Text = L"Минимальный элемент";
this->radMin->UseVisualStyleBackColor = true;
this->radMin->CheckedChanged += gcnew System::EventHandler(this, &MyForm::radMin_CheckedChanged);
//
// radMid
//
this->radMid->AutoSize = true;
this->radMid->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->radMid->ForeColor = System::Drawing::SystemColors::ControlText;
this->radMid->Location = System::Drawing::Point(24, 82);
this->radMid->Name = L"radMid";
this->radMid->Size = System::Drawing::Size(209, 29);
this->radMid->TabIndex = 1;
this->radMid->TabStop = true;
this->radMid->Text = L"Среднее значение";
this->radMid->UseVisualStyleBackColor = true;
this->radMid->CheckedChanged += gcnew System::EventHandler(this, &MyForm::radMid_CheckedChanged);
//
// radSum
//
this->radSum->AutoSize = true;
this->radSum->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->radSum->ForeColor = System::Drawing::SystemColors::ControlText;
this->radSum->Location = System::Drawing::Point(24, 43);
this->radSum->Name = L"radSum";
this->radSum->Size = System::Drawing::Size(214, 29);
this->radSum->TabIndex = 0;
this->radSum->TabStop = true;
this->radSum->Text = L"Сумма элементов";
this->radSum->UseVisualStyleBackColor = true;
this->radSum->CheckedChanged += gcnew System::EventHandler(this, &MyForm::radSum_CheckedChanged);
//
// label4
//
this->label4->AutoSize = true;
this->label4->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label4->Location = System::Drawing::Point(7, 220);
this->label4->Name = L"label4";
this->label4->Size = System::Drawing::Size(224, 29);
this->label4->TabIndex = 2;
this->label4->Text = L"Исходный массив:";
//
// label5
//
this->label5->AutoSize = true;
this->label5->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label5->Location = System::Drawing::Point(7, 532);
this->label5->Name = L"label5";
this->label5->Size = System::Drawing::Size(259, 29);
this->label5->TabIndex = 4;
this->label5->Text = L"Результат операции:";
//
// btnGenerate
//
this->btnGenerate->BackColor = System::Drawing::SystemColors::Window;
this->btnGenerate->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->btnGenerate->Location = System::Drawing::Point(650, 26);
this->btnGenerate->Name = L"btnGenerate";
this->btnGenerate->Size = System::Drawing::Size(215, 45);
this->btnGenerate->TabIndex = 6;
this->btnGenerate->Text = L"Генерация массива";
this->btnGenerate->UseVisualStyleBackColor = false;
this->btnGenerate->Click += gcnew System::EventHandler(this, &MyForm::btnGenerate_Click);
//
// label6
//
this->label6->AutoSize = true;
this->label6->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label6->Location = System::Drawing::Point(645, 86);
this->label6->Name = L"label6";
this->label6->Size = System::Drawing::Size(185, 25);
this->label6->TabIndex = 7;
this->label6->Text = L"Имя файла ввода:";
//
// txtInput
//
this->txtInput->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->txtInput->Location = System::Drawing::Point(650, 114);
this->txtInput->Name = L"txtInput";
this->txtInput->RightToLeft = System::Windows::Forms::RightToLeft::Yes;
this->txtInput->Size = System::Drawing::Size(215, 35);
this->txtInput->TabIndex = 8;
//
// btnInput
//
this->btnInput->BackColor = System::Drawing::SystemColors::Window;
this->btnInput->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->btnInput->Location = System::Drawing::Point(650, 165);
this->btnInput->Name = L"btnInput";
this->btnInput->Size = System::Drawing::Size(215, 45);
this->btnInput->TabIndex = 9;
this->btnInput->Text = L"Ввод из файла";
this->btnInput->UseVisualStyleBackColor = false;
this->btnInput->Click += gcnew System::EventHandler(this, &MyForm::btnInput_Click);
//
// btnDo
//
this->btnDo->BackColor = System::Drawing::SystemColors::Window;
this->btnDo->Enabled = false;
this->btnDo->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->btnDo->Location = System::Drawing::Point(650, 327);
this->btnDo->Name = L"btnDo";
this->btnDo->Size = System::Drawing::Size(215, 45);
this->btnDo->TabIndex = 10;
this->btnDo->Text = L"Выполнить";
this->btnDo->UseVisualStyleBackColor = false;
this->btnDo->Click += gcnew System::EventHandler(this, &MyForm::btnDo_Click);
//
// label7
//
this->label7->AutoSize = true;
this->label7->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label7->Location = System::Drawing::Point(645, 395);
this->label7->Name = L"label7";
this->label7->Size = System::Drawing::Size(199, 25);
this->label7->TabIndex = 11;
this->label7->Text = L"Имя файла вывода:";
//
// txtOutput
//
this->txtOutput->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->txtOutput->Location = System::Drawing::Point(650, 428);
this->txtOutput->Name = L"txtOutput";
this->txtOutput->RightToLeft = System::Windows::Forms::RightToLeft::Yes;
this->txtOutput->Size = System::Drawing::Size(215, 35);
this->txtOutput->TabIndex = 12;
//
// btnSave
//
this->btnSave->BackColor = System::Drawing::SystemColors::Window;
this->btnSave->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->btnSave->Location = System::Drawing::Point(650, 484);
this->btnSave->Name = L"btnSave";
this->btnSave->Size = System::Drawing::Size(215, 45);
this->btnSave->TabIndex = 13;
this->btnSave->Text = L"Сохранить в файл";
this->btnSave->UseVisualStyleBackColor = false;
this->btnSave->Click += gcnew System::EventHandler(this, &MyForm::btnSave_Click);
//
// btnClose
//
this->btnClose->BackColor = System::Drawing::SystemColors::Window;
this->btnClose->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->btnClose->Location = System::Drawing::Point(650, 563);
this->btnClose->Name = L"btnClose";
this->btnClose->Size = System::Drawing::Size(215, 45);
this->btnClose->TabIndex = 14;
this->btnClose->Text = L"Закрыть";
this->btnClose->UseVisualStyleBackColor = false;
this->btnClose->Click += gcnew System::EventHandler(this, &MyForm::btnClose_Click);
//
// openFD
//
this->openFD->FileName = L"input";
//
// saveFD
//
this->saveFD->DefaultExt = L"txt";
this->saveFD->FileName = L"output";
//
// lblError
//
this->lblError->AutoSize = true;
this->lblError->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 16, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->lblError->ForeColor = System::Drawing::Color::Red;
this->lblError->Location = System::Drawing::Point(245, 214);
this->lblError->Name = L"lblError";
this->lblError->Size = System::Drawing::Size(0, 37);
this->lblError->TabIndex = 15;
//
// txtMassiv
//
this->txtMassiv->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 16, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->txtMassiv->Location = System::Drawing::Point(12, 257);
this->txtMassiv->Name = L"txtMassiv";
this->txtMassiv->Size = System::Drawing::Size(853, 50);
this->txtMassiv->TabIndex = 16;
this->txtMassiv->Text = L"";
//
// txtResult
//
this->txtResult->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->txtResult->Location = System::Drawing::Point(12, 563);
this->txtResult->Name = L"txtResult";
this->txtResult->ReadOnly = true;
this->txtResult->Size = System::Drawing::Size(619, 45);
this->txtResult->TabIndex = 17;
this->txtResult->Text = L"";
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(9, 20);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::SystemColors::Window;
this->ClientSize = System::Drawing::Size(882, 620);
this->Controls->Add(this->txtResult);
this->Controls->Add(this->txtMassiv);
this->Controls->Add(this->lblError);
this->Controls->Add(this->btnClose);
this->Controls->Add(this->btnSave);
this->Controls->Add(this->txtOutput);
this->Controls->Add(this->label7);
this->Controls->Add(this->btnDo);
this->Controls->Add(this->btnInput);
this->Controls->Add(this->txtInput);
this->Controls->Add(this->label6);
this->Controls->Add(this->btnGenerate);
this->Controls->Add(this->label5);
this->Controls->Add(this->label4);
this->Controls->Add(this->groupBox2);
this->Controls->Add(this->groupBox1);
this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle;
this->MaximizeBox = false;
this->Name = L"MyForm";
this->Text = L"Обработка массива ";
this->groupBox1->ResumeLayout(false);
this->groupBox1->PerformLayout();
this->groupBox2->ResumeLayout(false);
this->groupBox2->PerformLayout();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void btnClose_Click(System::Object^ sender, System::EventArgs^ e) {
this->Close();
}
String^ currentArray = "";
String^ max(array<Int64>^ numbers)
{
Int64 Max = numbers[0];
for (int i = 1; i < numbers->Length; ++i) {
if (numbers[i] > Max) {
Max = numbers[i];
}
}
return Convert::ToString(Max);
}
String^ sum(array<Int64>^ numbers)
{
Int64 Sum = 0, i;
for (i = 0; i < numbers->Length; ++i) {
Sum += numbers[i];
}
return Convert::ToString(Sum);
}
String^ avg(array<Int64>^ numbers) {
int count = 0;
Int64 sum = 0;
for (int i = 0; i < numbers->Length; ++i) {
sum += numbers[i];
++count;
}
return Convert::ToString(sum / (double)count);
}
array<Int64>^ decSort(array<Int64>^ numbers) {
Int64 tmp;
array<Int64>^ numbersCopy = numbers;
for (int i = 0; i < numbersCopy->Length - 1; ++i) {
for (int j = i + 1; j < numbersCopy->Length; ++j) {
if (numbersCopy[j] > numbersCopy[i]) {
tmp = numbersCopy[i];
numbersCopy[i] = numbersCopy[j];
numbersCopy[j] = tmp;
}
}
}
return numbersCopy;
}
String^ conv(array<Int64>^ numbers) {
String^ output = "";
for (int i = 0; i < numbers->Length; ++i) {
output += Convert::ToString(numbers[i]) + " ";
}
return output;
}
array<Int64>^ incSort(array<Int64>^ numbers) {
Int64 tmp;
array<Int64>^ numbersCopy = numbers;
for (int i = 0; i < numbersCopy->Length - 1; ++i) {
for (int j = i + 1; j < numbersCopy->Length; ++j) {
if (numbersCopy[j] < numbersCopy[i]) {
tmp = numbersCopy[i];
numbersCopy[i] = numbersCopy[j];
numbersCopy[j] = tmp;
}
}
}
return numbersCopy;
}
String^ min(array<Int64>^ numbers) {
Int64 Min = numbers[0];
for (int i = 1; i < numbers->Length; ++i) {
if (numbers[i] < Min) {
Min = numbers[i];
}
}
return Convert::ToString(Min);
}
String^ even(array<Int64>^ numbers) {
String^ output;
for (int i = 0; i < numbers->Length; ++i) {
if (numbers[i] % 2 == 0) {
output += Convert::ToString(numbers[i]) + " ";
}
}
return output;
}
String^ odd(array<Int64>^ numbers) {
String^ output;
for (int i = 0; i < numbers->Length; ++i) {
if (numbers[i] % 2 == 1) {
output += Convert::ToString(numbers[i]) + " ";
}
}
return output;
}
void fill(array<Int64>^ numbers) { //ф-ция отвечает за автоматическое определение
Int64 Min, Max; //min, max и кол-ва элементов
int i;
Min = Max = numbers[0];
for (int i = 1; i < numbers->Length; ++i) {
if (numbers[i] > Max) {
Max = numbers[i];
}
if (numbers[i] < Min) {
Min = numbers[i];
}
}
txtMax->Text = Convert::ToString(Max);
txtMin->Text = Convert::ToString(Min);
txtNum->Text = Convert::ToString(numbers->Length);
}
private: System::Void btnDo_Click(System::Object^ sender, System::EventArgs^ e) {
if (txtMassiv->Text->Length == 0) {
lblError->Text = "Заполните исходный массив";
txtResult->Text = "";
return;
}
array<String^>^ strings = txtMassiv->Text->Split(' ');
Converter<String^, Int64>^ converter =
gcnew Converter<String^, Int64>(Convert::ToInt64);
array<String^>^ cleaned = gcnew array<String^>(strings->Length);
int index = 0;
for each(String^ s in strings) {
if (!String::IsNullOrEmpty(s)) {
cleaned[index++] = s;
}
}
Array::Resize(cleaned, index);
array<Int64>^ numbers;
numbers = Array::ConvertAll(cleaned, converter);
try {
numbers = Array::ConvertAll(cleaned, converter);
fill(numbers);
}
catch (FormatException^)
{
lblError->Text = "Некорректный формат";
txtResult->Text = "";
return;
}
catch (OverflowException^) {
lblError->Text = "Число не попадает в допустимый ряд";
txtResult->Text = "";
return;
}
txtResult->Text = "";
txtMassiv->Text = "";
btnSave->Enabled = true;
for (int i = 0; i < cleaned->Length; ++i) {
txtMassiv->Text += Convert::ToString(cleaned[i]) + " ";
}
lblError->Text = "";
if (radMid->Checked) {
txtResult->Text = "Среднее значение: " + avg(numbers);
}
else if (radDecrease->Checked) {
txtResult->Text = "Сортировка по убыванию: " + conv(decSort(numbers));
}
else if (radEven->Checked) {
txtResult->Text = "Чётные элементы: " + even(numbers);
}
else if (radIncrease->Checked) {
txtResult->Text = "Сортировка по возрастанию: " + conv(incSort(numbers));
}
else if (radMax->Checked) {
txtResult->Text = "Максимальный элемент: " + max(numbers);
}
else if (radMin->Checked) {
txtResult->Text = "Минимальный элемент: " + min(numbers);
}
else if (radOdd->Checked) {
txtResult->Text = "Нечётные элементы: " + odd(numbers);
}
else if (radSum->Checked) {
txtResult->Text = "Сумма элементов: " + sum(numbers);
}
btnDo->Enabled = false;
}
private: System::Void btnGenerate_Click(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
txtMassiv->Text = "";
Random^ rand = gcnew Random();
int count;
Int64 Max, Min;
if (txtMax->Text->Length == 0 || txtMin->Text->Length == 0 || txtNum->Text->Length == 0) {
lblError->Text = "Заполните все поля";
return;
}
try
{
count = Convert::ToInt32(txtNum->Text);
Max = Convert::ToInt64(txtMax->Text);
Min = Convert::ToInt64(txtMin->Text);
}
catch (FormatException^)
{
lblError->Text = "Некорректный формат";
return;
}
if (Max < Min) {
lblError->Text = "Диапазон массива указан неверно";
return;
}
if (count < 1) {
lblError->Text = "В массиве должно быть не менее 1 элемента";
return;
}
String^ input;
for (int i = 0; i < count; ++i) {
input += Convert::ToString(rand->Next(Min, Max + 1)) + " ";
}
lblError->Text = "";
currentArray = input;
txtMassiv->Text = input;
}
private: System::Void btnInput_Click(System::Object^ sender, System::EventArgs^ e) {
openFD->DefaultExt = ".txt";
openFD->Filter = "Text files |*.txt";
OpenFileDialog^ openFD = gcnew OpenFileDialog();
try {
if (openFD->ShowDialog() == System::Windows::Forms::DialogResult::OK && openFD->FileName->Length > 0)
{
txtMax->Text = "";
txtMin->Text = "";
txtNum->Text = "";
txtMassiv->Text = "";
txtResult->Text = "";
txtInput->Text = openFD->FileName;
txtMassiv->Text = File::ReadAllText(txtInput->Text);
array<String^>^ strings = txtMassiv->Text->Split(' ');
Converter<String^, Int64>^ converter =
gcnew Converter<String^, Int64>(Convert::ToInt64);
array<String^>^ cleaned = gcnew array<String^>(strings->Length);
int index = 0;
for each(String^ s in strings) {
if (!String::IsNullOrEmpty(s)) {
cleaned[index++] = s;
}
}
Array::Resize(cleaned, index);
array<Int64>^ numbers;
try {
numbers = Array::ConvertAll(cleaned, converter);
fill(numbers);
}
catch (FormatException^)
{
lblError->Text = "Некорректный формат";
txtResult->Text = "";
return;
}
catch (OverflowException^) {
lblError->Text = "Число не попадает в допустимый ряд";
txtResult->Text = "";
return;
}
txtMassiv->Text = File::ReadAllText(txtInput->Text);
}
}
catch (FileNotFoundException^) {
lblError->Text = "Такого файла нет";
}
lblError->Text = "";
}
bool empty = true;
private: System::Void btnSave_Click(System::Object^ sender, System::EventArgs^ e) {
if (txtResult->Text == "") {
lblError->Text = "Отсутствует результат операции";
return;
}
try {
if (currentArray != txtMassiv->Text || empty) {
empty = false;
currentArray = txtInput->Text;
SaveFileDialog^ saveFD = gcnew SaveFileDialog();
saveFD->DefaultExt = ".txt";
saveFD->Filter = "Text files |*.txt";
if (saveFD->ShowDialog() == System::Windows::Forms::DialogResult::OK && saveFD->FileName->Length > 0)
{
btnSave->Enabled = false;
txtOutput->Text = saveFD->FileName;
StreamWriter^sw = gcnew StreamWriter(saveFD->FileName, true);
if (txtMassiv->Text)
sw->WriteLine("Сгенерированный массив: " + txtMassiv->Text);
sw->WriteLine("Результаты обработки: " + txtResult->Text);
sw->Close();
}
}
}
catch (...) {
lblError->Text = "Такого файла нет";
txtResult->Text = "";
}
lblError->Text = "";
}
private: System::Void txtInput_TextChanged(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
btnDo->Enabled = true;
}
private: System::Void radSum_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
btnDo->Enabled = true;
}
private: System::Void radMid_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
btnDo->Enabled = true;
}
private: System::Void radMin_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
btnDo->Enabled = true;
}
private: System::Void radMax_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
btnDo->Enabled = true;
}
private: System::Void radEven_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
btnDo->Enabled = true;
}
private: System::Void radOdd_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
btnDo->Enabled = true;
}
private: System::Void radIncrease_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
btnDo->Enabled = true;
}
private: System::Void radDecrease_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
txtResult->Text = "";
btnDo->Enabled = true;
}
private: System::Void txtNum_TextChanged(System::Object^ sender, System::EventArgs^ e) {
txtMassiv->Text = "";
txtResult->Text = "";
}
private: System::Void txtMin_TextChanged(System::Object^ sender, System::EventArgs^ e) {
txtMassiv->Text = "";
txtResult->Text = "";
}
private: System::Void txtMax_TextChanged(System::Object^ sender, System::EventArgs^ e) {
txtMassiv->Text = "";
txtResult->Text = "";
}
};
}
|
56efdc1c4aeccc1225d6211fa0e5af22e782ac66 | dd1385ee93b0135f53c705f9d89f7936390a8fd8 | /src/resources/resources.h | 705bb5c16e0549f9ae5640a8b8a0650efcf2c6ce | [] | no_license | catompiler/celestial-battle | fcceff6d1551398bda97a62930295986d1217281 | 1998c50867317d71326caec54ecbc47749f71445 | refs/heads/master | 2016-09-05T09:51:32.493447 | 2015-05-09T16:47:44 | 2015-05-09T16:47:44 | 35,336,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,774 | h | resources.h | #ifndef _RESOURCES_H
#define _RESOURCES_H
#include <assert.h>
#include <string>
#include <map>
#include <list>
#include <iterator>
#include "engine/engine.h"
#include "resptrs_types.h"
#include "typelist/typelist.h"
#include "reader.h"
ENGINE_NAMESPACE_BEGIN
class Resources {
public:
typedef tl::makeTypeList<GL::Buffer,
GL::VertexShader, GL::FragmentShader, GL::GeometryShader,
GL::TessControlShader, GL::TessEvalShader, GL::ComputeShader, GL::Program,
GL::Texture1D, GL::Texture2D, GL::Texture3D, GL::TextureCube, GL::TextureRect,
Mesh, Material>::value ResourceTypes;
template <typename T>
class ResourceContainer{
public:
ResourceContainer();
ResourceContainer(const resource_ptr<T>& sptr_);
~ResourceContainer();
resource_ptr<T>& get();
void set(const resource_ptr<T>& sptr_);
private:
resource_ptr<T> _sptr;
};
template <typename T>
using ResourcesList = std::unordered_multimap<std::string, ResourceContainer<T>*>;
template <typename T>
using ReadersList = std::list<Reader<T>*>;
Resources();
virtual ~Resources();
template<class T>
bool hasResourceType();
template<class T>
resource_ptr<T> get();//create
template<class T>
resource_ptr<T> get(const std::string& filename_);//read
template<class T>
bool release(resource_ptr<T>& resource_);//release
void gc();
template<class _Reader>
bool addReader(_Reader* reader_);
template<class _Reader>
bool removeReader(_Reader* reader_);
template <class T>
class iterator
:public std::iterator<std::bidirectional_iterator_tag, T>
{
public:
iterator();
iterator(typename ResourcesList<T>::iterator it_);
iterator(const iterator<T>& it_);
~iterator();
iterator<T>& operator=(const iterator<T>& it_);
iterator<T>& operator++();
iterator<T> operator++(int);
iterator<T>& operator--();
iterator<T> operator--(int);
bool operator==(const iterator<T>& it_) const;
bool operator!=(const iterator<T>& it_) const;
resource_ptr<T>& operator*();
resource_ptr<T>& operator->();
const std::string& filename() const;
resource_ptr<T>& sptr();
private:
typename ResourcesList<T>::iterator _it;
};
template<class T>
iterator<T> begin();
template<class T>
iterator<T> end();
private:
class ResourceTypeItemBase{
public:
ResourceTypeItemBase();
ResourceTypeItemBase(const ResourceTypeItemBase& rtib_);
virtual ~ResourceTypeItemBase();
virtual bool hasReaders() const = 0;
virtual bool hasResources() const = 0;
virtual void gc() = 0;
};
template <typename T>
class ResourceTypeItem
:public ResourceTypeItemBase
{
public:
ResourceTypeItem();
ResourceTypeItem(const ResourceTypeItem& restypeitem_);
~ResourceTypeItem();
bool hasReaders() const;
ReadersList<T>* readers();
ReadersList<T>* getReaders();
bool hasResources() const;
ResourcesList<T>* resources();
ResourcesList<T>* getResources();
void gc();
private:
ReadersList<T>* _readers;
ResourcesList<T>* _resources;
};
typedef std::unordered_map<int, ResourceTypeItemBase*> ResourceTypeItems;
ResourceTypeItems _resourcetypeitems;
template<class T>
int _getResourceTypeIndex();
template<class T>
ResourceTypeItems::iterator _getResourceTypeIt();
template<class T>
ResourceTypeItems::iterator _resourceTypeIt();
template<class T>
ReadersList<T>* _readersList();
};
template<class T>
bool Resources::hasResourceType()
{
return _getResourceTypeIndex<T>() != -1;
}
template<class T>
resource_ptr<T> Resources::get()//create
{
ResourceTypeItems::iterator restype_it = _getResourceTypeIt<T>();
if(restype_it == _resourcetypeitems.end()) return resource_ptr<T>(NULL);
ResourceTypeItem<T>* restypeitem = static_cast<ResourceTypeItem<T>*>((*restype_it).second);
ResourcesList<T>* resourceslist = restypeitem->getResources();
resource_ptr<T> res_sptr(new T());
resourceslist->insert(
std::make_pair(std::string(), new ResourceContainer<T>(res_sptr))
);
return res_sptr;
}
template<class T>
resource_ptr<T> Resources::get(const std::string& filename_)//read
{
ResourceTypeItems::iterator restype_it = _resourceTypeIt<T>();
if(restype_it == _resourcetypeitems.end()) return resource_ptr<T>(NULL);
ResourceTypeItem<T>* restypeitem = static_cast<ResourceTypeItem<T>*>((*restype_it).second);
ResourcesList<T>* resourceslist = restypeitem->resources();
if(resourceslist != NULL){
typename ResourcesList<T>::iterator res_it = resourceslist->find(filename_);
if(res_it != resourceslist->end()){
ResourceContainer<T>* rescontainer = static_cast<ResourceContainer<T>*>((*res_it).second);
return rescontainer->get();
}
}
ReadersList<T>* readerslist = restypeitem->readers();
if(readerslist == NULL) return resource_ptr<T>(NULL);
T* res = NULL;
for(typename ReadersList<T>::iterator it = readerslist->begin();
it != readerslist->end(); ++ it){
res = static_cast<Reader<T>*>((*it))->read(this, filename_);
if(res != NULL){
if(resourceslist == NULL) resourceslist = restypeitem->getResources();
resource_ptr<T> res_sptr(res);
resourceslist->insert(
std::make_pair(filename_, new ResourceContainer<T>(res_sptr))
);
return res_sptr;
}
}
return resource_ptr<T>(NULL);
}
template<class T>
bool Resources::release(resource_ptr<T>& resource_)
{
ResourceTypeItems::iterator restype_it = _resourceTypeIt<T>();
if(restype_it == _resourcetypeitems.end()) return false;
ResourceTypeItem<T>* restypeitem = static_cast<ResourceTypeItem<T>*>((*restype_it).second);
ResourcesList<T>* resourceslist = restypeitem->resources();
if(resourceslist == NULL) return false;
typename ResourcesList<T>::iterator res_it =
std::find_if(resourceslist->begin(), resourceslist->end(), [&resource_](typename ResourcesList<T>::value_type& item_){
return item_.second->get() == resource_;
});
if(res_it == resourceslist->end()) return false;
//if(!resource_.release()) resource_.reset();
resource_ = NULL;
ResourceContainer<T>* rescontainer = (*res_it).second;
assert(rescontainer->get().use_count() != 0);
if(rescontainer->get().use_count() == 1){
delete rescontainer;
resourceslist->erase(res_it);
return true;
}
return false;
}
template<class _Reader>
bool Resources::addReader(_Reader* reader_)
{
ResourceTypeItems::iterator restypeitem_it =
_getResourceTypeIt<typename _Reader::ResourceType>();
if(restypeitem_it == _resourcetypeitems.end()) return false;
ResourceTypeItem<typename _Reader::ResourceType>* resourcetypeitem =
static_cast<ResourceTypeItem<typename _Reader::ResourceType>*>((*restypeitem_it).second);
ReadersList<typename _Reader::ResourceType>* readerslist = resourcetypeitem->getReaders();
typename ReadersList<typename _Reader::ResourceType>::iterator it = std::find(readerslist->begin(),
readerslist->end(), reader_);
if(it != readerslist->end()) return false;
readerslist->insert(readerslist->end(), reader_);
return true;
}
template<class _Reader>
bool Resources::removeReader(_Reader* reader_)
{
ResourceTypeItems::iterator restypeitem_it =
_getResourceTypeIt<typename _Reader::ResourceType>();
if(restypeitem_it == _resourcetypeitems.end()) return false;
ResourceTypeItem<typename _Reader::ResourceType>* resourcetypeitem =
static_cast<ResourceTypeItem<typename _Reader::ResourceType>*>((*restypeitem_it).second);
ReadersList<typename _Reader::ResourceType>* readerslist = resourcetypeitem->readers();
if(readerslist == NULL) return false;
typename ReadersList<typename _Reader::ResourceType>::iterator it = std::find(readerslist->begin(),
readerslist->end(), reader_);
if(it == readerslist->end()) return false;
readerslist->erase(it);
return true;
}
template<class T>
Resources::iterator<T> Resources::begin()
{
ResourceTypeItems::iterator restype_it = _resourceTypeIt<T>();
if(restype_it == _resourcetypeitems.end()) return iterator<T>();
ResourceTypeItem<T>* restypeitem = static_cast<ResourceTypeItem<T>*>((*restype_it).second);
ResourcesList<T>* resourceslist = restypeitem->resources();
if(resourceslist == NULL) return iterator<T>();
return iterator<T>(resourceslist->begin());
}
template<class T>
Resources::iterator<T> Resources::end()
{
ResourceTypeItems::iterator restype_it = _resourceTypeIt<T>();
if(restype_it == _resourcetypeitems.end()) return iterator<T>();
ResourceTypeItem<T>* restypeitem = static_cast<ResourceTypeItem<T>*>((*restype_it).second);
ResourcesList<T>* resourceslist = restypeitem->resources();
if(resourceslist == NULL) return iterator<T>();
return iterator<T>(resourceslist->end());
}
template <typename T>
Resources::ResourceTypeItem<T>::ResourceTypeItem()
:ResourceTypeItemBase()
{
_readers = NULL;
_resources = NULL;
}
template <typename T>
Resources::ResourceTypeItem<T>::ResourceTypeItem(const ResourceTypeItem& restypeitem_)
:ResourceTypeItemBase(restypeitem_)
{
if(restypeitem_._readers){
_readers = new ReadersList<T>(*restypeitem_._readers);
}else{
_readers = NULL;
}
if(restypeitem_._resources){
_resources = new ResourcesList<T>(*restypeitem_._resources);
}else{
_resources = NULL;
}
}
template <typename T>
Resources::ResourceTypeItem<T>::~ResourceTypeItem()
{
if(_readers) delete _readers;
if(_resources){
std::for_each(_resources->begin(), _resources->end(), functors::delete_single());
delete _resources;
}
}
template <typename T>
bool Resources::ResourceTypeItem<T>::hasReaders() const
{
return _readers != NULL && !_readers->empty();
}
template <typename T>
Resources::ReadersList<T>* Resources::ResourceTypeItem<T>::readers()
{
return _readers;
}
template <typename T>
Resources::ReadersList<T>* Resources::ResourceTypeItem<T>::getReaders()
{
if(_readers == NULL){
_readers = new ReadersList<T>();
}
return _readers;
}
template <typename T>
bool Resources::ResourceTypeItem<T>::hasResources() const
{
return _resources != NULL && !_resources->empty();
}
template <typename T>
Resources::ResourcesList<T>* Resources::ResourceTypeItem<T>::resources()
{
return _resources;
}
template <typename T>
Resources::ResourcesList<T>* Resources::ResourceTypeItem<T>::getResources()
{
if(_resources == NULL){
_resources = new ResourcesList<T>();
}
return _resources;
}
template <typename T>
void Resources::ResourceTypeItem<T>::gc()
{
//if has resources
if(_resources != NULL){
//for each resource
for(typename ResourcesList<T>::iterator res_it = _resources->begin();
res_it != _resources->end();){
ResourceContainer<T>* resource_container = (*res_it).second;
//if no one use the resource
assert(resource_container->get().use_count() != 0);
if(resource_container->get().use_count() == 1){
//delete
delete resource_container;
//erase
typename ResourcesList<T>::iterator erase_it = res_it ++;
_resources->erase(erase_it);
}else{
++ res_it;
}
}
}
}
template<class T>
int Resources::_getResourceTypeIndex()
{
return tl::index_of<ResourceTypes, T>::value;
}
template<class T>
Resources::ResourceTypeItems::iterator Resources::_getResourceTypeIt()
{
int type_index = _getResourceTypeIndex<T>();
if(type_index == -1) return _resourcetypeitems.end();
ResourceTypeItems::iterator it = _resourcetypeitems.find(type_index);
if(it == _resourcetypeitems.end()){
it = _resourcetypeitems.insert(std::make_pair(type_index, new ResourceTypeItem<T>())).first;
}
return it;
}
template<class T>
Resources::ResourceTypeItems::iterator Resources::_resourceTypeIt()
{
int type_index = _getResourceTypeIndex<T>();
if(type_index == -1) return _resourcetypeitems.end();
return _resourcetypeitems.find(type_index);
}
template<class T>
Resources::ReadersList<T>* Resources::_readersList()
{
ResourceTypeItems::iterator restypeitem_it = _getResourceTypeIt<T>();
if(restypeitem_it == _resourcetypeitems.end()) return NULL;
ResourceTypeItem<T>* resourceTypeItem = static_cast<ResourceTypeItem<T>*>((*restypeitem_it).second);
if(resourceTypeItem == NULL) return NULL;
ReadersList<T>* readerslist = resourceTypeItem->readers();
return readerslist;
}
template <typename T>
Resources::ResourceContainer<T>::ResourceContainer()
{
}
template <typename T>
Resources::ResourceContainer<T>::ResourceContainer(const resource_ptr<T>& sptr_)
{
_sptr = sptr_;
}
template <typename T>
Resources::ResourceContainer<T>::~ResourceContainer()
{
}
template <typename T>
resource_ptr<T>& Resources::ResourceContainer<T>::get()
{
return _sptr;
}
template <typename T>
void Resources::ResourceContainer<T>::set(const resource_ptr<T>& sptr_)
{
_sptr = sptr_;
}
template<class T>
Resources::iterator<T>::iterator()
{
}
template<class T>
Resources::iterator<T>::iterator(typename ResourcesList<T>::iterator it_)
{
_it = it_;
}
template<class T>
Resources::iterator<T>::iterator(const iterator<T>& it_)
{
_it = it_._it;
}
template<class T>
Resources::iterator<T>::~iterator()
{
}
template<class T>
Resources::iterator<T>& Resources::iterator<T>::operator=(const iterator<T>& it_)
{
_it = it_._it;
}
template<class T>
Resources::iterator<T>& Resources::iterator<T>::operator++()
{
++ _it;
return *this;
}
template<class T>
Resources::iterator<T> Resources::iterator<T>::operator++(int)
{
return iterator<T>(_it ++);
}
template<class T>
Resources::iterator<T>& Resources::iterator<T>::operator--()
{
-- _it;
return *this;
}
template<class T>
Resources::iterator<T> Resources::iterator<T>::operator--(int)
{
return iterator<T>(_it --);
}
template<class T>
bool Resources::iterator<T>::operator==(const iterator<T>& it_) const
{
return _it == it_._it;
}
template<class T>
bool Resources::iterator<T>::operator!=(const iterator<T>& it_) const
{
return _it != it_._it;
}
template<class T>
resource_ptr<T>& Resources::iterator<T>::operator*()
{
return sptr();
}
template<class T>
resource_ptr<T>& Resources::iterator<T>::operator->()
{
return sptr();
}
template<class T>
const std::string& Resources::iterator<T>::filename() const
{
return (*_it).first;
}
template<class T>
resource_ptr<T>& Resources::iterator<T>::sptr()
{
return (*_it).second->get();
}
ENGINE_NAMESPACE_END
#endif /* _RESOURCES_H */
|
8b3a0959dea2d9a4f1dbe75503a413e1510aec47 | 61c49d20245da7c4af2bf745978997eafae76350 | /c-plus-plus-como-programar/cap-6-funcoes-recursao/sobrecarga_funcoes.cpp | 22dac5d12bd8fe72a1b8b34f1dcb60dca1eba463 | [] | no_license | virginiasatyro/c-plus-plus | c71c59a1cb75ff36d116e72a70cd226cdebc68d8 | 69a57494fc2a82dc3285b93798f9ec8210d8057f | refs/heads/master | 2022-11-24T10:50:22.741089 | 2020-07-28T22:46:00 | 2020-07-28T22:46:00 | 147,515,932 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 738 | cpp | sobrecarga_funcoes.cpp | /***********************************************************************************
* File: sobrecarga_funcoes.cpp
* C++
* Author: Virgínia Sátyro
* License: Free - Open Source
* Created on 2020 April
*
* Funcoes sobrecarregadas.
***********************************************************************************/
#include <iostream>
using namespace std;
// funcao square para valores int
int square(int x)
{
cout << "square of integer " << x << " is ";
return x * x;
}
// funcao square para valores double
double square(double y)
{
cout << "square of double " << y << " is ";
return y * y;
}
int main()
{
cout << square(7) << endl; // 49
cout << square(7.5) << endl; // 56.25
return 0;
} |
86ab50913fc490fe4b4421a9735860a95d8b2d88 | b843121078c3d43753654d84e26f815c63b49f74 | /aviTypes.h | 0f4e731674c29a39d7ae9f486e087043069b3010 | [] | no_license | jzeeck/aviConverter | 950d4016eec9c2c12f9f853e85f16524c4e80345 | ef2bfdb06c80fc959181b0ffdae9cdbf69a678ad | refs/heads/master | 2016-08-04T13:43:05.385800 | 2014-01-22T12:50:47 | 2014-01-22T12:50:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,304 | h | aviTypes.h |
#ifndef AVI__HEADER
#define AVI__HEADER
#include <iostream>
#include <string>
using namespace std;
//Raw Data Types
typedef uint8_t BYTE; // 1byte
typedef uint16_t WORD; // 2bytes
typedef uint32_t DWORD; // 4bytes
typedef uint8_t SIZE[4];
typedef uint32_t FOURCC;// 4bytes
//Static values
static const DWORD VALID_AVI_START_HEADER = 0x46464952;//"RIFF";
static const DWORD VALID_LIST_HEADER = 0x5453494c;//"LIST";
/* The Flags in AVI File header */
#define AVIF_HASINDEX 0x00000010 /* Index at end of file */
#define AVIF_MUSTUSEINDEX 0x00000020
#define AVIF_ISINTERLEAVED 0x00000100
#define AVIF_TRUSTCKTYPE 0x00000800 /* Use CKType to find key frames */
#define AVIF_WASCAPTUREFILE 0x00010000
#define AVIF_COPYRIGHTED 0x00020000
//Helper functions
namespace auxiliary
{
void printFlags(DWORD flags) {
if (flags & AVIF_HASINDEX)
{
printf("%s\n", "This file has an index.");
}
if (flags & AVIF_MUSTUSEINDEX)
{
printf("%s\n", "This file must use index.");
}
//TODO more flags figure out what they do.
}
void printFourCC(string s, FOURCC fourCC) {
char c1 = (char)fourCC;
char c2 = (char)(fourCC>>8);
char c3 = (char)(fourCC>>16);
char c4 = (char)(fourCC>>24);
printf("%s: %c%c%c%c\n", s.c_str(),c1,c2,c3,c4);
}
void printSize(string s, FOURCC fourCC) {
//unsigned int num;
//num = (fourCC >> 24) | (fourCC >> 8 & 0x0000FF00) | (fourCC << 8 & 0x00FF0000) | (fourCC << 24);
//printf("%s: %u\n", s.c_str(),num);
printf("%s: %u\n", s.c_str(),fourCC);
}
void printDW(string s, FOURCC fourCC) {
//unsigned int num;
//num = (fourCC >> 24) | (fourCC >> 8 & 0x0000FF00) | (fourCC << 8 & 0x00FF0000) | (fourCC << 24);
//printf("%s: %u\n", s.c_str(),num);
printf("%s: %u\n", s.c_str(),fourCC);
}
void printDW(FOURCC fourCC) {
//unsigned int num;
//num = (fourCC >> 24) | (fourCC >> 8 & 0x0000FF00) | (fourCC << 8 & 0x00FF0000) | (fourCC << 24);
//printf("%s: %u\n", s.c_str(),num);
printf("%u\n",fourCC);
}
uint32_t getSizeAsInt(SIZE dwSize) {
uint32_t size = 0;
//size = size | (dwSize>>24);
//size = size | ((dwSize<<8)>>24)<<8;
//size = size | ((dwSize<<16)>>24)<<16;
size = dwSize[0] | (dwSize[1]<<8) | (dwSize[2]<<16) | (dwSize[3]<<24);
return size;
}
}
//AVI datatypes
class LIST {
public:
FOURCC dwList;
SIZE dwSize;
FOURCC dwFourCC;
// print List info
void print(){
auxiliary::printFourCC("dwList",dwList);
auxiliary::printSize("dwSize",auxiliary::getSizeAsInt(dwSize));
auxiliary::printFourCC("dwFourCC",dwFourCC);
}
//after this point we have the data. the size of the data is specefied by (dwSize - 4) bytes
};
class CHUNK {
public:
FOURCC dwFourCC;
DWORD dwSize;
//after this point we have the data. the size of the data is specefied by dwSize
};
class AVIMAINHEADER {
public:
FOURCC fcc; // 'avih'
SIZE cb; // size minus 8 bytes
DWORD dwMicroSecPerFrame;
DWORD dwMaxBytesPerSec;
DWORD dwPaddingGranularity; // pad to multiples of this size; normally 2K for cd-rom
DWORD dwFlags;
DWORD dwTotalFrames;
DWORD dwInitialFrames;
// There is one strl - List for each stream. If the number of strl - Lists inside the hdrl - List
// is different from MainAVIHeader::dwStreams, a fatal error should be reported.
DWORD dwStreams;
DWORD dwSuggestedBufferSize;
DWORD dwWidth;
DWORD dwHeight;
DWORD dwReserved[4];
void print(){
auxiliary::printFourCC("FOURCC",fcc);
auxiliary::printSize("Size minus 8 bytes",auxiliary::getSizeAsInt(cb));
auxiliary::printDW("MicroSecPerFrame",dwMicroSecPerFrame);
auxiliary::printDW("MaxBytesPerSec",dwMaxBytesPerSec);
auxiliary::printDW("PaddingGranularity",dwPaddingGranularity);
auxiliary::printFlags(dwFlags);
auxiliary::printDW("Total frames",dwTotalFrames);
auxiliary::printDW("Initial frames",dwInitialFrames);
auxiliary::printDW("Number of streams",dwStreams);
auxiliary::printDW("Suggested Buffer Size",dwSuggestedBufferSize);
auxiliary::printDW("Width",dwWidth);
auxiliary::printDW("Height",dwHeight);
float temp = dwMicroSecPerFrame * dwTotalFrames / 1000000;
uint32_t min = temp / 60;
//uint8_t sec = math::ciel(temp - (min * 60))m;
uint8_t sec = (temp - (min * 60));
printf("Running time %d min and %d sec.\n", min, sec);
}
};
#endif |
01fb08e294680b999ed17e5301f7335a7da40320 | 803c63295eb7c5793bca40f6a2572704013ec31e | /NOI/NOI2009/treapmod.cpp | 7937f6c734ad725edfbf9e93f233af67f7e59bda | [] | no_license | dxmtb/OICodeShare | 59587e3560e188e7d5332ba6fd5b54e7639f1866 | 3b4cc940e4819abcea3c513c4d555fea87ffc1f0 | refs/heads/master | 2016-08-07T12:46:49.748565 | 2013-05-17T05:19:59 | 2013-05-17T05:19:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,102 | cpp | treapmod.cpp | /*
* Problem: NOI2009 二叉查找树
* Time: 2011.06.13
* Author: dxmtb
* State: Solved
* Memo: 树形dp
*/
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN=75;
const int oo=0x7fffffff;
struct Node
{
int data,w,f;
}node[MAXN];
inline bool operator < (const Node &a,const Node &b)
{
return a.data<b.data;
}
inline void Min(int &a,int b)
{
if (b<a)
a=b;
}
int N,K;
int d[MAXN][MAXN][MAXN],c[MAXN][MAXN][MAXN];
int sum[MAXN];
pair<int,int> tmp[MAXN];
void dp(int i,int j,int p)
{
if (d[i][j][p]!=oo) return ;
for(int k=i;k<=j;k++)
tmp[k].first=node[k].w,tmp[k].second=k;
sort(tmp+i,tmp+j+1);
int rank[MAXN];
for(int k=i;k<=j;k++)
rank[tmp[k].second]=k-i+1;
int p1=0,p2=p;
for(int k=i;k<=j;k++)
{
int cost=sum[j]-sum[i-1];
int de=d[i][j][p];
if (rank[k]<=p)
p2--;
if (rank[k]<=p+1)
{
dp(i,k-1,p1);dp(k+1,j,p2);
Min(d[i][j][p],d[i][k-1][p1]+d[k+1][j][p2]+cost);
}
else
{
dp(i,k-1,p1);dp(k+1,j,p2);
Min(d[i][j][p],d[i][k-1][p1]+d[k+1][j][p2]+cost+K);
int t1=0,t2=0;
for(int t=i;t<k;t++)
if (rank[t]<rank[k])
t1++;
for(int t=k+1;t<=j;t++)
if (rank[t]<rank[k])
t2++;
dp(i,k-1,t1);dp(k+1,j,t2);
Min(d[i][j][p],d[i][k-1][t1]+d[k+1][j][t2]+cost+K*(t1-p1+t2-p2));
}
if (rank[k]<=p)
p1++;
if (d[i][j][p]!=de)
c[i][j][p]=k;
}
}
int main()
{
freopen("treapmod.in","r",stdin);
freopen("treapmod.out","w",stdout);
scanf("%d%d",&N,&K);
for(int i=1;i<=N;i++)
scanf("%d",&node[i].data);
for(int i=1;i<=N;i++)
scanf("%d",&node[i].w);
for(int i=1;i<=N;i++)
scanf("%d",&node[i].f);
sort(node+1,node+N+1);
/* for(int i=1;i<=N;i++)
printf("%d ",node[i].data);
printf("\n");
for(int i=1;i<=N;i++)
printf("%d ",node[i].w);
printf("\n");
for(int i=1;i<=N;i++)
printf("%d ",node[i].f);
printf("\n");*/
for(int i=0;i<=N;i++)
for(int j=0;j<=N;j++)
for(int k=0;k<=N;k++)
d[i][j][k]=oo;
for(int i=1;i<=N;i++)
{
d[i][i][0]=d[i][i][1]=node[i].f;
d[i][i-1][0]=0;d[i+1][i][0]=0;
sum[i]=sum[i-1]+node[i].f;
}
dp(1,N,0);
printf("%d\n",d[1][N][0]);
return 0;
}
|
a0c4b92247acb474ca549a505ff61d661b3a8aba | 43220f87a527e4b143e5969346c987a97e1e25bb | /semestr2/6_2/set_2.h | 5637aa9db4defba5f0e0ad350a8ad29e4bf1b399 | [] | no_license | TatianaZ/homework | 9c5b532e523a4a39ba1daee8c21e679a2c81ba41 | 6050110edca0af5a7afa2a48e2926a9f59efd73c | refs/heads/master | 2020-05-17T23:29:26.017717 | 2013-12-22T18:58:11 | 2013-12-22T18:58:11 | 3,537,314 | 2 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,890 | h | set_2.h | #pragma once
#include <iostream>
/**
@brief класс множество
элементы организованны в видем списка
@param element элемент множества
*next указатель на следующий элемент
*/
template <typename T>
class Set
{
public:
/**
@brief конструктор
*/
Set():next(NULL){}
/**
@brief конструктор
@param newElement новый элемент, добавляемый в множество
*/
Set(T newElement):next(NULL)
{
element = newElement;
}
/**
@brief функция добавления элемента
@param newElement новый элемент, добавляемый в множество
*/
void add(T newElement)
{
Set *temp = this;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = new Set<T>(newElement);
}
/**
@brief функция, удаляющая элемент из множества
@param delEltment элемент, удаляемый из множества
*/
void deleteElement(T delElement)
{
if (ownershipSet(delElement))
{
Set *temp = this->next;
if (temp->element == delElement) //head
{
this->next = this->next->next;
delete temp;
return;
}
temp = temp->next;
while (temp->next->element != delElement)
{
temp = temp->next;
}
if (temp->next->next == NULL) // tail
{
Set *temp2;
temp2 = temp->next;
temp->next = NULL;
delete temp2;
}
else
{
Set *temp2;
temp2 = temp->next;
temp->next = temp->next->next;
delete temp2;
}
}
}
/**
@brief функция, объединяющая два множества
@param newSet множество, с который объединяют
*/
void uniteSet(Set *newSet)
{
while (newSet != NULL)
{
if (!ownershipSet(newSet->element))
{
add(newSet->element);
}
newSet = newSet->next;
}
}
/**
@brief функция, осуществляющая пересечекние множеств
@param anotherSet множество, с которым пересекается
*/
void crossingSet(Set *anotherSet);
/**
@brief функция, проверяющая принадлежность множеству
@param elementSearch элемент, который проверяется
@return 1 принадлежит
0 не принадлежит
*/
bool ownershipSet(T elementSearch);
/**
@brief функция, проверяющая пустоту множества
@return 1 пусто
0 не пусто
*/
bool EmptySet();
private:
T element;
Set *next;
};
template <typename T>
bool Set<T>::EmptySet()
{
if (next == NULL)
{
return 1;
}
return 0;
}
template <typename T>
bool Set<T>::ownershipSet(T elementSearch)
{
Set<T> *temp = this->next;
while (temp != NULL)
{
if (temp->element == elementSearch)
{
return 1;
}
temp = temp->next;
}
return 0;
}
template <typename T>
void Set<T>::crossingSet(Set<T> *anotherSet)
{
Set<T> *temp = this->next;
while (temp != NULL)
{
if (!anotherSet->ownershipSet(temp->element))
{
deleteElement(temp->element);
}
temp = temp->next;
}
|
5b1b6862b04bfa3465ce1ae6175cc91404743ed9 | 189f52bf5454e724d5acc97a2fa000ea54d0e102 | /ras/fluidisedBed/0.59/pMean | 7cd4d3e556c4327fc581e4e11bdd2559907cbf8d | [] | no_license | pyotr777/openfoam_samples | 5399721dd2ef57545ffce68215d09c49ebfe749d | 79c70ac5795decff086dd16637d2d063fde6ed0d | refs/heads/master | 2021-01-12T16:52:18.126648 | 2016-11-05T08:30:29 | 2016-11-05T08:30:29 | 71,456,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,374 | pMean | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1606+ |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.59";
object pMean;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -1 -2 0 0 0 0];
internalField nonuniform List<scalar>
6000
(
108759
108759
108759
108758
108757
108757
108756
108755
108755
108755
108755
108755
108755
108756
108756
108756
108756
108755
108755
108755
108755
108755
108756
108756
108757
108758
108759
108759
108760
108759
108687
108688
108688
108687
108686
108685
108684
108684
108683
108683
108683
108684
108684
108685
108685
108685
108685
108684
108684
108683
108683
108683
108684
108685
108686
108687
108687
108688
108689
108688
108637
108638
108638
108638
108637
108636
108635
108635
108634
108634
108635
108636
108637
108637
108637
108637
108637
108636
108636
108635
108634
108634
108635
108636
108637
108637
108638
108639
108639
108638
108583
108583
108582
108582
108581
108580
108579
108578
108578
108578
108578
108579
108581
108582
108582
108582
108582
108581
108579
108578
108578
108578
108579
108580
108581
108582
108582
108583
108583
108584
108532
108531
108531
108530
108530
108529
108527
108526
108525
108524
108524
108524
108526
108527
108528
108528
108527
108525
108524
108524
108524
108525
108526
108528
108529
108530
108531
108531
108532
108533
108483
108482
108481
108479
108478
108478
108477
108476
108474
108473
108472
108471
108472
108473
108474
108474
108473
108472
108472
108472
108473
108475
108476
108477
108478
108479
108480
108481
108482
108483
108432
108430
108427
108425
108425
108425
108425
108425
108424
108423
108422
108421
108421
108421
108422
108422
108421
108421
108421
108422
108424
108425
108426
108426
108426
108425
108426
108427
108430
108432
108376
108372
108368
108367
108368
108370
108371
108372
108372
108372
108370
108370
108369
108369
108370
108370
108369
108370
108370
108371
108372
108373
108372
108371
108370
108368
108367
108368
108373
108377
108313
108308
108304
108303
108306
108310
108314
108316
108317
108318
108317
108317
108317
108317
108317
108317
108317
108317
108317
108318
108318
108318
108316
108314
108310
108306
108303
108304
108308
108314
108243
108239
108237
108238
108243
108249
108255
108260
108262
108263
108264
108264
108265
108265
108266
108266
108265
108265
108264
108265
108264
108262
108260
108255
108249
108242
108238
108237
108239
108243
108172
108169
108169
108172
108178
108187
108195
108202
108206
108209
108212
108213
108214
108215
108215
108215
108215
108213
108213
108212
108209
108206
108202
108195
108186
108177
108172
108169
108169
108172
108101
108100
108101
108105
108112
108123
108134
108143
108149
108154
108158
108161
108162
108164
108165
108165
108164
108162
108161
108158
108153
108149
108143
108133
108122
108111
108104
108100
108099
108101
108031
108030
108032
108036
108045
108057
108071
108083
108091
108097
108103
108108
108110
108112
108113
108113
108112
108110
108108
108103
108096
108090
108081
108069
108056
108044
108035
108031
108029
108030
107963
107962
107963
107968
107977
107990
108005
108019
108031
108039
108047
108054
108057
108059
108061
108061
108059
108057
108053
108046
108038
108029
108018
108004
107988
107976
107967
107962
107961
107962
107897
107896
107898
107901
107909
107922
107938
107954
107968
107979
107989
107998
108003
108005
108007
108007
108005
108002
107997
107988
107978
107967
107952
107936
107920
107908
107900
107897
107896
107896
107835
107834
107835
107837
107843
107853
107869
107886
107903
107917
107928
107938
107946
107950
107952
107952
107949
107945
107937
107926
107915
107901
107885
107867
107852
107842
107837
107835
107834
107834
107775
107774
107775
107777
107780
107787
107800
107817
107834
107850
107863
107874
107884
107889
107891
107891
107889
107883
107872
107862
107849
107832
107815
107798
107786
107779
107776
107775
107774
107774
107716
107716
107716
107717
107719
107724
107732
107746
107764
107781
107795
107804
107814
107822
107824
107824
107821
107813
107803
107793
107779
107761
107744
107731
107723
107718
107716
107715
107715
107715
107656
107657
107657
107657
107659
107662
107667
107676
107692
107709
107724
107733
107740
107748
107752
107751
107748
107739
107732
107722
107708
107690
107675
107666
107660
107657
107656
107655
107655
107655
107596
107596
107595
107595
107596
107599
107604
107611
107623
107638
107652
107661
107667
107673
107676
107676
107672
107666
107660
107651
107637
107621
107610
107602
107597
107594
107593
107593
107594
107594
107536
107535
107533
107532
107534
107537
107543
107550
107559
107572
107584
107593
107597
107600
107602
107601
107599
107597
107592
107583
107570
107558
107549
107542
107536
107533
107531
107532
107534
107535
107478
107477
107475
107475
107477
107480
107485
107491
107498
107508
107519
107527
107531
107532
107532
107532
107532
107531
107527
107518
107507
107497
107490
107485
107480
107476
107474
107475
107476
107478
107424
107422
107421
107422
107424
107426
107430
107433
107438
107446
107455
107463
107467
107468
107468
107468
107468
107467
107462
107454
107445
107438
107433
107429
107426
107424
107422
107421
107423
107424
107372
107370
107370
107371
107373
107374
107375
107376
107379
107384
107392
107399
107403
107404
107404
107404
107404
107403
107399
107391
107384
107378
107376
107375
107374
107373
107372
107371
107371
107372
107320
107320
107321
107322
107322
107322
107320
107319
107320
107323
107329
107335
107340
107341
107341
107341
107341
107339
107335
107328
107322
107319
107319
107320
107322
107322
107322
107321
107320
107320
107268
107269
107270
107271
107270
107267
107264
107261
107261
107262
107266
107271
107276
107277
107277
107277
107277
107275
107271
107265
107261
107260
107261
107264
107267
107270
107271
107271
107269
107269
107217
107218
107219
107218
107214
107209
107205
107201
107200
107200
107203
107207
107212
107213
107214
107214
107213
107211
107207
107202
107200
107200
107201
107204
107209
107214
107218
107219
107218
107217
107164
107165
107164
107161
107155
107148
107143
107139
107137
107137
107139
107143
107147
107150
107150
107150
107150
107147
107143
107139
107137
107137
107139
107143
107148
107154
107160
107164
107165
107164
107108
107109
107105
107099
107092
107085
107079
107075
107072
107072
107075
107079
107083
107086
107087
107087
107086
107083
107079
107074
107072
107072
107074
107079
107085
107092
107099
107105
107109
107109
107049
107048
107042
107035
107027
107020
107013
107009
107006
107007
107010
107014
107019
107022
107023
107023
107022
107019
107014
107010
107007
107006
107008
107013
107019
107027
107035
107042
107048
107049
106986
106983
106977
106969
106961
106952
106946
106941
106940
106941
106945
106950
106955
106958
106959
106959
106958
106955
106950
106945
106941
106940
106941
106945
106952
106960
106968
106976
106983
106986
106920
106916
106909
106901
106892
106884
106878
106875
106875
106877
106882
106887
106891
106894
106895
106895
106894
106891
106887
106882
106877
106875
106874
106877
106884
106892
106901
106909
106915
106919
106852
106848
106841
106832
106824
106816
106812
106811
106812
106816
106820
106824
106828
106831
106832
106832
106831
106828
106824
106819
106815
106812
106811
106811
106816
106823
106832
106840
106847
106851
106783
106779
106772
106764
106756
106751
106749
106750
106753
106756
106758
106762
106765
106767
106768
106768
106767
106765
106762
106758
106755
106752
106750
106749
106750
106755
106763
106771
106778
106782
106714
106710
106703
106696
106690
106688
106689
106691
106694
106696
106698
106700
106702
106703
106704
106704
106703
106702
106699
106697
106696
106694
106691
106689
106688
106690
106695
106703
106709
106713
106645
106641
106636
106631
106628
106629
106631
106633
106635
106636
106636
106637
106638
106639
106639
106639
106638
106638
106637
106636
106635
106635
106633
106630
106628
106628
106630
106635
106641
106645
106577
106574
106571
106568
106568
106570
106573
106575
106575
106575
106574
106573
106573
106573
106573
106573
106573
106573
106573
106573
106574
106575
106574
106572
106570
106568
106568
106570
106574
106577
106511
106509
106508
106508
106510
106512
106514
106515
106513
106512
106510
106508
106507
106507
106507
106506
106507
106507
106507
106509
106511
106513
106514
106514
106512
106510
106508
106508
106509
106511
106447
106446
106447
106449
106452
106453
106453
106452
106449
106446
106443
106441
106439
106439
106438
106438
106439
106439
106440
106442
106445
106448
106451
106453
106453
106451
106449
106447
106446
106447
106383
106384
106387
106390
106392
106392
106390
106386
106382
106378
106374
106372
106370
106370
106369
106369
106370
106370
106371
106373
106377
106381
106385
106389
106391
106391
106390
106387
106384
106383
106319
106321
106325
106328
106328
106326
106322
106316
106311
106306
106303
106301
106300
106299
106299
106299
106299
106300
106300
106302
106305
106310
106315
106321
106325
106328
106327
106325
106321
106319
106255
106257
106260
106261
106259
106255
106249
106243
106237
106233
106230
106228
106228
106228
106228
106228
106228
106228
106228
106229
106232
106236
106242
106248
106254
106259
106261
106260
106257
106255
106190
106192
106192
106190
106185
106180
106173
106166
106160
106157
106155
106155
106155
106155
106155
106155
106155
106155
106155
106155
106157
106160
106165
106172
106179
106185
106190
106192
106191
106190
106121
106122
106119
106115
106109
106102
106094
106087
106082
106080
106079
106079
106080
106080
106080
106080
106081
106080
106080
106080
106081
106083
106087
106094
106101
106109
106115
106119
106122
106122
106048
106047
106043
106037
106030
106021
106013
106007
106004
106003
106003
106003
106003
106004
106004
106004
106004
106004
106004
106004
106004
106005
106008
106014
106022
106030
106037
106043
106047
106048
105969
105968
105963
105956
105948
105939
105932
105928
105926
105925
105925
105925
105926
105926
105926
105927
105927
105927
105927
105927
105927
105927
105929
105933
105940
105948
105956
105963
105968
105970
105888
105885
105879
105872
105864
105856
105851
105848
105847
105846
105846
105846
105846
105847
105847
105847
105847
105848
105848
105848
105849
105849
105850
105853
105857
105865
105873
105880
105886
105888
105804
105801
105794
105787
105779
105773
105770
105768
105767
105766
105766
105766
105765
105765
105766
105766
105766
105767
105767
105768
105769
105770
105771
105772
105775
105780
105787
105795
105801
105804
105718
105714
105708
105701
105695
105691
105689
105688
105686
105685
105684
105683
105683
105683
105683
105683
105684
105684
105685
105687
105688
105689
105691
105691
105692
105696
105701
105708
105714
105718
105631
105628
105622
105616
105612
105609
105608
105606
105605
105603
105601
105600
105599
105599
105599
105599
105599
105600
105602
105604
105606
105608
105610
105610
105610
105612
105616
105621
105627
105630
105544
105541
105537
105532
105529
105527
105526
105525
105522
105520
105518
105516
105515
105514
105513
105513
105514
105515
105516
105519
105522
105525
105528
105529
105529
105529
105531
105535
105539
105543
105457
105454
105451
105447
105445
105445
105444
105442
105439
105436
105433
105431
105429
105427
105426
105426
105426
105427
105429
105432
105436
105440
105444
105446
105447
105446
105446
105449
105452
105454
105370
105367
105365
105363
105362
105362
105360
105357
105354
105351
105347
105344
105341
105339
105337
105336
105336
105337
105339
105342
105347
105352
105357
105361
105364
105364
105363
105363
105364
105366
105282
105281
105280
105280
105280
105278
105275
105271
105267
105263
105259
105254
105251
105248
105246
105245
105244
105245
105246
105249
105253
105258
105265
105272
105277
105280
105280
105278
105277
105278
105196
105196
105197
105198
105196
105192
105187
105181
105176
105172
105167
105162
105158
105154
105152
105150
105149
105149
105150
105152
105155
105159
105166
105176
105185
105191
105194
105193
105191
105191
105110
105111
105113
105112
105108
105102
105094
105088
105083
105078
105072
105067
105062
105058
105055
105053
105051
105051
105051
105052
105054
105057
105062
105071
105082
105094
105102
105104
105103
105102
105022
105024
105024
105020
105013
105005
104998
104992
104987
104981
104975
104968
104963
104959
104955
104952
104951
104949
104949
104949
104950
104951
104954
104961
104972
104986
105000
105008
105012
105011
104932
104932
104928
104921
104911
104904
104898
104894
104888
104881
104874
104867
104861
104857
104853
104850
104848
104846
104845
104845
104844
104844
104845
104849
104857
104871
104887
104902
104911
104914
104836
104833
104824
104814
104807
104802
104799
104793
104787
104779
104771
104763
104757
104752
104749
104746
104743
104742
104740
104739
104738
104737
104736
104736
104742
104754
104770
104787
104801
104807
104729
104723
104714
104706
104703
104701
104697
104691
104682
104673
104665
104657
104651
104647
104643
104640
104638
104636
104635
104634
104632
104630
104627
104626
104629
104637
104652
104668
104683
104692
104616
104610
104603
104600
104601
104599
104594
104585
104575
104565
104556
104549
104544
104539
104536
104534
104532
104531
104530
104529
104528
104526
104523
104520
104520
104525
104535
104550
104564
104573
104503
104499
104498
104500
104500
104495
104486
104475
104464
104454
104446
104439
104434
104431
104428
104426
104425
104424
104424
104424
104424
104424
104423
104421
104419
104419
104425
104436
104447
104455
104394
104395
104399
104401
104396
104387
104374
104362
104350
104341
104334
104328
104324
104321
104320
104318
104318
104318
104318
104319
104321
104324
104327
104328
104326
104323
104323
104328
104336
104342
104291
104295
104300
104298
104287
104273
104258
104245
104235
104226
104220
104216
104213
104211
104210
104209
104209
104210
104211
104213
104217
104222
104228
104234
104236
104233
104229
104229
104232
104236
104193
104196
104196
104187
104171
104155
104140
104128
104118
104111
104106
104103
104102
104101
104100
104100
104100
104101
104103
104106
104111
104117
104126
104134
104141
104143
104141
104137
104136
104136
104094
104093
104084
104069
104052
104035
104021
104009
104000
103995
103992
103991
103990
103990
103990
103990
103991
103992
103994
103997
104001
104009
104018
104029
104040
104047
104050
104048
104045
104043
103985
103980
103966
103949
103931
103915
103901
103891
103884
103880
103879
103879
103879
103880
103880
103881
103881
103882
103884
103886
103890
103897
103907
103919
103933
103945
103953
103956
103954
103952
103868
103859
103845
103828
103811
103795
103783
103774
103769
103767
103767
103768
103769
103771
103772
103773
103773
103774
103774
103775
103778
103784
103794
103807
103822
103836
103849
103857
103860
103859
103747
103738
103724
103708
103693
103679
103668
103662
103658
103656
103657
103659
103662
103664
103666
103667
103667
103667
103667
103667
103668
103673
103682
103693
103709
103725
103740
103752
103759
103761
103626
103618
103606
103592
103578
103567
103559
103554
103551
103550
103551
103554
103557
103561
103563
103564
103564
103563
103562
103561
103561
103566
103573
103583
103596
103612
103628
103642
103652
103656
103509
103502
103492
103480
103469
103460
103454
103451
103448
103448
103449
103453
103458
103462
103464
103465
103465
103463
103461
103459
103459
103463
103468
103477
103487
103501
103516
103530
103542
103547
103398
103392
103384
103374
103366
103360
103356
103353
103352
103352
103354
103358
103363
103367
103370
103371
103370
103368
103365
103363
103363
103366
103370
103376
103384
103395
103408
103421
103431
103437
103293
103289
103282
103275
103269
103265
103262
103261
103261
103262
103265
103268
103272
103275
103278
103279
103278
103277
103275
103273
103273
103274
103276
103281
103287
103295
103304
103315
103325
103330
103193
103190
103186
103182
103178
103175
103173
103173
103175
103177
103179
103181
103183
103185
103186
103187
103187
103187
103186
103186
103186
103186
103186
103189
103194
103201
103208
103216
103222
103227
103099
103097
103096
103094
103092
103089
103087
103088
103090
103092
103094
103094
103094
103095
103095
103095
103096
103096
103096
103098
103099
103098
103098
103100
103104
103110
103116
103122
103125
103128
103008
103009
103011
103009
103007
103004
103002
103002
103004
103006
103006
103005
103004
103003
103003
103003
103003
103004
103005
103007
103008
103009
103009
103011
103015
103020
103026
103031
103033
103034
102921
102923
102925
102924
102921
102918
102916
102915
102915
102916
102915
102914
102911
102910
102909
102909
102909
102910
102912
102914
102915
102917
102918
102921
102925
102930
102936
102941
102943
102943
102836
102836
102838
102836
102833
102829
102826
102824
102823
102822
102822
102820
102817
102815
102814
102813
102814
102815
102817
102819
102821
102822
102825
102828
102833
102839
102846
102851
102853
102853
102748
102748
102747
102745
102742
102738
102734
102731
102729
102727
102726
102724
102721
102719
102717
102717
102717
102718
102720
102723
102724
102726
102730
102735
102741
102747
102753
102758
102761
102762
102658
102657
102654
102650
102647
102644
102640
102637
102634
102631
102629
102627
102624
102621
102620
102619
102619
102620
102623
102625
102627
102630
102635
102640
102647
102654
102660
102664
102667
102669
102566
102565
102560
102556
102553
102550
102546
102542
102538
102534
102531
102528
102525
102523
102521
102520
102521
102522
102524
102527
102530
102535
102541
102547
102554
102561
102566
102569
102573
102574
102474
102472
102468
102465
102462
102458
102453
102447
102442
102437
102432
102429
102426
102424
102422
102422
102422
102423
102425
102429
102433
102440
102447
102455
102462
102469
102472
102475
102478
102480
102383
102381
102378
102375
102372
102367
102361
102354
102346
102340
102334
102330
102327
102325
102323
102323
102323
102325
102327
102331
102338
102345
102354
102362
102370
102377
102380
102383
102385
102387
102294
102292
102290
102287
102283
102276
102269
102260
102252
102244
102237
102232
102229
102227
102226
102225
102226
102227
102230
102235
102242
102251
102260
102270
102278
102284
102289
102292
102295
102296
102206
102205
102203
102199
102193
102186
102177
102168
102158
102149
102142
102136
102133
102131
102129
102129
102130
102132
102135
102140
102148
102157
102167
102176
102184
102191
102198
102203
102205
102206
102120
102119
102117
102111
102104
102095
102085
102075
102064
102055
102048
102042
102039
102037
102036
102035
102036
102038
102042
102047
102054
102063
102072
102082
102091
102099
102106
102113
102116
102117
102035
102034
102030
102023
102014
102004
101993
101982
101972
101963
101956
101951
101948
101946
101945
101945
101946
101948
101951
101956
101962
101970
101979
101988
101998
102006
102015
102022
102027
102028
101950
101948
101942
101933
101923
101912
101901
101890
101881
101873
101868
101863
101861
101860
101859
101859
101860
101862
101864
101868
101873
101879
101887
101896
101905
101915
101924
101932
101938
101941
101864
101860
101854
101844
101833
101821
101811
101801
101793
101787
101783
101780
101779
101778
101778
101778
101779
101780
101781
101784
101788
101792
101799
101806
101815
101825
101834
101843
101850
101853
101777
101773
101766
101755
101744
101734
101724
101716
101710
101706
101703
101701
101701
101700
101700
101701
101701
101702
101703
101705
101707
101710
101715
101721
101729
101738
101747
101756
101762
101766
101690
101686
101678
101669
101659
101650
101642
101635
101631
101629
101627
101626
101625
101625
101625
101626
101626
101627
101628
101629
101630
101632
101635
101640
101647
101655
101663
101670
101677
101680
101605
101600
101594
101587
101579
101571
101564
101559
101556
101555
101553
101553
101552
101552
101552
101552
101552
101553
101554
101555
101556
101558
101560
101564
101570
101577
101584
101589
101593
101597
101521
101518
101514
101509
101503
101497
101491
101487
101484
101483
101482
101481
101480
101479
101479
101480
101480
101481
101482
101483
101484
101486
101488
101492
101497
101503
101507
101511
101513
101516
101441
101439
101437
101434
101430
101425
101421
101417
101414
101412
101411
101409
101409
101408
101408
101408
101409
101409
101410
101412
101413
101415
101418
101422
101427
101430
101433
101436
101437
101438
101365
101364
101363
101360
101358
101355
101352
101348
101345
101342
101341
101339
101338
101338
101338
101338
101338
101339
101340
101341
101343
101346
101349
101353
101357
101359
101361
101363
101363
101364
101291
101291
101291
101289
101288
101285
101282
101279
101276
101273
101271
101270
101269
101268
101268
101268
101269
101269
101270
101272
101274
101277
101281
101285
101287
101289
101291
101292
101291
101291
101220
101220
101221
101220
101219
101216
101213
101210
101207
101205
101202
101201
101200
101199
101199
101199
101200
101200
101201
101203
101205
101208
101212
101216
101219
101221
101221
101221
101221
101220
101149
101150
101151
101151
101150
101147
101144
101141
101138
101136
101134
101133
101132
101131
101131
101131
101131
101132
101133
101134
101136
101139
101143
101147
101149
101151
101152
101151
101150
101149
101078
101079
101080
101080
101079
101078
101075
101073
101070
101068
101067
101065
101065
101064
101064
101064
101064
101065
101066
101067
101069
101071
101074
101077
101079
101080
101081
101080
101079
101078
101009
101010
101011
101011
101011
101010
101009
101008
101006
101005
101004
101003
101002
101002
101001
101002
101002
101002
101003
101004
101005
101007
101009
101010
101011
101011
101011
101011
101010
101009
100945
100945
100946
100946
100946
100947
100947
100947
100947
100946
100946
100945
100945
100944
100944
100944
100944
100945
100945
100946
100947
100948
100948
100948
100947
100946
100946
100945
100945
100944
100884
100884
100884
100884
100885
100887
100889
100890
100891
100891
100891
100890
100890
100890
100890
100890
100890
100890
100891
100891
100892
100892
100891
100889
100887
100885
100884
100883
100883
100883
100825
100825
100825
100826
100827
100830
100833
100836
100837
100838
100838
100838
100838
100838
100838
100838
100838
100838
100838
100839
100839
100838
100836
100833
100830
100827
100825
100824
100823
100824
100769
100769
100769
100770
100773
100777
100780
100783
100785
100787
100787
100787
100787
100787
100787
100787
100787
100787
100788
100788
100787
100786
100783
100780
100777
100773
100769
100767
100767
100767
100716
100715
100716
100719
100722
100726
100730
100733
100735
100736
100737
100738
100738
100738
100738
100738
100738
100738
100738
100738
100737
100735
100733
100730
100726
100722
100718
100715
100714
100714
100665
100665
100667
100670
100674
100677
100681
100684
100686
100688
100689
100689
100690
100690
100690
100690
100690
100690
100690
100689
100688
100687
100684
100681
100677
100673
100669
100666
100664
100663
100617
100617
100620
100623
100627
100630
100633
100636
100638
100640
100641
100642
100642
100642
100642
100643
100643
100643
100643
100642
100641
100639
100636
100633
100630
100626
100623
100619
100616
100616
100571
100572
100575
100578
100581
100584
100586
100589
100591
100593
100594
100595
100596
100596
100596
100596
100596
100596
100596
100595
100594
100592
100589
100587
100584
100581
100578
100575
100572
100571
100528
100529
100532
100534
100536
100539
100541
100543
100545
100547
100548
100549
100550
100550
100550
100550
100550
100550
100550
100549
100548
100546
100544
100541
100539
100537
100535
100532
100529
100528
100486
100487
100489
100491
100493
100494
100496
100498
100500
100502
100503
100504
100505
100505
100505
100505
100505
100505
100504
100503
100502
100500
100498
100497
100495
100493
100491
100489
100487
100486
100445
100445
100447
100448
100450
100451
100453
100454
100456
100458
100459
100460
100461
100461
100461
100461
100461
100461
100460
100459
100458
100456
100454
100453
100452
100451
100449
100448
100446
100446
100406
100406
100406
100407
100409
100410
100411
100412
100413
100415
100416
100418
100418
100419
100419
100419
100419
100418
100418
100416
100415
100413
100412
100411
100411
100410
100409
100408
100407
100407
100368
100368
100368
100369
100370
100370
100371
100371
100372
100374
100375
100377
100378
100378
100378
100378
100378
100378
100377
100375
100374
100373
100372
100371
100371
100370
100370
100369
100369
100369
100333
100332
100332
100332
100332
100332
100333
100333
100334
100335
100337
100338
100339
100339
100339
100340
100339
100339
100338
100337
100336
100334
100334
100333
100333
100333
100333
100333
100333
100334
100299
100298
100298
100298
100298
100297
100297
100298
100298
100299
100301
100301
100302
100303
100303
100303
100303
100303
100302
100301
100300
100299
100298
100298
100298
100299
100299
100299
100299
100300
100268
100267
100266
100266
100265
100265
100265
100265
100266
100266
100267
100268
100268
100269
100269
100269
100269
100269
100268
100268
100267
100266
100266
100266
100266
100266
100267
100267
100268
100269
100238
100237
100237
100236
100236
100235
100235
100235
100235
100236
100236
100236
100237
100237
100237
100237
100237
100237
100237
100237
100236
100236
100236
100236
100236
100237
100237
100237
100238
100239
100211
100210
100209
100209
100208
100208
100208
100207
100207
100207
100207
100207
100207
100207
100208
100208
100208
100208
100208
100208
100208
100208
100208
100209
100209
100209
100210
100210
100211
100212
100186
100185
100184
100184
100183
100183
100182
100181
100181
100180
100180
100180
100180
100180
100180
100181
100181
100181
100181
100181
100181
100182
100182
100183
100183
100184
100184
100185
100185
100186
100162
100161
100161
100160
100159
100159
100158
100157
100157
100156
100156
100156
100156
100156
100157
100157
100157
100157
100157
100157
100157
100157
100158
100159
100159
100160
100160
100161
100161
100162
100139
100138
100138
100138
100137
100136
100136
100135
100135
100135
100135
100135
100135
100135
100135
100135
100135
100135
100135
100135
100136
100136
100136
100137
100137
100138
100138
100138
100138
100139
100117
100117
100117
100117
100117
100117
100116
100116
100116
100115
100115
100115
100115
100115
100115
100115
100115
100115
100116
100116
100116
100116
100117
100117
100117
100117
100117
100117
100117
100117
100098
100098
100098
100098
100098
100098
100098
100098
100097
100097
100097
100097
100097
100097
100097
100097
100097
100097
100097
100098
100098
100098
100098
100098
100099
100098
100098
100098
100097
100097
100081
100080
100080
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100081
100080
100080
100080
100066
100065
100065
100064
100065
100065
100065
100065
100065
100065
100065
100066
100066
100066
100066
100066
100066
100066
100066
100066
100066
100065
100065
100065
100065
100065
100064
100064
100065
100065
100051
100050
100050
100050
100050
100050
100051
100051
100051
100052
100052
100052
100052
100052
100052
100052
100052
100052
100052
100052
100052
100051
100051
100051
100050
100050
100050
100050
100050
100051
100038
100037
100036
100036
100037
100038
100038
100039
100039
100039
100040
100040
100040
100040
100040
100040
100040
100040
100040
100040
100040
100039
100039
100038
100038
100037
100036
100036
100036
100038
100026
100025
100025
100025
100026
100027
100027
100028
100028
100029
100029
100029
100029
100030
100030
100030
100030
100030
100029
100029
100029
100029
100028
100028
100027
100026
100025
100025
100025
100025
100016
100015
100015
100016
100017
100018
100018
100019
100019
100020
100020
100020
100020
100020
100021
100021
100021
100021
100020
100020
100020
100020
100019
100019
100018
100017
100016
100015
100015
100016
100009
100008
100009
100009
100010
100011
100011
100012
100012
100012
100013
100013
100013
100013
100013
100013
100013
100013
100013
100013
100013
100012
100012
100011
100011
100010
100009
100009
100008
100009
100004
100004
100005
100005
100006
100006
100006
100006
100007
100007
100007
100007
100007
100007
100008
100008
100007
100007
100007
100007
100007
100007
100007
100006
100006
100006
100005
100005
100004
100004
100003
100003
100003
100003
100003
100003
100003
100003
100003
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100003
100003
100003
100003
100003
100003
100003
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100003
100003
100003
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
)
;
boundaryField
{
inlet
{
type calculated;
value nonuniform List<scalar>
30
(
108759
108759
108759
108758
108757
108757
108756
108755
108755
108755
108755
108755
108755
108756
108756
108756
108756
108755
108755
108755
108755
108755
108756
108756
108757
108758
108759
108759
108760
108759
)
;
}
outlet
{
type calculated;
value uniform 100000;
}
walls
{
type calculated;
value nonuniform List<scalar>
400
(
108759
108687
108637
108583
108532
108483
108432
108376
108313
108243
108172
108101
108031
107963
107897
107835
107775
107716
107656
107596
107536
107478
107424
107372
107320
107268
107217
107164
107108
107049
106986
106920
106852
106783
106714
106645
106577
106511
106447
106383
106319
106255
106190
106121
106048
105969
105888
105804
105718
105631
105544
105457
105370
105282
105196
105110
105022
104932
104836
104729
104616
104503
104394
104291
104193
104094
103985
103868
103747
103626
103509
103398
103293
103193
103099
103008
102921
102836
102748
102658
102566
102474
102383
102294
102206
102120
102035
101950
101864
101777
101690
101605
101521
101441
101365
101291
101220
101149
101078
101009
100945
100884
100825
100769
100716
100665
100617
100571
100528
100486
100445
100406
100368
100333
100299
100268
100238
100211
100186
100162
100139
100117
100098
100081
100066
100051
100038
100026
100016
100009
100004
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
108759
108688
108638
108584
108533
108483
108432
108377
108314
108243
108172
108101
108030
107962
107896
107834
107774
107715
107655
107594
107535
107478
107424
107372
107320
107269
107217
107164
107109
107049
106986
106919
106851
106782
106713
106645
106577
106511
106447
106383
106319
106255
106190
106122
106048
105970
105888
105804
105718
105630
105543
105454
105366
105278
105191
105102
105011
104914
104807
104692
104573
104455
104342
104236
104136
104043
103952
103859
103761
103656
103547
103437
103330
103227
103128
103034
102943
102853
102762
102669
102574
102480
102387
102296
102206
102117
102028
101941
101853
101766
101680
101597
101516
101438
101364
101291
101220
101149
101078
101009
100944
100883
100824
100767
100714
100663
100616
100571
100528
100486
100446
100407
100369
100334
100300
100269
100239
100212
100186
100162
100139
100117
100097
100080
100065
100051
100038
100025
100016
100009
100004
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
)
;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
| |
08c130777490917e99187e24bb9b192a8631a1c7 | 900ac54ee1b249b52e55504148f14ea2cd964b10 | /Sources/Solver/Mitosis.Formatters/DeSerializingPoleUpdater.h | eb5050df8008e6bca427ccc6014a48c411b05904 | [
"MIT"
] | permissive | m-krivov/MiCoSi | 1d5bf248bcd7908837aeee3a1fb4c7827d94dd1e | a0f32bacb2e09f23518a5629b4ccc2ca27e67209 | refs/heads/master | 2021-09-10T04:48:53.927491 | 2021-08-27T10:56:34 | 2021-08-27T10:56:34 | 165,875,825 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 635 | h | DeSerializingPoleUpdater.h |
#pragma once
#include "Mitosis.Objects/Pole.h"
class DeSerializingPoleUpdater : public IPoleUpdater
{
public:
DeSerializingPoleUpdater() = default;
DeSerializingPoleUpdater(const DeSerializingPoleUpdater &) = default;
DeSerializingPoleUpdater &operator =(const DeSerializingPoleUpdater &) = default;
virtual IClonnable *Clone() const override
{ return new DeSerializingPoleUpdater(); }
virtual void SetInitial(Pole *left, Pole *right, Random::State &state) override
{ /*nothing*/ }
virtual void MovePoles(Pole *left, Pole *right, real time, Random::State &state) override
{ /*nothing*/ }
};
|
93b54722ad95c89fb8f6facc2d92b72439ff47a6 | 5631f368f153a855fbc1bbc59bf2217f88681d50 | /eccezionebacca.h | 564dce8cac4054d79978eb901292dfeb03d2c85e | [] | no_license | piaz97/monsterKalk | 77f4214ca4310e04a45a0b3c535378b87de123be | 27d2153b9c6a7461f2197d3a95e87e18616ccd1f | refs/heads/master | 2020-03-29T02:10:16.154250 | 2018-09-19T10:12:55 | 2018-09-19T10:12:55 | 149,423,468 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 236 | h | eccezionebacca.h | #ifndef ECCEZIONEBACCA_H
#define ECCEZIONEBACCA_H
#include "eccezione.h"
class EccezioneBacca:public Eccezione{
public:
EccezioneBacca(std::string messaggio="");
std::string getMessaggio() const;
};
#endif // ECCEZIONEBACCA_H
|
d203c17a65a232e0e3d2a02c54233e8d6205ae88 | 5de7df0be411b4bad61f927cae845bdb8223308f | /src/libs/vtkh/rendering/VolumeRenderer.cpp | 71bea3ea356afaf3e1a8ef56de9f88af72705b24 | [
"BSD-3-Clause",
"Zlib"
] | permissive | Alpine-DAV/ascent | cb40429167a93c62f78fe650a0121258be279162 | e52b7bb8c9fd131f2fd49edf58037cc5ef77a166 | refs/heads/develop | 2023-09-06T07:57:11.558238 | 2023-08-25T16:05:31 | 2023-08-25T16:05:31 | 81,366,855 | 151 | 61 | NOASSERTION | 2023-09-13T19:31:09 | 2017-02-08T19:21:22 | C++ | UTF-8 | C++ | false | false | 25,276 | cpp | VolumeRenderer.cpp | #include "VolumeRenderer.hpp"
#include <vtkh/utils/vtkm_array_utils.hpp>
#include <vtkh/compositing/Compositor.hpp>
#include <vtkh/Logger.hpp>
#include <vtkm/rendering/CanvasRayTracer.h>
#include <memory>
#ifdef VTKH_PARALLEL
#include <mpi.h>
#endif
#include <vtkm/cont/ColorTable.h>
#include <vtkm/rendering/ConnectivityProxy.h>
#include <vtkh/compositing/PartialCompositor.hpp>
#include <vtkm/rendering/raytracing/VolumeRendererStructured.h>
#include <vtkm/rendering/raytracing/RayOperations.h>
#include <vtkm/rendering/raytracing/Camera.h>
#include <vtkh/compositing/VolumePartial.hpp>
#define VTKH_OPACITY_CORRECTION 10.f
namespace vtkh {
namespace detail
{
struct VisOrdering
{
int m_rank;
int m_domain_index;
int m_order;
float m_minz;
};
struct DepthOrder
{
inline bool operator()(const VisOrdering &lhs, const VisOrdering &rhs)
{
return lhs.m_minz < rhs.m_minz;
}
};
struct RankOrder
{
inline bool operator()(const VisOrdering &lhs, const VisOrdering &rhs)
{
if(lhs.m_rank < rhs.m_rank)
{
return true;
}
else if(lhs.m_rank == rhs.m_rank)
{
return lhs.m_domain_index < rhs.m_domain_index;
}
return false;
}
};
vtkm::cont::ArrayHandle<vtkm::Vec4f_32>
convert_table(const vtkm::cont::ColorTable& colorTable)
{
constexpr vtkm::Float32 conversionToFloatSpace = (1.0f / 255.0f);
vtkm::cont::ArrayHandle<vtkm::Vec4ui_8> temp;
{
vtkm::cont::ScopedRuntimeDeviceTracker tracker(vtkm::cont::DeviceAdapterTagSerial{});
colorTable.Sample(1024, temp);
}
vtkm::cont::ArrayHandle<vtkm::Vec4f_32> color_map;
color_map.Allocate(1024);
auto portal = color_map.WritePortal();
auto colorPortal = temp.ReadPortal();
for (vtkm::Id i = 0; i < 1024; ++i)
{
auto color = colorPortal.Get(i);
vtkm::Vec4f_32 t(color[0] * conversionToFloatSpace,
color[1] * conversionToFloatSpace,
color[2] * conversionToFloatSpace,
color[3] * conversionToFloatSpace);
portal.Set(i, t);
}
return color_map;
}
class VolumeWrapper
{
protected:
vtkm::cont::DataSet m_data_set;
vtkm::Range m_scalar_range;
std::string m_field_name;
vtkm::Float32 m_sample_dist;
vtkm::cont::ArrayHandle<vtkm::Vec4f_32> m_color_map;
public:
VolumeWrapper() = delete;
VolumeWrapper(vtkm::cont::DataSet &data_set)
: m_data_set(data_set)
{
}
virtual ~VolumeWrapper()
{
}
void sample_distance(const vtkm::Float32 &distance)
{
m_sample_dist = distance;
}
void field(const std::string &field_name)
{
m_field_name = field_name;
}
void scalar_range(vtkm::Range &range)
{
m_scalar_range = range;
}
void color_map(vtkm::cont::ArrayHandle<vtkm::Vec4f_32> &color_map)
{
m_color_map = color_map;
}
virtual void
render(const vtkm::rendering::Camera &camera,
vtkm::rendering::CanvasRayTracer &canvas,
std::vector<VolumePartial<float>> &partials) = 0;
};
void vtkm_to_partials(vtkm::rendering::PartialVector32 &vtkm_partials,
std::vector<VolumePartial<float>> &partials)
{
const int num_vecs = vtkm_partials.size();
std::vector<int> offsets;
offsets.reserve(num_vecs);
int total_size = 0;
for(int i = 0; i < num_vecs; ++i)
{
const int size = vtkm_partials[i].PixelIds.GetNumberOfValues();
offsets.push_back(total_size);
total_size += size;
}
partials.resize(total_size);
for(int i = 0; i < num_vecs; ++i)
{
const int size = vtkm_partials[i].PixelIds.GetNumberOfValues();
auto pixel_ids = vtkm_partials[i].PixelIds.ReadPortal();
auto distances = vtkm_partials[i].Distances.ReadPortal();
auto colors = vtkm_partials[i].Buffer.Buffer.ReadPortal();
const int offset = offsets[i];
#ifdef VTKH_OPENMP_ENABLED
#pragma omp parallel for
#endif
for(int p = 0; p < size; ++p)
{
VolumePartial<float> &partial = partials[offset+p];
partial.m_pixel[0] = colors.Get(p*4 + 0);
partial.m_pixel[1] = colors.Get(p*4 + 1);
partial.m_pixel[2] = colors.Get(p*4 + 2);
partial.m_alpha = colors.Get(p*4 + 3);
partial.m_pixel_id = pixel_ids.Get(p);
partial.m_depth = distances.Get(p);
}
}
}
class UnstructuredWrapper : public VolumeWrapper
{
vtkm::rendering::ConnectivityProxy m_tracer;
public:
UnstructuredWrapper(vtkm::cont::DataSet &data_set)
: VolumeWrapper(data_set),
m_tracer(data_set, "")
{
}
virtual void
render(const vtkm::rendering::Camera &camera,
vtkm::rendering::CanvasRayTracer &canvas,
std::vector<VolumePartial<float>> &partials) override
{
const vtkm::cont::CoordinateSystem &coords = m_data_set.GetCoordinateSystem();
vtkm::rendering::raytracing::Camera rayCamera;
vtkm::rendering::raytracing::Ray<vtkm::Float32> rays;
vtkm::Int32 width = (vtkm::Int32) canvas.GetWidth();
vtkm::Int32 height = (vtkm::Int32) canvas.GetHeight();
rayCamera.SetParameters(camera, width, height);
rayCamera.CreateRays(rays, coords.GetBounds());
rays.Buffers.at(0).InitConst(0.f);
vtkm::rendering::raytracing::RayOperations::MapCanvasToRays(rays, camera, canvas);
m_tracer.SetSampleDistance(m_sample_dist);
m_tracer.SetColorMap(m_color_map);
m_tracer.SetScalarField(m_field_name);
m_tracer.SetScalarRange(m_scalar_range);
vtkm::rendering::PartialVector32 vtkm_partials;
vtkm_partials = m_tracer.PartialTrace(rays);
vtkm_to_partials(vtkm_partials, partials);
}
};
class StructuredWrapper : public VolumeWrapper
{
public:
StructuredWrapper(vtkm::cont::DataSet &data_set)
: VolumeWrapper(data_set)
{
}
virtual void
render(const vtkm::rendering::Camera &camera,
vtkm::rendering::CanvasRayTracer &canvas,
std::vector<VolumePartial<float>> &partials) override
{
const vtkm::cont::UnknownCellSet &cellset = m_data_set.GetCellSet();
const vtkm::cont::Field &field = m_data_set.GetField(m_field_name);
const vtkm::cont::CoordinateSystem &coords = m_data_set.GetCoordinateSystem();
vtkm::rendering::raytracing::Camera rayCamera;
vtkm::rendering::raytracing::Ray<vtkm::Float32> rays;
vtkm::Int32 width = (vtkm::Int32) canvas.GetWidth();
vtkm::Int32 height = (vtkm::Int32) canvas.GetHeight();
rayCamera.SetParameters(camera, width, height);
rayCamera.CreateRays(rays, coords.GetBounds());
rays.Buffers.at(0).InitConst(0.f);
vtkm::rendering::raytracing::RayOperations::MapCanvasToRays(rays, camera, canvas);
vtkm::rendering::raytracing::VolumeRendererStructured tracer;
tracer.SetSampleDistance(m_sample_dist);
tracer.SetData(coords,
field,
cellset.AsCellSet<vtkm::cont::CellSetStructured<3>>(),
m_scalar_range);
tracer.SetColorMap(m_color_map);
tracer.Render(rays);
// Convert the rays to partial composites
const int ray_size = rays.NumRays;
// partials use the max distance
auto depths = rays.MaxDistance.ReadPortal();
auto pixel_ids = rays.PixelIdx.ReadPortal();
auto colors = rays.Buffers.at(0).Buffer.ReadPortal();
// TODO: better way? we could do this in parallel if we
// don't check the alpha
partials.reserve(ray_size);
for(int i = 0; i < ray_size; ++i)
{
const int offset = i * 4;
float alpha = colors.Get(offset + 3);
if(alpha < 0.001f) continue;
VolumePartial<float> partial;
partial.m_pixel[0] = colors.Get(offset + 0);
partial.m_pixel[1] = colors.Get(offset + 1);
partial.m_pixel[2] = colors.Get(offset + 2);
partial.m_alpha = alpha;
partial.m_pixel_id = pixel_ids.Get(i);
partial.m_depth = depths.Get(i);
partials.push_back(std::move(partial));
}
}
};
void partials_to_canvas(std::vector<VolumePartial<float>> &partials,
const vtkm::rendering::Camera &camera,
vtkm::rendering::CanvasRayTracer &canvas)
{
// partial depths are in world space but the canvas depths
// are in image space. We have to find the intersection
// point to project it into image space to get the correct
// depths for annotations
vtkm::Id width = canvas.GetWidth();
vtkm::Id height = canvas.GetHeight();
vtkm::Matrix<vtkm::Float32, 4, 4> projview =
vtkm::MatrixMultiply(camera.CreateProjectionMatrix(width, height),
camera.CreateViewMatrix());
const vtkm::Vec3f_32 origin = camera.GetPosition();
float fov_y = camera.GetFieldOfView();
float fov_x = fov_y;
if(width != height)
{
vtkm::Float32 fovyRad = fov_y * vtkm::Pi_180f();
vtkm::Float32 verticalDistance = vtkm::Tan(0.5f * fovyRad);
vtkm::Float32 aspectRatio = vtkm::Float32(width) / vtkm::Float32(height);
vtkm::Float32 horizontalDistance = aspectRatio * verticalDistance;
vtkm::Float32 fovxRad = 2.0f * vtkm::ATan(horizontalDistance);
fov_x = fovxRad / vtkm::Pi_180f();
}
vtkm::Vec3f_32 look = camera.GetLookAt() - origin;
vtkm::Normalize(look);
vtkm::Vec3f_32 up = camera.GetViewUp();
const vtkm::Float32 thx = tanf((fov_x * vtkm::Pi_180f()) * .5f);
const vtkm::Float32 thy = tanf((fov_y * vtkm::Pi_180f()) * .5f);
vtkm::Vec3f_32 ru = vtkm::Cross(look, up);
vtkm::Normalize(ru);
vtkm::Vec3f_32 rv = vtkm::Cross(ru, look);
vtkm::Normalize(rv);
vtkm::Vec3f_32 delta_x = ru * (2 * thx / (float)width);
vtkm::Vec3f_32 delta_y = ru * (2 * thy / (float)height);
vtkm::Float32 zoom = camera.GetZoom();
if(zoom > 0)
{
delta_x[0] = delta_x[0] / zoom;
delta_x[1] = delta_x[1] / zoom;
delta_x[2] = delta_x[2] / zoom;
delta_y[0] = delta_y[0] / zoom;
delta_y[1] = delta_y[1] / zoom;
delta_y[2] = delta_y[2] / zoom;
}
const int size = partials.size();
auto colors = canvas.GetColorBuffer().WritePortal();
auto depths = canvas.GetDepthBuffer().WritePortal();
#ifdef VTKH_OPENMP_ENABLED
#pragma omp parallel for
#endif
for(int p = 0; p < size; ++p)
{
const int pixel_id = partials[p].m_pixel_id;
const int i = pixel_id % width;
const int j = pixel_id / width;
vtkm::Vec3f_32 dir;
dir = look + delta_x * ((2.f * float(i) - float(width)) / 2.0f) +
delta_y * ((2.f * float(j) - float(height)) / 2.0f);
vtkm::Normalize(dir);
const float world_depth = partials[p].m_depth;
vtkm::Vec3f_32 pos = origin + world_depth * dir;
vtkm::Vec4f_32 point(pos[0], pos[1], pos[2], 1.f);
vtkm::Vec4f_32 newpoint;
newpoint = vtkm::MatrixMultiply(projview, point);
// don't push it all the way(.49 instead of .5) so that
// subtle differences allow bounding box annotations don't
// draw in front of the back
const float image_depth = 0.5f*(newpoint[2] / newpoint[3]) + 0.49f;
vtkm::Vec4f_32 color;
color[0] = partials[p].m_pixel[0];
color[1] = partials[p].m_pixel[1];
color[2] = partials[p].m_pixel[2];
color[3] = partials[p].m_alpha;
vtkm::Vec4f_32 inColor = colors.Get(pixel_id);
// We crafted the rendering so that all new colors are in front
// of the colors that exist in the canvas
// if transparency exists, all alphas have been pre-multiplied
vtkm::Float32 alpha = (1.f - color[3]);
color[0] = color[0] + inColor[0] * alpha;
color[1] = color[1] + inColor[1] * alpha;
color[2] = color[2] + inColor[2] * alpha;
color[3] = inColor[3] * alpha + color[3];
colors.Set(pixel_id, color);
depths.Set(pixel_id, image_depth);
}
}
} // namespace detail
VolumeRenderer::VolumeRenderer()
{
typedef vtkm::rendering::MapperVolume TracerType;
m_tracer = std::make_shared<TracerType>();
this->m_mapper = m_tracer;
m_tracer->SetCompositeBackground(false);
//
// add some default opacity to the color table
//
m_color_table.AddPointAlpha(0.0f, .02);
m_color_table.AddPointAlpha(.0f, .5);
m_num_samples = 100.f;
m_has_unstructured = false;
}
VolumeRenderer::~VolumeRenderer()
{
ClearWrappers();
}
void
VolumeRenderer::Update()
{
VTKH_DATA_OPEN(this->GetName());
#ifdef VTKH_ENABLE_LOGGING
VTKH_DATA_ADD("device", GetCurrentDevice());
long long int in_cells = this->m_input->GetNumberOfCells();
VTKH_DATA_ADD("input_cells", in_cells);
VTKH_DATA_ADD("input_domains", this->m_input->GetNumberOfDomains());
int in_topo_dims;
bool in_structured = this->m_input->IsStructured(in_topo_dims);
if(in_structured)
{
VTKH_DATA_ADD("in_topology", "structured");
}
else
{
VTKH_DATA_ADD("in_topology", "unstructured");
}
#endif
PreExecute();
DoExecute();
PostExecute();
VTKH_DATA_CLOSE();
}
void VolumeRenderer::SetColorTable(const vtkm::cont::ColorTable &color_table)
{
m_color_table = color_table;
}
void VolumeRenderer::CorrectOpacity()
{
const float correction_scalar = VTKH_OPACITY_CORRECTION;
float samples = m_num_samples;
float ratio = correction_scalar / samples;
vtkm::cont::ColorTable corrected;
corrected = m_color_table.MakeDeepCopy();
int num_points = corrected.GetNumberOfPointsAlpha();
for(int i = 0; i < num_points; i++)
{
vtkm::Vec<vtkm::Float64,4> point;
corrected.GetPointAlpha(i,point);
point[1] = 1. - vtkm::Pow((1. - point[1]), double(ratio));
corrected.UpdatePointAlpha(i,point);
}
m_corrected_color_table = corrected;
}
void
VolumeRenderer::DoExecute()
{
if(m_input->OneDomainPerRank() && !m_has_unstructured)
{
// Danger: this logic only works if there is exactly one per rank
RenderOneDomainPerRank();
}
else
{
RenderMultipleDomainsPerRank();
}
}
void
VolumeRenderer::RenderOneDomainPerRank()
{
if(m_mapper.get() == 0)
{
std::string msg = "Renderer Error: no renderer was set by sub-class";
throw Error(msg);
}
m_tracer->SetSampleDistance(m_sample_dist);
int total_renders = static_cast<int>(m_renders.size());
int num_domains = static_cast<int>(m_input->GetNumberOfDomains());
if(num_domains > 1)
{
throw Error("RenderOneDomainPerRank: this should never happend.");
}
for(int dom = 0; dom < num_domains; ++dom)
{
vtkm::cont::DataSet data_set;
vtkm::Id domain_id;
m_input->GetDomain(0, data_set, domain_id);
if(!data_set.HasField(m_field_name))
{
continue;
}
const vtkm::cont::UnknownCellSet &cellset = data_set.GetCellSet();
const vtkm::cont::Field &field = data_set.GetField(m_field_name);
const vtkm::cont::CoordinateSystem &coords = data_set.GetCoordinateSystem();
if(cellset.GetNumberOfCells() == 0) continue;
for(int i = 0; i < total_renders; ++i)
{
m_mapper->SetActiveColorTable(m_corrected_color_table);
Render::vtkmCanvas &canvas = m_renders[i].GetCanvas();
const vtkmCamera &camera = m_renders[i].GetCamera();
m_mapper->SetCanvas(&canvas);
m_mapper->RenderCells(cellset,
coords,
field,
m_corrected_color_table,
camera,
m_range);
}
}
if(m_do_composite)
{
this->Composite(total_renders);
}
}
void
VolumeRenderer::RenderMultipleDomainsPerRank()
{
// We are treating this as the most general case
// where we could have a mix of structured and
// unstructured data sets. There are zero
// assumptions
// this might be smaller than the input since
// it is possible for cell sets to be empty
const int num_domains = m_wrappers.size();
const int total_renders = static_cast<int>(m_renders.size());
vtkm::cont::ArrayHandle<vtkm::Vec4f_32> color_map
= detail::convert_table(this->m_corrected_color_table);
vtkm::cont::ArrayHandle<vtkm::Vec4f_32> color_map2
= detail::convert_table(this->m_color_table);
// render/domain/result
std::vector<std::vector<std::vector<VolumePartial<float>>>> render_partials;
render_partials.resize(total_renders);
for(int i = 0; i < total_renders; ++i)
{
render_partials[i].resize(num_domains);
}
for(int i = 0; i < num_domains; ++i)
{
detail::VolumeWrapper *wrapper = m_wrappers[i];
wrapper->sample_distance(m_sample_dist);
wrapper->color_map(color_map);
wrapper->field(m_field_name);
wrapper->scalar_range(m_range);
for(int r = 0; r < total_renders; ++r)
{
Render::vtkmCanvas &canvas = m_renders[r].GetCanvas();
const vtkmCamera &camera = m_renders[r].GetCamera();
wrapper->render(camera, canvas, render_partials[r][i]);
}
}
PartialCompositor<VolumePartial<float>> compositor;
#ifdef VTKH_PARALLEL
compositor.set_comm_handle(GetMPICommHandle());
#endif
// composite
for(int r = 0; r < total_renders; ++r)
{
std::vector<VolumePartial<float>> res;
compositor.composite(render_partials[r],res);
if(vtkh::GetMPIRank() == 0)
{
detail::partials_to_canvas(res,
m_renders[r].GetCamera(),
m_renders[r].GetCanvas());
}
}
}
void
VolumeRenderer::PreExecute()
{
Renderer::PreExecute();
CorrectOpacity();
vtkm::Vec<vtkm::Float32,3> extent;
extent[0] = static_cast<vtkm::Float32>(this->m_bounds.X.Length());
extent[1] = static_cast<vtkm::Float32>(this->m_bounds.Y.Length());
extent[2] = static_cast<vtkm::Float32>(this->m_bounds.Z.Length());
vtkm::Float32 dist = vtkm::Magnitude(extent) / m_num_samples;
m_sample_dist = dist;
}
void
VolumeRenderer::PostExecute()
{
// do nothing and override compositing since
// we already did it
}
void
VolumeRenderer::SetNumberOfSamples(const int num_samples)
{
if(num_samples < 1)
{
throw Error("Volume rendering samples must be greater than 0");
}
m_num_samples = num_samples;
}
Renderer::vtkmCanvasPtr
VolumeRenderer::GetNewCanvas(int width, int height)
{
return std::make_shared<vtkm::rendering::CanvasRayTracer>(width, height);
}
float
VolumeRenderer::FindMinDepth(const vtkm::rendering::Camera &camera,
const vtkm::Bounds &bounds) const
{
vtkm::Vec<vtkm::Float64,3> center = bounds.Center();
vtkm::Vec<vtkm::Float64,3> fcenter;
fcenter[0] = static_cast<vtkm::Float32>(center[0]);
fcenter[1] = static_cast<vtkm::Float32>(center[1]);
fcenter[2] = static_cast<vtkm::Float32>(center[2]);
vtkm::Vec<vtkm::Float32,3> pos = camera.GetPosition();
vtkm::Float32 dist = vtkm::Magnitude(fcenter - pos);
return dist;
}
void
VolumeRenderer::Composite(const int &num_images)
{
const int num_domains = static_cast<int>(m_input->GetNumberOfDomains());
m_compositor->SetCompositeMode(Compositor::VIS_ORDER_BLEND);
FindVisibilityOrdering();
for(int i = 0; i < num_images; ++i)
{
float* color_buffer =
&GetVTKMPointer(m_renders[i].GetCanvas().GetColorBuffer())[0][0];
float* depth_buffer =
GetVTKMPointer(m_renders[i].GetCanvas().GetDepthBuffer());
int height = m_renders[i].GetCanvas().GetHeight();
int width = m_renders[i].GetCanvas().GetWidth();
m_compositor->AddImage(color_buffer,
depth_buffer,
width,
height,
m_visibility_orders[i][0]);
Image result = m_compositor->Composite();
const std::string image_name = m_renders[i].GetImageName() + ".png";
#ifdef VTKH_PARALLEL
if(vtkh::GetMPIRank() == 0)
{
#endif
ImageToCanvas(result, m_renders[i].GetCanvas(), true);
#ifdef VTKH_PARALLEL
}
#endif
m_compositor->ClearImages();
} // for image
}
void
VolumeRenderer::DepthSort(int num_domains,
std::vector<float> &min_depths,
std::vector<int> &local_vis_order)
{
if(min_depths.size() != num_domains)
{
throw Error("min depths size does not equal the number of domains");
}
if(local_vis_order.size() != num_domains)
{
throw Error("local vis order not equal to number of domains");
}
#ifdef VTKH_PARALLEL
int root = 0;
MPI_Comm comm = MPI_Comm_f2c(vtkh::GetMPICommHandle());
int num_ranks = vtkh::GetMPISize();
int rank = vtkh::GetMPIRank();
int *domain_counts = NULL;
int *domain_offsets = NULL;
int *vis_order = NULL;
float *depths = NULL;
if(rank == root)
{
domain_counts = new int[num_ranks];
domain_offsets = new int[num_ranks];
}
MPI_Gather(&num_domains,
1,
MPI_INT,
domain_counts,
1,
MPI_INT,
root,
comm);
int depths_size = 0;
if(rank == root)
{
//scan for dispacements
domain_offsets[0] = 0;
for(int i = 1; i < num_ranks; ++i)
{
domain_offsets[i] = domain_offsets[i - 1] + domain_counts[i - 1];
}
for(int i = 0; i < num_ranks; ++i)
{
depths_size += domain_counts[i];
}
depths = new float[depths_size];
}
MPI_Gatherv(&min_depths[0],
num_domains,
MPI_FLOAT,
depths,
domain_counts,
domain_offsets,
MPI_FLOAT,
root,
comm);
if(rank == root)
{
std::vector<detail::VisOrdering> order;
order.resize(depths_size);
for(int i = 0; i < num_ranks; ++i)
{
for(int c = 0; c < domain_counts[i]; ++c)
{
int index = domain_offsets[i] + c;
order[index].m_rank = i;
order[index].m_domain_index = c;
order[index].m_minz = depths[index];
}
}
std::sort(order.begin(), order.end(), detail::DepthOrder());
for(int i = 0; i < depths_size; ++i)
{
order[i].m_order = i;
}
std::sort(order.begin(), order.end(), detail::RankOrder());
vis_order = new int[depths_size];
for(int i = 0; i < depths_size; ++i)
{
vis_order[i] = order[i].m_order;
}
}
MPI_Scatterv(vis_order,
domain_counts,
domain_offsets,
MPI_INT,
&local_vis_order[0],
num_domains,
MPI_INT,
root,
comm);
if(rank == root)
{
delete[] domain_counts;
delete[] domain_offsets;
delete[] vis_order;
delete[] depths;
}
#else
std::vector<detail::VisOrdering> order;
order.resize(num_domains);
for(int i = 0; i < num_domains; ++i)
{
order[i].m_rank = 0;
order[i].m_domain_index = i;
order[i].m_minz = min_depths[i];
}
std::sort(order.begin(), order.end(), detail::DepthOrder());
for(int i = 0; i < num_domains; ++i)
{
order[i].m_order = i;
}
std::sort(order.begin(), order.end(), detail::RankOrder());
for(int i = 0; i < num_domains; ++i)
{
local_vis_order[i] = order[i].m_order;
}
#endif
}
void
VolumeRenderer::FindVisibilityOrdering()
{
const int num_domains = static_cast<int>(m_input->GetNumberOfDomains());
const int num_cameras = static_cast<int>(m_renders.size());
m_visibility_orders.resize(num_cameras);
for(int i = 0; i < num_cameras; ++i)
{
m_visibility_orders[i].resize(num_domains);
}
//
// In order for parallel volume rendering to composite correctly,
// we nee to establish a visibility ordering to pass to IceT.
// We will transform the data extents into camera space and
// take the minimum z value. Then sort them while keeping
// track of rank, then pass the list in.
//
std::vector<float> min_depths;
min_depths.resize(num_domains);
for(int i = 0; i < num_cameras; ++i)
{
const vtkm::rendering::Camera &camera = m_renders[i].GetCamera();
for(int dom = 0; dom < num_domains; ++dom)
{
vtkm::Bounds bounds = this->m_input->GetDomainBounds(dom);
min_depths[dom] = FindMinDepth(camera, bounds);
}
DepthSort(num_domains, min_depths, m_visibility_orders[i]);
} // for each camera
}
void VolumeRenderer::SetInput(DataSet *input)
{
Filter::SetInput(input);
ClearWrappers();
int num_domains = static_cast<int>(m_input->GetNumberOfDomains());
m_has_unstructured = false;
for(int dom = 0; dom < num_domains; ++dom)
{
vtkm::cont::DataSet data_set;
vtkm::Id domain_id;
m_input->GetDomain(dom, data_set, domain_id);
const vtkm::cont::UnknownCellSet &cellset = data_set.GetCellSet();
if(cellset.GetNumberOfCells() == 0)
{
continue;
}
const vtkm::cont::CoordinateSystem &coords = data_set.GetCoordinateSystem();
using Uniform = vtkm::cont::ArrayHandleUniformPointCoordinates;
using DefaultHandle = vtkm::cont::ArrayHandle<vtkm::FloatDefault>;
using Rectilinear
= vtkm::cont::ArrayHandleCartesianProduct<DefaultHandle,
DefaultHandle,
DefaultHandle>;
bool structured = coords.GetData().IsType<Uniform>() ||
coords.GetData().IsType<Rectilinear>();
if(structured)
{
m_wrappers.push_back(new detail::StructuredWrapper(data_set));
}
else
{
m_has_unstructured = true;
m_wrappers.push_back(new detail::UnstructuredWrapper(data_set));
}
}
}
void VolumeRenderer::ClearWrappers()
{
const int num_wrappers = m_wrappers.size();
for(int i = 0; i < num_wrappers; ++i)
{
delete m_wrappers[i];
}
m_wrappers.clear();
}
std::string
VolumeRenderer::GetName() const
{
return "vtkh::VolumeRenderer";
}
} // namespace vtkh
|
bd2d9a3e482f76637080576507aa4583e397a594 | e1315b89ffe93ca1646b4efd5f339e83e891ee36 | /Physics.h | 8c0356cce55e20e76dc973fe89c59497fca17fe0 | [] | no_license | eriytt/helo | 8eb323dee3292a31475b0ede45862fd10bd25fc9 | 9eb36d1c158b32ebf5fe5d3c58241524ed808ce4 | refs/heads/master | 2021-05-08T15:59:19.347940 | 2015-07-14T18:51:39 | 2015-07-14T18:51:39 | 120,135,718 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,073 | h | Physics.h | #ifndef PHYSICS_H
#define PHYSICS_H
#include <vector>
#include <Ogre.h>
#include <btBulletDynamicsCommon.h>
#include "Thread.h"
class HeloMotionState : public btMotionState
{
protected:
btTransform worldTrans;
btTransform offset;
Ogre::SceneNode *snode;
bool dirty;
public:
HeloMotionState(const btTransform& startTrans = btTransform::getIdentity(),
Ogre::SceneNode *node = 0,
const btTransform& centerOfMassOffset = btTransform::getIdentity())
: worldTrans(startTrans),
offset(centerOfMassOffset),
snode(node),
dirty(false) {}
virtual ~HeloMotionState() {}
void setNode(Ogre::SceneNode *node) {
snode = node;
}
virtual void getWorldTransform(btTransform &trans) const {
trans = worldTrans;
}
virtual void setWorldTransform(const btTransform &trans) {
if(snode == 0)
return;
worldTrans = trans;
dirty = true;
}
virtual void updateSceneNode()
{
if (not (snode && dirty))
return;
btQuaternion rot = worldTrans.getRotation();
btVector3 pos = worldTrans.getOrigin();
snode->setOrientation(rot.w(), rot.x(), rot.y(), rot.z());
snode->setPosition(pos.x(), pos.y(), pos.z());
dirty = false;
}
};
class PhysicsObject
{
public:
virtual void finishPhysicsConfiguration(class Physics *phys) = 0;
virtual void physicsUpdate(float step) = 0;
};
typedef std::vector < PhysicsObject* > PhysObjVector;
typedef std::vector < PhysicsObject* > ::iterator PhysObjIter;
class Physics : public ThreadWorker
{
protected:
typedef std::vector<btRigidBody*> BodyVector;
typedef std::vector<btRigidBody*>::iterator BodyIter;
typedef std::vector<HeloMotionState*> MSVector;
typedef std::vector<HeloMotionState*>::iterator MSIter;
protected:
Thread *physicsThread;
protected:
btDiscreteDynamicsWorld *world;
btDefaultCollisionConfiguration *collisionConfiguration;
btCollisionDispatcher *dispatcher;
//btAxisSweep3 *overlappingPairCache;
btDbvtBroadphase *overlappingPairCache;
btSequentialImpulseConstraintSolver *constraintSolver;
btClock clock;
BodyVector bodies;
MSVector motionStates;
bool runInThread;
PhysObjVector pobjects;
protected:
void internalStep(float timeSlice);
public:
Physics(Ogre::AxisAlignedBox bbox, bool inThread);
virtual ~Physics();
// TODO: add BodyVector version
void addBody(btRigidBody *body);
void addMotionState(HeloMotionState *ms);
void addConstraint(btTypedConstraint* constraint, bool disableCollisionsBetweenLinkedBodies = false);
void addAction(btActionInterface *action);
void addObject(PhysicsObject *obj);
void finishConfiguration();
btRigidBody *testSphere(const Ogre::Vector3 &pos, Ogre::Real size, Ogre::SceneNode *node);
void step();
void sync();
void work();
void stop();
void resume();
btDynamicsWorld *getWorld() {return world;}
static btRigidBody* CreateRigidBody(float mass, const btTransform& startTransform, btCollisionShape* shape,
Ogre::SceneNode *node = 0, btVector3 localInertia = btVector3(0, 0, 0));
};
#endif // PHYSICS_H
|
8fe19702f8fbd471203f40448bd8167d242c205a | a8f8d2d00584e339582725e8e92328938f4a3cb1 | /LatticeStatics/mex/Energies.cpp | 8617e36c5fdfd276d58b32856f043909b7181f1a | [] | no_license | gvsureshreddy/LatticeStaticsPackage | c78586839c7b4bec22e5bfcdc7ed5702137c4af6 | e3cd7b6e013d21ff734a86a38133358bcfc01518 | refs/heads/master | 2021-08-23T07:35:26.950556 | 2017-02-15T04:20:01 | 2017-02-15T04:20:01 | 112,993,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,571 | cpp | Energies.cpp | #include "mex.h"
#include "PerlInput.h"
#include <Matrix.h>
#include <Vector.h>
#include "KnownLattices.h"
#define param0 8
#define param1 8
#define param2 24
#define totparams 40
// RadiiMorse has 8 parameters
// [A0, AT, B0, BT, Rref1, Rtheta1, Rref2, Rtheta2]
// Lat0 -- FCC Ni; Lat1 -- FCC Ti; Lat2 -- B2 NiTi
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
int j;
double* output;
static int flag = 1;
static PerlInput Input;
if (flag)
{
cerr << "setup 1\n";
Input.Readfile("Input1");
}
static MultiLatticeTPP Lat0(Input);
if (flag)
{
Input.ClearHash("Main");
Input.ClearHash("Lattice");
cerr << "setup 2\n";
Input.Readfile("Input2");
}
static MultiLatticeTPP Lat1(Input);
if (flag)
{
Input.ClearHash("Main");
Input.ClearHash("Lattice");
cerr << "setup 3\n";
Input.Readfile("Input3");
}
static MultiLatticeTPP Lat2(Input);
flag = 0;
int m, n;
m = mxGetM(prhs[0]);
n = mxGetN(prhs[0]);
if ((m != 1) && (n != totparams))
{
mexPrintf("Input must be of size 1x%i\n", totparams);
mexErrMsgTxt("Input wrong size. exiting");
}
double* params;
params = mxGetPr(prhs[0]);
Lat0.SetParameters(&(params[0]));
Lat1.SetParameters(&(params[param0]));
Lat2.SetParameters(&(params[param0 + param1]));
// Create the array
plhs[0] = mxCreateDoubleMatrix(1, 3, mxREAL);
output = mxGetPr(plhs[0]);
output[0] = Lat0.E0();
output[1] = Lat1.E0();
output[2] = Lat2.E0();
}
|
9d24c0a4427e0fea22190f37a1e2f35b8431cfcf | 06e3a51780fe6906a8713b7e274a35c0d89d2506 | /qtmdsrv/leveldbbackend.h | 52227a4c78e4ef47659e0415467e54f97888656d | [] | no_license | ssh352/qtctp-1 | d91fc8d432cd93019b23e7e29f40b41b1493aceb | 248d09e629b09cbe1adbf7cd818679721bf156d0 | refs/heads/master | 2020-04-01T16:55:31.012740 | 2015-10-27T15:56:02 | 2015-10-27T15:56:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,296 | h | leveldbbackend.h | #ifndef LEVELDBBACKEND_H
#define LEVELDBBACKEND_H
#include <QObject>
namespace leveldb {
class DB;
}
class LevelDBBackend : public QObject{
Q_OBJECT
public:
explicit LevelDBBackend(QObject* parent = 0);
~LevelDBBackend();
void init();
void shutdown();
leveldb::DB* getTodayDB();
leveldb::DB* getHistoryDB();
static void initInstrumentLocator(leveldb::DB* db);
static void initTickLocator(QString id,leveldb::DB* db,bool raw);
static void initBarM1Locator(QString id,leveldb::DB* db);
static void initBarM5Locator(QString id,leveldb::DB* db);
static void putInstrument(void* instrument,leveldb::DB* db,bool rawTick,bool barM1,bool barM5);
signals:
void mergeBegined();
void mergeUpdated(int progress);
void mergeEnded();
public slots:
void putTick(void* tick, int indexRb, void* rb);
void merge();
private:
QStringList mergeTodayInstruments();
void openHistoryDB();
void closeHistoryDB();
void openTodayDB();
void closeTodayDB();
void mergeById(QString id);
void buildBarM1(void* bar,void* tick);
void putBarM1(const char* id,char* actionday,char* updatetime,void* bar);
private:
leveldb::DB* today_db_ = nullptr;
leveldb::DB* history_db_ = nullptr;
};
#endif // LEVELDBBACKEND_H
|
9961152d62e939bebbb126bbbce5415863f017d6 | f535eaca6e51b35c3bdbed16090be6694f4fcc82 | /聊天室/server/main.cpp | ae00e8540eda23dc4a61c8e98a3f3f706dfadf75 | [] | no_license | mubai-victor/project | 61736495a05424a9c7b4a2c42a3dd234ad766f00 | adb5c0b639a49e1ed1aa56e15a8485119fe111cc | refs/heads/master | 2022-12-10T19:32:04.812484 | 2020-09-12T07:14:42 | 2020-09-12T07:14:42 | 290,642,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,725 | cpp | main.cpp | #include <iostream>
#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include "mysql.h"
#include <list>
#include <unordered_map>
using namespace std;
list<int> clients;
unordered_map<string,int> name2sock;
unordered_map<int,string> sock2name;
MYSQL *mysql=NULL;
pthread_rwlock_t rwlockClient,rwlockTrans;
void*service(void*);
int main()
{
mysql=new MYSQL;
mysql = mysql_init(mysql);
//连接存放名称,密码的数据库
if(!mysql_real_connect(mysql, "localhost", "root", "1314", "clients", 0, NULL, 0))/*针对的是本地数据库且无密码的情况*/
{
cout << "Failed to connect to database. ERROR: "<<mysql_error(mysql) <<endl;
exit(1);
}
cout << "mysql conenct success" << endl;
//初始化两个读写锁
pthread_rwlock_init(&rwlockClient,NULL);
pthread_rwlock_init(&rwlockTrans,NULL);
int serverSock=0,clientSock=0;
if((serverSock=socket(AF_INET,SOCK_STREAM,0))<0){
cout<<"Can not open socket."<<endl;
exit(0);
}
//将服务器端口绑定到8000端口上
sockaddr_in serverAddr,clientAddr;
serverAddr.sin_addr.s_addr=INADDR_ANY;
serverAddr.sin_family=PF_INET;
serverAddr.sin_port=htons(8000);
if(bind(serverSock,(sockaddr*)&serverAddr,sizeof(sockaddr))!=0){
cout<<"Bind error."<<endl;
exit(0);
}
//开始监听
if(listen(serverSock,10)!=0){
cout<<"set Listen error."<<endl;
exit(0);
}
cout<<"Waiting for connection....."<<endl;
//主线程中不断接受新的连接请求,并为每一个连接请求建立一线程
socklen_t len=0;
while(true){
if((clientSock=accept(serverSock,(sockaddr*)(&clientAddr),&len))<0){
cout<<"Accept error."<<endl;
}
else{
pthread_t thread;
pthread_create(&thread,NULL,service,(void*)&clientSock);
}
}
//销毁读写锁
pthread_rwlock_destroy(&rwlockClient);
pthread_rwlock_destroy(&rwlockTrans);
//关闭socket
close(serverSock);
//关闭数据库
mysql_close(mysql);
return 0;
}
/** \brief
*1,如果账号存在,验证密码的合法性
*2.账号不存在,以账号和密码新建一个账号
* \param name:用户名
* \param password:用户密码
* \return bool,验证的结果正确与否
*
*/
bool verify(string&name,string&password){
//进行查询
string cmd="SELECT password FROM clients WHERE name='"+name+"';";
if(mysql_query(mysql,cmd.c_str())!=0){
cout<<"Query databases failed."<<endl;
return false;
}
MYSQL_RES*res;
res=mysql_store_result(mysql);
int row=mysql_num_rows(res);
//如果查询的结果为空,说明数据库中不存在这样的账户,则新建一个账户
if(row==0){
cmd="INSERT INTO clients";
cmd+=" VALUES(NULL,";
cmd+="'"+name+"',";
cmd+="'"+password+"'";
cmd+=");";
//新建账户成功与否
if(mysql_query(mysql,cmd.c_str())!=0){
cout<<"Can not add a new client,name:"<<name<<endl;
return false;
}
else{
cout<<"Add a new client,name:"<<name<<endl;
return true;
}
}
else{
string token;
//获取查询到的那一行
MYSQL_ROW data=mysql_fetch_row(res);
int len=*mysql_fetch_lengths(res);
copy(data[0],data[0]+len,back_inserter(token));
//验证密码
if(token==password){
return true;
}
else{
return false;
}
}
return true;
}
/** \brief 某一用户主动退出或者异常退出之后请清理函数
*
* \param sock:要清理的用户的socket号
* \param
* \return void
*
*/
void disconnect(int sock){
list<int>::iterator target;
//直接删除会出错
for(auto iter=clients.begin();iter!=clients.end();iter++){
if(*iter==sock){
target=iter;
break;
}
}
//要秀给全局变量,要获取写锁
pthread_rwlock_wrlock(&rwlockClient);
pthread_rwlock_wrlock(&rwlockTrans);
//清理当前用户的信息
clients.erase(target);
name2sock.erase(sock2name[sock]);
sock2name.erase(sock);
pthread_rwlock_unlock(&rwlockClient);
pthread_rwlock_unlock(&rwlockTrans);
}
/** \brief 群发消息函数
*
* \param src:消息发送者
* \param msg:要发送的消息(已包含发送者姓名)
* \return void
*
*/
void sendToAll(int src,string&msg){
char buff[BUFSIZ];
copy(msg.begin(),msg.end(),buff);
//要获取读锁
pthread_rwlock_wrlock(&rwlockClient);
for(int des:clients){
//不向发送者群发消息
if(des!=src){
if(send(des,buff,msg.size(),0)<=0){
cout<<"client "<<des<<"failed,abort."<<endl;
}
}
}
pthread_rwlock_unlock(&rwlockClient);
}
/** \brief 单发消息给某个人
*
* \param someone:消息发送对象
* \param msg:要发送的消息(已经包含消息发送者姓名)
* \return void
*
*/
void sendToSomeone(int someone,string&msg){
char buff[BUFSIZ];
copy(msg.begin(),msg.end(),buff);
if(send(someone,buff,msg.size(),0)<=0){
cout<<"Client "<<someone<<"failed."<<endl;
}
}
/** \brief 服务函数,为每一个客户进行服务
*
* \param sock:要服务的对象的套接字
* \param
* \return
*
*/
void*service(void*sock){
const int client=*(int*)sock;
string str,name,password;
char buff[BUFSIZ];
//首先接收客户端发过来的用户名和密码
int len=0;
if((len=recv(client,buff,BUFSIZ,0))<=0){
cout<<"Client "<<client<<" failed."<<endl;
disconnect(client);
}
copy(buff,buff+len,back_inserter(str));
int pos=str.find(":");
name=str.substr(0,pos);
password=str.substr(pos+1);
//验证密码
if(verify(name,password)==true){
//为新来的用户添加记录,先获取写锁,注意预防死锁
pthread_rwlock_wrlock(&rwlockClient);
pthread_rwlock_wrlock(&rwlockTrans);
clients.push_back(client);
name2sock[name]=client;
sock2name[client]=name;
pthread_rwlock_unlock(&rwlockClient);
pthread_rwlock_unlock(&rwlockTrans);
//提示用户密码验证成功
string msg="OK";
sendToSomeone(client,msg);
//群发消息,提醒有新用户上线了
msg=name+" now online.";
cout<<msg<<endl;
sendToAll(client,msg);
}
else{
//验证失败,提醒用户
string msg="Fail";
sendToSomeone(client,msg);
return NULL;
}
//不断接收用户发来的信息,根据不同参数群发,单发消息,或者退出服务
while(true){
string msg;
if((len=recv(client,buff,BUFSIZ,0))<=0){
cout<<"Client "<<client<<" failed."<<endl;
break;
}
copy(buff,buff+len,back_inserter(msg));
if(msg=="quit"){
msg=name+" "+"quit";
cout<<msg<<endl;
sendToAll(client,msg);
break;
}
int pos=msg.find(":");
string des=msg.substr(0,pos);
msg=name+":"+msg.substr(pos+1);
//第一个命令为0发送给指定人员
if(des=="all"){
sendToAll(client,msg);
}
else{
sendToSomeone(name2sock[des],msg);
}
}
disconnect(client);
return NULL;
}
|
e4b78bfe666bd030ebb378bac39668939b6b9b1f | 0e795a2b435ddf87df66dd00bf7020d032f9d8bd | /src/deploy/ssd_model.h | f9a759a740a70c51121190173c8614b7b508610f | [] | no_license | pppppM/mmdetection-tvm | a1a038d671ca78c0bb82da4dd3781d987db011f4 | bdb3090dc59b052da32687d6853d3dd2fe2d6d05 | refs/heads/master | 2022-12-02T04:14:28.341519 | 2020-08-22T23:17:32 | 2020-08-22T23:17:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,306 | h | ssd_model.h | #include <stdio.h>
#include <opencv2/opencv.hpp>
#include <tvm/runtime/module.h>
#include <tvm/runtime/registry.h>
#include <tvm/runtime/packed_func.h>
#include <cstdio>
constexpr char kLibSoFileName[] = "ssd_lib.so";
constexpr char kGraphFileName[] = "ssd_graph.json";
constexpr char kParamsFileName[] = "ssd_param.params";
constexpr int kSsdWidth = 300;
constexpr int kSsdHeight = 300;
// TVM array constants
constexpr int kDTypeCode = kDLFloat;
constexpr int kDTypeBits = 32;
constexpr int kDTypeLanes = 1;
constexpr int kDeviceType = kDLCPU;
constexpr int kDeviceId = 0;
constexpr int kInDim = 4;
class SsdModel
{
public:
SsdModel(const std::string& weight_folder)
{
tvm::runtime::Module mod_syslib = tvm::runtime::Module::LoadFromFile(weight_folder + kLibSoFileName);
// load graph
std::ifstream json_in(weight_folder + kGraphFileName);
std::string graph_json((std::istreambuf_iterator<char>(json_in)), std::istreambuf_iterator<char>());
json_in.close();
// Define device
int device_type = kDLCPU;
int device_id = 0;
// get global function module for graph runtime
tvm::runtime::Module mod = (*tvm::runtime::Registry::Get("tvm.graph_runtime.create"))(graph_json, mod_syslib, device_type, device_id);
module_ = std::unique_ptr<tvm::runtime::Module>(new tvm::runtime::Module(mod));
//load param
std::ifstream params_in(weight_folder + kParamsFileName, std::ios::binary);
std::string params_data((std::istreambuf_iterator<char>(params_in)), std::istreambuf_iterator<char>());
params_in.close();
TVMByteArray params_arr;
params_arr.data = params_data.c_str();
params_arr.size = params_data.length();
tvm::runtime::PackedFunc load_params = module_->GetFunction("load_params");
load_params(params_arr);
}
cv::Mat Forward(cv::Mat input_image)
{
// TODO: update the code in forward function to generate bounding box.
cv::Mat tensor = cv::dnn::blobFromImage(input_image, 1.0, cv::Size(kSsdWidth, kSsdHeight), cv::Scalar(0, 0, 0), true);
//convert uint8 to float32 and convert to RGB via opencv dnn function
TVMArrayHandle input;
constexpr int dtype_code = kDLFloat;
constexpr int dtype_bits = 32;
constexpr int dtype_lanes = 1;
constexpr int device_type = kDLCPU;
constexpr int device_id = 0;
const int64_t input_shape[kInDim] = {1, 3, kSsdWidth, kSsdHeight};
TVMArrayAlloc(input_shape, kInDim, kDTypeCode, kDTypeBits, kDTypeLanes, kDeviceType, kDeviceId, &input);
TVMArrayCopyFromBytes(input, tensor.data, kSsdWidth * 3 * kSsdHeight * 4);
// set input
module_->GetFunction("set_input")("input0", input);
// execute graph
module_->GetFunction("run")();
// get output
tvm::runtime::PackedFunc get_output = module_->GetFunction("get_output");
const tvm::runtime::NDArray res = get_output(0);
cv::Mat vector(8732, 6, CV_32F);
memcpy(vector.data, res->data, 8732 * 6 * 4);
// vector = vector.reshape(6, 8732);
TVMArrayFree(input);
return vector;
}
private:
std::unique_ptr<tvm::runtime::Module> module_;
}; |
a7e549c238853fc4c7451871d636dbadb3a224d5 | a06f362b431d0255411e30cb95dbe14750d64dad | /Calculator.cpp | d2f5f98b0e4f0cb40e8de71aa96d9d434e4367cc | [] | no_license | MrZloHex/roman_calculator | 30c2edc5d911ed1ccfbed64ecc599594d6798d3e | 75d2e32d9a951ba1199575036b20dd60274ca259 | refs/heads/main | 2023-06-15T18:03:35.515103 | 2021-06-29T18:23:03 | 2021-06-29T18:23:03 | 382,953,358 | 1 | 0 | null | 2021-07-04T21:41:02 | 2021-07-04T21:41:02 | null | UTF-8 | C++ | false | false | 4,853 | cpp | Calculator.cpp | #include "Calculator.h"
#include <iostream>
int Calculator::OperatorPriority(const std::string &ch) {
if (ch == "+" || ch == "-") {
return 1; //Precedence of + or - is 1
} else if (ch == "*" || ch == "/") {
return 2; //Precedence of * or / is 2
} else if (ch == "^") {
return 3; //Precedence of ^ is 3
} else {
return 0;
}
}
bool Calculator::IsNumber(const std::string &s) {
return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit);
}
Result<std::vector<Token>> Calculator::InfixToPostfix(const std::vector<Token> &infix) {
Result<std::vector<Token>> result;
std::vector<Token> postfix;
std::stack<Token> stack;
for (const auto &it: infix) {
if (it.token_type == TokenType::CONSTANT) {
postfix.emplace_back(it);
continue;
}
if (it.token == "(") {
stack.push(it);
continue;
}
if (it.token == ")") {
while (!stack.empty() && stack.top().token != "(") {
postfix.emplace_back(stack.top());
stack.pop();
}
if (stack.empty()) {
result.SetError("wrong input data/calculation error");
return result;
}
stack.pop();
continue;
}
if (it.token_type == TokenType::OPERATOR) {
if (stack.empty() ||
OperatorPriority(it.token) > OperatorPriority(stack.top().token)) {
stack.push(it);
} else {
while (!stack.empty() &&
OperatorPriority(it.token) <= OperatorPriority(stack.top().token)) {
postfix.emplace_back(stack.top());
stack.pop();
}
stack.push(it);
};
}
}
while (!stack.empty()) {
Token top = stack.top();
if (top.token != "(") {
postfix.emplace_back(top);
}
stack.pop();
}
result.SetValue(std::move(postfix));
return result;
}
std::vector<Token> Calculator::PrepareInfixString(const std::string &input) {
std::string result;
std::string input1;
for (const auto &it: input) {
if (' ' == it) {
continue;
}
input1.push_back(it);
}
std::string input2;
auto it = input1.begin();
while (it != input1.end()) {
size_t i = it - input1.begin();
if (0 == i && '-' == *it) {
input2 += "0-";
++it;
continue;
}
if (i >= 1 && '-' == *it && '(' == *(it - 1)) {
input2 += "0-";
++it;
continue;
}
input2 += *it;
++it;
}
std::vector<Token> tokens;
std::stack<Token> stack;
std::string buff;
for (auto it1: input2) {
if (IsNumber(std::string{it1}) || isalpha(it1)) {
buff += it1;
}
if ('+' == it1 ||
'*' == it1 ||
'-' == it1 ||
'/' == it1 ||
')' == it1 ||
'(' == it1
) {
if (!buff.empty()) {
tokens.emplace_back(Token{TokenType::CONSTANT, buff});
buff = "";
}
}
if ('+' == it1 ||
'*' == it1 ||
'/' == it1 ||
'-' == it1) {
tokens.emplace_back(Token{TokenType::OPERATOR,
std::string{it1}});
}
if ('(' == it1 || ')' == it1) {
tokens.emplace_back(Token{TokenType::PARENTHESES,
std::string{it1}});
}
}
if (!buff.empty()) {
tokens.emplace_back(Token{TokenType::CONSTANT, buff});
buff = "";
}
return tokens;
}
Result<int64_t> Calculator::CalculateResult(const std::string &input) {
Result<int64_t> result;
auto prep = PrepareInfixString(input);
auto inf2post_result = InfixToPostfix(prep);
if (inf2post_result.HasError()) {
result.SetError(inf2post_result.ErrorDesc());
return result;
}
auto inf2post = inf2post_result.GetValue();
std::stack<int64_t> stack;
for (const auto &it: inf2post) {
if (it.token_type == TokenType::CONSTANT) {
stack.push(std::stoll(it.token));
}
if (it.token_type == TokenType::OPERATOR) {
int64_t op1;
int64_t op2;
for (size_t i = 0; i < 2; ++i) {
if (!stack.empty()) {
if (i == 0) {
op2 = stack.top();
}
if (i == 1) {
op1 = stack.top();
}
stack.pop();
} else {
result.SetError("wrong input data/calculation error");
return result;
}
}
int64_t res;
if (it.token == "+") {
res = op1 + op2;
} else if (it.token == "-") {
res = op1 - op2;
} else if (it.token == "*") {
res = op1 * op2;
} else if (it.token == "/") {
if (op2 == 0) {
result.SetError("zero division");
return result;
}
res = op1 / op2;
}
stack.push(res);
}
}
// assert stack.size == 1
if (stack.size() != 1) {
result.SetError("wrong input data/calculation error");
return result;
}
result.SetValue(stack.top());
return result;
}
|
490e510b9747ad9b615c9c597c93a4aa90dbe8eb | b11f71cdacb190426e1be64414855d1b3062fde2 | /App/rational.h | 9ecec29dfd05bda09a613752e7d369f52e883393 | [] | no_license | AngelOfSol/dress_app | be661fb0807f782dd5723784c9033ee5680f5628 | fc5b81e0b523be8ce0fa47c825df97703244a0ba | refs/heads/master | 2016-09-06T08:13:43.151199 | 2015-02-02T01:16:56 | 2015-02-02T01:16:56 | 28,242,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,437 | h | rational.h | #pragma once
#include "math.h"
#include <string>
#include <boost\regex.hpp>
#define DEBUG
template <class IntType>
class Rational
{
public:
Rational(IntType numerator, IntType denominator):numerator_(numerator), denominator_(denominator)
{
this->rationalize();
#ifdef DEBUG
this->value = (long double)this->numerator_ / (long double) this->denominator_;
#endif
};
template <class OldType>
Rational(Rational<OldType> value):numerator_((IntType)value.numerator()), denominator_((IntType)value.denominator())
{
#ifdef DEBUG
this->value = (long double)this->numerator_ / (long double) this->denominator_;
#endif
}
Rational():numerator_(0), denominator_(1)
{
#ifdef DEBUG
this->value = (long double)this->numerator_ / (long double) this->denominator_;
#endif
}
template<class FloatType>
Rational(FloatType number):numerator_(0), denominator_(1)
{
this->assign<FloatType>(number);
this->rationalize();
#ifdef DEBUG
this->value = (long double)this->numerator_ / (long double) this->denominator_;
#endif
};
Rational& operator =(const IntType& rhs)
{
this->numerator_ = rhs;
this->denominator_ = 1;
#ifdef DEBUG
this->value = (long double)this->numerator_ / (long double) this->denominator_;
#endif
return *this;
};
template<class FloatType>
Rational& operator =(const FloatType& rhs)
{
this->assign(rhs);
#ifdef DEBUG
this->value = (long double)this->numerator_ / (long double) this->denominator_;
#endif
return *this;
};
Rational operator -() const
{
return Rational(-this->numerator_, this->denominator_);
};
Rational operator +(const Rational& rhs) const
{
return Rational(this->numerator_ * rhs.denominator_ + this->denominator_ * rhs.numerator_, this->denominator_ * rhs.denominator_);
};
Rational operator -(const Rational& rhs) const
{
return (*this) + (-rhs);
}
Rational operator *(const Rational& rhs) const
{
return Rational(this->numerator_ * rhs.numerator_, this->denominator_ * rhs.denominator_);
}
Rational operator /(const Rational& rhs) const
{
return Rational(this->numerator_ * rhs.denominator_, this->denominator_ * rhs.numerator_);
}
Rational& operator +=(const Rational& rhs)
{
*this = *this + rhs;
return *this;
}
Rational& operator -=(const Rational& rhs)
{
*this = *this - rhs;
return *this;
}
Rational& operator *=(const Rational& rhs)
{
*this = *this * rhs;
return *this;
}
Rational& operator /=(const Rational& rhs)
{
*this = *this / rhs;
return *this;
}
bool operator ==(const Rational& rhs) const
{
return this->numerator_ == rhs.numerator_ && this->denominator_ == rhs.denominator_;
}
bool operator !=(const Rational& rhs) const
{
return *this == rhs;
}
bool operator <(const Rational& rhs) const
{
return (this->numerator_ * rhs.denominator_) < (this->denominator_ * rhs.numerator_);
}
bool operator <=(const Rational& rhs) const
{
return *this < rhs || *this == rhs;
}
bool operator >(const Rational& rhs) const
{
return !(*this <= rhs);
}
bool operator >=(const Rational& rhs) const
{
return !(*this < rhs);
}
template <class FloatType>
bool operator <(const FloatType& rhs) const
{
return this->numerator_ < rhs * this->denominator_;
}
template <class FloatType>
bool operator <=(const FloatType& rhs) const
{
return this->numerator_ <= rhs * this->denominator_;
}
template <class FloatType>
bool operator >(const FloatType& rhs) const
{
return this->numerator_ > rhs * this->denominator_;
}
template <class FloatType>
bool operator >=(const FloatType& rhs) const
{
return this->numerator_ >= rhs * this->denominator_;
}
template <class FloatType>
bool operator ==(const FloatType& rhs) const
{
return this->numerator_ == rhs * this->denominator_;
}
template <class FloatType>
bool operator !=(const FloatType& rhs) const
{
return this->numerator_ != rhs * this->denominator_;
}
IntType as() const
{
return this->numerator_ / this->denominator_;
}
template <class FloatType>
operator const FloatType() const
{
return (FloatType)this->numerator_ / (FloatType)this->denominator_;
}
Rational rabs() const
{
return Rational(sign(this->numerator_) * this->numerator_, this->denominator_);
}
Rational rsqrt() const
{
Rational ret;
ret.assign<double>(std::sqrt((double)*this));
return ret;
}
Rational rsign() const
{
return Rational(sign(this->numerator_), 1);
}
const IntType& denominator() const { return this->denominator_; };
const IntType& numerator() const { return this->numerator_; };
static boost::regex numberParse;
private:
template <typename FloatType>
void assign(const FloatType& rhs)
{
int denominator = 1;
FloatType numerator = rhs;
int counter = 0;
this->numerator_ = (IntType)std::floor(numerator * pow(6, 10));
this->denominator_ = (IntType)pow(6, 10);
this->rationalize();
}
void rationalize()
{
this->numerator_ *= sign(this->denominator_);
this->denominator_ *= sign(this->denominator_);
IntType divisor = gcd(this->numerator_ * sign(this->numerator_), this->denominator_);
divisor = divisor ? divisor : 1;
this->numerator_ /= divisor;
this->denominator_ /= divisor;
IntType maxDenom = 1000000;
if (this->denominator_ > maxDenom)
{
this->numerator_ = this->numerator_ * maxDenom / this->denominator_;
this->denominator_ = maxDenom;
}
};
IntType numerator_;
IntType denominator_;
#ifdef DEBUG
long double value;
#endif
};
template <class IntType>
Rational<IntType> sqrt(const Rational<IntType>& rhs)
{
return rhs.rsqrt();
}
template <class IntType>
Rational<IntType> abs(const Rational<IntType>& rhs)
{
return rhs.rabs();
}
template <class IntType>
Rational<IntType> sign(const Rational<IntType>& rhs)
{
return rhs.rsign();
}
template <class IntType>
Rational<IntType> stor(std::string input)
{
IntType numerator = 0;
IntType denominator = 1;
boost::smatch results;
boost::regex numberParse("(\\+|\\-)?(\\.)?([\\d]+)((\\.)([\\d]*))?");
if (boost::regex_match(input, results, numberParse))
{
if (results[2].str() == ".")
{
IntType powerOfTen = (IntType)pow(10, results[3].str().size());
numerator = std::stoi(results[3].str());
denominator = powerOfTen;
}
else
{
numerator = std::stoi(results[3].str());
if (results[6].str().size() > 0)
{
IntType powerOfTen = (IntType)pow(10, results[6].str().size());
numerator *= powerOfTen;
numerator += std::stoi(results[6]);
denominator = powerOfTen;
}
}
if (results[1].str() == "-")
numerator *= -1;
return Rational<IntType>(numerator, denominator);
}
throw std::invalid_argument("invalid string passed");
}
template <class IntType>
Rational<IntType> stor(const char* input)
{
return stor<IntType>(std::string(input));
}
/*
template <class IntType>
Rational<IntType> operator +(IntType lhs, const Rational<IntType>& rhs)
{
return Rational<IntType>(lhs) + rhs;
};
template <class IntType>
Rational<IntType> operator -(IntType lhs, const Rational<IntType>& rhs)
{
return Rational<IntType>(lhs) - rhs;
}
template <class IntType>
Rational<IntType> operator *(IntType lhs, const Rational<IntType>& rhs)
{
return Rational<IntType>(lhs) * rhs;
}
template <class IntType>
Rational<IntType> operator /(IntType lhs, const Rational<IntType>& rhs)
{
return Rational<IntType>(lhs) * rhs;
}*/
/*
Rational(IntType numerator = 0, IntType denominator = 1):numerator_(numerator), denominator_(denominator)
{
};
*/ |
2867a630c2e6048e2745d4ff7c9fe0ffd439316e | d23e594e88dcf907ed9ce1dc28d4c89803ca98e3 | /src/iFuseOper.cpp | 5b80f4043b89d151f6d63880ddbf006dbb02a0eb | [] | no_license | cyverse/irods_client_fuse | f3465bade36a079d9b39ffb2c3cf08833d0dd5be | 834c42bfb01b5561c36cb013b2c0acf49c091888 | refs/heads/master | 2021-01-11T20:51:34.577972 | 2020-11-24T19:19:57 | 2020-11-24T19:19:57 | 79,190,231 | 0 | 1 | null | 2017-01-17T05:01:12 | 2017-01-17T05:01:12 | null | UTF-8 | C++ | false | false | 24,409 | cpp | iFuseOper.cpp | /*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/*
Copyright 2020 The Trustees of University of Arizona and CyVerse
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 <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <assert.h>
#include "iFuseOper.hpp"
#include "iFuse.Preload.hpp"
#include "iFuse.BufferedFS.hpp"
#include "iFuse.FS.hpp"
#include "iFuse.Lib.hpp"
#include "iFuse.Lib.Fd.hpp"
#include "iFuse.Lib.Conn.hpp"
#include "iFuse.Lib.Util.hpp"
#include "iFuse.Lib.RodsClientAPI.hpp"
#include "sockComm.h"
void *iFuseInit(struct fuse_conn_info *conn) {
if (conn->capable & FUSE_CAP_BIG_WRITES) {
conn->want |= FUSE_CAP_BIG_WRITES;
}
#ifdef FUSE_CAP_IOCTL_DIR
if (conn->capable & FUSE_CAP_IOCTL_DIR) {
conn->want |= FUSE_CAP_IOCTL_DIR;
}
#endif
iFuseLibInitTimerThread();
int status = 0;
char iRodsPath[MAX_NAME_LEN];
bzero(iRodsPath, MAX_NAME_LEN);
iFuseLibLog(LOG_DEBUG, "iFuseInit: pre-fetch mount root directory.");
status = iFuseRodsClientMakeRodsPath("/", iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseInit: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
// quick return
return NULL;
}
iFuseFsCacheDir(iRodsPath);
return NULL;
}
void iFuseDestroy(void *data) {
UNUSED(data);
iFuseLibTerminateTimerThread();
}
int iFuseGetAttr(const char *path, struct stat *stbuf) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseGetAttr: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
if(iFuseLibGetOption()->bufferedFS) {
status = iFuseBufferedFsGetAttr(iRodsPath, stbuf);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseGetAttr: iFuseBufferedFsGetAttr of %s error", iRodsPath);
}
} else {
status = iFuseFsGetAttr(iRodsPath, stbuf);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseGetAttr: iFuseFsGetAttr of %s error", iRodsPath);
}
}
return status;
}
int iFuseOpen(const char *path, struct fuse_file_info *fi) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseFd_t *iFuseFd = NULL;
int flag = fi->flags;
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseOpen: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
/* use ENOTDIR for this type of error */
return -ENOTDIR;
}
if(iFuseLibGetOption()->bufferedFS) {
if(iFuseLibGetOption()->preload) {
status = iFusePreloadOpen(iRodsPath, &iFuseFd, flag);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseOpen: cannot open file descriptor for %s error", iRodsPath);
return -ENOENT;
}
} else {
status = iFuseBufferedFsOpen(iRodsPath, &iFuseFd, flag);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseOpen: cannot open file descriptor for %s error", iRodsPath);
return -ENOENT;
}
}
} else {
status = iFuseFsOpen(iRodsPath, &iFuseFd, flag);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseOpen: cannot open file descriptor for %s error", iRodsPath);
return -ENOENT;
}
}
fi->fh = (uint64_t)iFuseFd;
return 0;
}
int iFuseClose(const char *path, struct fuse_file_info *fi) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseFd_t *iFuseFd = NULL;
assert(fi->fh != 0);
iFuseFd = (iFuseFd_t *)fi->fh;
assert(iFuseFd->fd > 0);
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseClose: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
/* use ENOTDIR for this type of error */
return -ENOTDIR;
}
if(iFuseLibGetOption()->bufferedFS) {
if(iFuseLibGetOption()->preload) {
status = iFusePreloadClose(iFuseFd);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseClose: cannot close file descriptor for %s error", iRodsPath);
return -ENOENT;
}
} else {
status = iFuseBufferedFsClose(iFuseFd);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseClose: cannot close file descriptor for %s error", iRodsPath);
return -ENOENT;
}
}
} else {
status = iFuseFsClose(iFuseFd);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseClose: cannot close file descriptor for %s error", iRodsPath);
return -ENOENT;
}
}
return 0;
}
int iFuseFlush(const char *path, struct fuse_file_info *fi) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseFd_t *iFuseFd = NULL;
assert(fi->fh != 0);
iFuseFd = (iFuseFd_t *)fi->fh;
assert(iFuseFd->fd > 0);
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseFlush: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
/* use ENOTDIR for this type of error */
return -ENOTDIR;
}
if(iFuseLibGetOption()->bufferedFS) {
status = iFuseBufferedFsFlush(iFuseFd);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseFlush: cannot flush file content for %s error", iRodsPath);
return -ENOENT;
}
} else {
status = iFuseFsFlush(iFuseFd);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseFlush: cannot flush file content for %s error", iRodsPath);
return -ENOENT;
}
}
return status;
}
int iFuseFsync(const char *path, int isdatasync, struct fuse_file_info *fi) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseFd_t *iFuseFd = NULL;
UNUSED(isdatasync);
assert(fi->fh != 0);
iFuseFd = (iFuseFd_t *)fi->fh;
assert(iFuseFd->fd > 0);
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseFsync: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
/* use ENOTDIR for this type of error */
return -ENOTDIR;
}
if(iFuseLibGetOption()->bufferedFS) {
status = iFuseBufferedFsFlush(iFuseFd);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseFsync: cannot flush file content for %s error", iRodsPath);
return -ENOENT;
}
} else {
status = iFuseFsFlush(iFuseFd);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseFsync: cannot flush file content for %s error", iRodsPath);
return -ENOENT;
}
}
return status;
}
int iFuseRead(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseFd_t *iFuseFd = NULL;
assert(buf != NULL);
assert(size > 0);
assert(offset >= 0);
assert(fi->fh != 0);
iFuseFd = (iFuseFd_t *)fi->fh;
assert(iFuseFd->fd > 0);
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseRead: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
/* use ENOTDIR for this type of error */
return -ENOTDIR;
}
if(iFuseLibGetOption()->bufferedFS) {
if(iFuseLibGetOption()->preload) {
status = iFusePreloadRead(iFuseFd, buf, offset, size);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseRead: cannot read file content for %s error", iRodsPath);
return -ENOENT;
}
} else {
status = iFuseBufferedFsRead(iFuseFd, buf, offset, size);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseRead: cannot read file content for %s error", iRodsPath);
return -ENOENT;
}
}
} else {
status = iFuseFsRead(iFuseFd, buf, offset, size);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseRead: cannot read file content for %s error", iRodsPath);
return -ENOENT;
}
}
return status;
}
int iFuseWrite(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseFd_t *iFuseFd = NULL;
iFuseFd = (iFuseFd_t *)fi->fh;
assert(iFuseFd->fd > 0);
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseWrite: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
/* use ENOTDIR for this type of error */
return -ENOTDIR;
}
if(iFuseLibGetOption()->bufferedFS) {
status = iFuseBufferedFsWrite(iFuseFd, buf, offset, size);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseWrite: cannot write file content for %s error", iRodsPath);
return -ENOENT;
}
} else {
status = iFuseFsWrite(iFuseFd, buf, offset, size);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseWrite: cannot write file content for %s error", iRodsPath);
return -ENOENT;
}
}
return status;
}
int iFuseCreate(const char *path, mode_t mode, dev_t) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseCreate: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
status = iFuseFsCreate(iRodsPath, mode);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseCreate: cannot create a file for %s error", iRodsPath);
return -ENOENT;
}
return 0;
}
int iFuseUnlink(const char *path) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseUnlink: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
status = iFuseFsUnlink(iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseUnlink: cannot delete a file for %s error", iRodsPath);
return status;
}
return 0;
}
int iFuseLink(const char *from, const char *to) {
UNUSED(from);
UNUSED(to);
return 0;
}
int iFuseStatfs(const char *path, struct statvfs *stbuf) {
int status = 0;
UNUSED(path);
if (stbuf == NULL) {
return 0;
}
status = statvfs( "/", stbuf );
if ( status < 0 ) {
// error cond?
}
stbuf->f_bsize = FILE_BLOCK_SIZE;
stbuf->f_blocks = 2000000000;
stbuf->f_bfree = stbuf->f_bavail = 1000000000;
stbuf->f_files = 200000000;
stbuf->f_ffree = stbuf->f_favail = 100000000;
stbuf->f_fsid = 777;
stbuf->f_namemax = MAX_NAME_LEN;
return 0;
}
int iFuseOpenDir(const char *path, struct fuse_file_info *fi) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseDir_t *iFuseDir = NULL;
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseOpenDir: iFuseRodsClientMakeRodsPath of %s error", path);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
status = iFuseFsOpenDir(iRodsPath, &iFuseDir);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseOpenDir: cannot open a directory for %s error", iRodsPath);
return status;
}
fi->fh = (uint64_t)iFuseDir;
return 0;
}
int iFuseCloseDir(const char *path, struct fuse_file_info *fi) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseDir_t *iFuseDir = NULL;
assert(fi->fh != 0);
iFuseDir = (iFuseDir_t *)fi->fh;
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseCloseDir: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
/* use ENOTDIR for this type of error */
return -ENOTDIR;
}
status = iFuseFsCloseDir(iFuseDir);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseCloseDir: cannot close a directory for %s error", iRodsPath);
return -ENOENT;
}
return 0;
}
int iFuseReadDir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseDir_t *iFuseDir = NULL;
assert(buf != NULL);
assert(fi->fh != 0);
iFuseDir = (iFuseDir_t *)fi->fh;
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseReadDir: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
/* use ENOTDIR for this type of error */
return -ENOTDIR;
}
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
status = iFuseFsReadDir(iFuseDir, filler, buf, offset);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseReadDir: cannot read directory for %s error", iRodsPath);
return status;
}
return 0;
}
int iFuseMakeDir(const char *path, mode_t mode) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
struct stat stbuf;
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseMakeDir: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
bzero(&stbuf, sizeof(struct stat));
status = iFuseFsGetAttr(iRodsPath, &stbuf);
if (status >= 0) {
return -EEXIST;
}
status = iFuseFsMakeDir(iRodsPath, mode);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseMakeDir: cannot create a directory for %s error", iRodsPath);
return -ENOENT;
}
return 0;
}
int iFuseRemoveDir(const char *path) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseRemoveDir: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
status = iFuseFsRemoveDir(iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseRemoveDir: cannot delete a directory for %s error", iRodsPath);
return status;
}
return 0;
}
int iFuseRename(const char *from, const char *to) {
int status = 0;
char iRodsFromPath[MAX_NAME_LEN];
char iRodsToPath[MAX_NAME_LEN];
struct stat stbuf;
bzero(iRodsFromPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(from, iRodsFromPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseRename: iFuseRodsClientMakeRodsPath of %s error", iRodsFromPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
bzero(iRodsToPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(to, iRodsToPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseRename: iFuseRodsClientMakeRodsPath of %s error", iRodsToPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
bzero(&stbuf, sizeof(struct stat));
status = iFuseFsGetAttr(iRodsToPath, &stbuf);
if (status >= 0) {
status = iFuseFsUnlink(iRodsToPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseUnlink: cannot delete a file for %s error", iRodsToPath);
return status;
}
}
status = iFuseFsRename(iRodsFromPath, iRodsToPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseFsRename: cannot rename a file or a directory for %s to %s error", iRodsFromPath, iRodsToPath);
return status;
}
return 0;
}
int iFuseTruncate(const char *path, off_t size) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseTruncate: iFuseRodsClientMakeRodsPath of %s error", path);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
status = iFuseFsTruncate(iRodsPath, size);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseTruncate: cannot truncate a file for %s error", iRodsPath);
return status;
}
return 0;
}
int iFuseSymlink(const char *to, const char *from) {
int status = 0;
char iRodsFromPath[MAX_NAME_LEN];
char iRodsToPath[MAX_NAME_LEN];
struct stat stbuf;
iFuseFd_t *iFuseFd = NULL;
bzero(iRodsFromPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(from, iRodsFromPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseSymlink: iFuseRodsClientMakeRodsPath of %s error", iRodsFromPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
bzero(iRodsToPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(to, iRodsToPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseSymlink: iFuseRodsClientMakeRodsPath of %s error", iRodsToPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
bzero(&stbuf, sizeof(struct stat));
status = iFuseFsGetAttr(iRodsFromPath, &stbuf);
if (status >= 0) {
status = iFuseFsTruncate(iRodsFromPath, 0);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseSymlink: cannot truncate a file for %s error", iRodsFromPath);
return status;
}
} else if(status == -ENOENT) {
status = iFuseFsCreate(iRodsFromPath, S_IFLNK);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseSymlink: cannot create a file for %s error", iRodsFromPath);
return -ENOENT;
}
}
status = iFuseFsOpen(iRodsFromPath, &iFuseFd, O_WRONLY);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseSymlink: cannot open file descriptor for %s error", iRodsFromPath);
return -ENOENT;
}
status = iFuseFsWrite(iFuseFd, iRodsToPath, 0, strlen(iRodsToPath));
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseSymlink: cannot write file content for %s error", iRodsToPath);
iFuseFsClose(iFuseFd);
return -ENOENT;
}
status = iFuseFsClose(iFuseFd);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseSymlink: cannot close file descriptor for %s error", iRodsFromPath);
return -ENOENT;
}
return 0;
}
int iFuseReadLink(const char *path, char *buf, size_t size) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
iFuseFd_t *iFuseFd = NULL;
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseReadLink: iFuseRodsClientMakeRodsPath of %s error", iRodsPath);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
status = iFuseFsOpen(iRodsPath, &iFuseFd, O_RDONLY);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseReadLink: cannot open file descriptor for %s error", iRodsPath);
return -ENOENT;
}
status = iFuseFsRead(iFuseFd, buf, 0, size - 1);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseReadLink: cannot read file content for %s error", iRodsPath);
iFuseFsClose(iFuseFd);
return -ENOENT;
}
buf[status] = 0;
status = iFuseFsClose(iFuseFd);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseReadLink: cannot close file descriptor for %s error", iRodsPath);
return -ENOENT;
}
return 0;
}
int iFuseChmod(const char *path, mode_t mode) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseChmod: iFuseRodsClientMakeRodsPath of %s error", path);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
status = iFuseFsChmod(iRodsPath, mode);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseChmod: cannot change mode of a file for %s error", iRodsPath);
return status;
}
return 0;
}
int iFuseChown(const char *path, uid_t uid, gid_t gid) {
UNUSED(path);
UNUSED(uid);
UNUSED(gid);
return 0;
}
int iFuseUtimens(const char *path, const struct timespec ts[2]) {
UNUSED(path);
UNUSED(ts);
return 0;
}
int iFuseIoctl(const char *path, int cmd, void *arg, struct fuse_file_info *fi, unsigned int flags, void *data) {
int status = 0;
char iRodsPath[MAX_NAME_LEN];
bzero(iRodsPath, MAX_NAME_LEN);
status = iFuseRodsClientMakeRodsPath(path, iRodsPath);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseIoctl: iFuseRodsClientMakeRodsPath of %s error", path);
// use ENOTDIR for this type of error
return -ENOTDIR;
}
status = iFuseFsIoctl(iRodsPath, cmd, arg, fi, flags, data);
if (status < 0) {
iFuseLibLogError(LOG_ERROR, status,
"iFuseIoctl: cannot peform ioctl of a file for %s error", iRodsPath);
return status;
}
return 0;
}
|
643860465a670284970b3ebd5c07c96ef5d5dbac | ba649a3c5666bbc3f7d95c1c029ac4e9cacd9655 | /ImageMagic/ImageHandler.cpp | 1964c2782275e9a8d30cf20cc882a329a3b58923 | [] | no_license | Neo-T/MachineVisionLib | 45de172947ea9a216121aa3a08b00e6625c5a15a | ab0e7692dfb9541e903a590f895f623faff7a7c2 | refs/heads/master | 2021-06-03T18:23:38.462418 | 2020-11-05T08:14:20 | 2020-11-05T08:14:20 | 131,290,811 | 12 | 9 | null | null | null | null | GB18030 | C++ | false | false | 6,295 | cpp | ImageHandler.cpp | #include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <io.h>
#include <vector>
#include "common_lib.h"
#include "MachineVisionLib.h"
#include "MathAlgorithmLib.h"
#include "ImagePreprocess.h"
#include "ImageHandler.h"
static void EHImgPerspecTrans_OnMouse(INT nEvent, INT x, INT y, INT nFlags, void *pvIPT);
//* 图像透视变换
void ImagePerspectiveTransformation::process(Mat& mSrcImg, Mat& mResultImg, Mat& mSrcShowImg, DOUBLE dblScaleFactor)
{
CHAR *pszSrcImgWinName = "源图片";
CHAR *pszDestImgWinName = "目标图片";
o_dblScaleFactor = dblScaleFactor;
//* 命名操作窗口
namedWindow(pszDestImgWinName, WINDOW_AUTOSIZE);
namedWindow(pszSrcImgWinName, WINDOW_AUTOSIZE);
//* 隐藏目标窗口
cv2shell::ShowImageWindow(pszDestImgWinName, FALSE);
//* 显示原始图片
imshow(pszSrcImgWinName, mSrcShowImg);
//* 处理鼠标事件的回调函数
setMouseCallback(pszSrcImgWinName, EHImgPerspecTrans_OnMouse, this);
BOOL blIsNotEndOpt = TRUE;
BOOL blIsPut = FALSE;
while (blIsNotEndOpt && cvGetWindowHandle(pszSrcImgWinName) && cvGetWindowHandle(pszDestImgWinName))
{
//* 等待按键
CHAR bInputKey = waitKey(10);
switch ((CHAR)toupper(bInputKey))
{
case 'R':
o_vptROI.push_back(o_vptROI[0]);
o_vptROI.erase(o_vptROI.begin());
//* 重绘
o_blIsNeedPaint = TRUE;
break;
case 'I':
swap(o_vptROI[0], o_vptROI[1]);
swap(o_vptROI[2], o_vptROI[3]);
//* 重绘
o_blIsNeedPaint = TRUE;
break;
case 'D':
case 46:
o_vptROI.clear();
//* 恢复原始图像
mSrcImg.copyTo(mResultImg);
//* 隐藏目标窗口
cv2shell::ShowImageWindow(pszDestImgWinName, FALSE);
//* 重绘
o_blIsNeedPaint = TRUE;
break;
case 'Q':
case 27: //* Esc键
blIsNotEndOpt = FALSE;
break;
default:
break;
}
//* 是否需要绘制角点区域
if (o_blIsNeedPaint)
{
o_blIsNeedPaint = FALSE;
//* 重新获取原始数据
Mat mShowImg = mSrcShowImg.clone();
//* 绘制角点
for (INT i = 0; i < o_vptROI.size(); i++)
{
Point2f point = o_vptROI[i] * o_dblScaleFactor;
circle(mShowImg, point, 4, Scalar(0, 255, 0), 2);
if (i)
{
line(mShowImg, o_vptROI[i - 1] * o_dblScaleFactor, point, Scalar(0, 0, 255), 2);
circle(mShowImg, point, 5, Scalar(0, 255, 0), 3);
}
}
//* 4个点选择完毕了
if (o_vptROI.size() == 4)
{
//* 将头尾两个角点连起来
Point2f point = o_vptROI[0] * o_dblScaleFactor;
line(mShowImg, point, o_vptROI[3] * o_dblScaleFactor, Scalar(0, 0, 255), 2);
circle(mShowImg, point, 5, Scalar(0, 255, 0), 3);
//* 进行透视转换
//* ===================================================================================================================
vector<Point2f> vptDstCorners(4);
//* 目标角点左上点,以下4个点的位置确定是按照顺时针方向定义的,换言之,用户必须先按照左上、右上、右下、左下的顺序
//* 选择变换区域才能变换出用户希望的图片样子
vptDstCorners[0].x = 0;
vptDstCorners[0].y = 0;
//* norm()函数的公式为:sqrt(x^2 + y^2),计算得到两个二维点之间的欧几里德距离
//* 比较0、1和2、3点之间那个欧式距离最大,大的那个就是目标角点中的右上点,通
//* 过欧式距离计算,就能知道目标右上点具体坐标位置了
vptDstCorners[1].x = (FLOAT)max(norm(o_vptROI[0] - o_vptROI[1]), norm(o_vptROI[2] - o_vptROI[3]));
vptDstCorners[1].y = 0;
//* 目标角点的右下点
vptDstCorners[2].x = (float)max(norm(o_vptROI[0] - o_vptROI[1]), norm(o_vptROI[2] - o_vptROI[3]));
vptDstCorners[2].y = (float)max(norm(o_vptROI[1] - o_vptROI[2]), norm(o_vptROI[3] - o_vptROI[0]));
//* 目标角点的左下点
vptDstCorners[3].x = 0;
vptDstCorners[3].y = (float)max(norm(o_vptROI[1] - o_vptROI[2]), norm(o_vptROI[3] - o_vptROI[0]));
//* 计算转换矩阵,并转换
Mat H = findHomography(o_vptROI, vptDstCorners);
warpPerspective(mSrcImg, mResultImg, H, Size(cvRound(vptDstCorners[2].x), cvRound(vptDstCorners[2].y)));
//* 显示转换结果
cv2shell::ShowImageWindow(pszDestImgWinName, TRUE);
imshow(pszDestImgWinName, mResultImg);
//* ===================================================================================================================
}
imshow(pszSrcImgWinName, mShowImg);
}
}
//* 销毁两个操作窗口
destroyWindow(pszSrcImgWinName);
destroyWindow(pszDestImgWinName);
}
//* 鼠标处理事件
static void EHImgPerspecTrans_OnMouse(INT nEvent, INT x, INT y, INT nFlags, void *pvIPT)
{
ImagePerspectiveTransformation *pobjIPT = (ImagePerspectiveTransformation *)pvIPT;
vector<Point2f>& vptROI = pobjIPT->GetROI();
DOUBLE dblScaleFactor = pobjIPT->GetScaleFactor();
//* 转变成原始图片坐标
FLOAT flSrcImgX = ((FLOAT)x) / dblScaleFactor;
FLOAT flSrcImgY = ((FLOAT)y) / dblScaleFactor;
//* 鼠标已按下
if (nEvent == EVENT_LBUTTONDOWN)
{
//* 看看用户点击的是不是已经存在的角点,如果是,则支持用户拖拽以调整透视变换区域及角度
for (INT i = 0; i < vptROI.size(); i++)
{
if (abs(vptROI[i].x - flSrcImgX) < MOUSE_SHOT_OFFSET && abs(vptROI[i].y - flSrcImgY) < MOUSE_SHOT_OFFSET)
{
pobjIPT->SetDragingCornerPointIndex(i);
break;
}
}
}
//* 在这个位置处理鼠标松开事件,三个if语句块的顺序不能变,这样才可避免程序继续响应用户针对某个角点的拖拽事件
if (nEvent == EVENT_LBUTTONUP)
{
//* 还没选择完4个点,则继续添加之
if (vptROI.size() < 4 && INVALID_INDEX == pobjIPT->GetDragingCornerPointIndex())
{
vptROI.push_back(Point2f(flSrcImgX, flSrcImgY));
pobjIPT->NeedToDrawCornerPoint();
}
//* 只要松开鼠标,则不再支持拖拽
pobjIPT->SetDragingCornerPointIndex(INVALID_INDEX);
}
//* 鼠标移动事件
if (nEvent == EVENT_MOUSEMOVE)
{
//* 看看用户是否在某个角点上点击的
INT nCornerPointIdx = pobjIPT->GetDragingCornerPointIndex();
if (nCornerPointIdx != INVALID_INDEX)
{
vptROI[nCornerPointIdx].x = flSrcImgX;
vptROI[nCornerPointIdx].y = flSrcImgY;
pobjIPT->NeedToDrawCornerPoint();
}
}
} |
1e94904e59cbdac48f060bbca62059970689c274 | 0c3bba7e9f749c60f1703448a1d7ca308e1b6e1d | /torches.cpp | e924e42c9192cdcb5dca424660c56d1e4ae65af5 | [] | no_license | theodorekwok/codepractices | 06cdc43b1719a15fd47b61bf39cb4ac8f41875b5 | 9f4b18bbe812b7dcc5b8408fb9f269253a63428b | refs/heads/main | 2023-03-19T00:15:13.359117 | 2021-03-12T14:49:12 | 2021-03-12T14:49:12 | 347,092,280 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | cpp | torches.cpp | #include <bits/stdc++.h>
#define ll long long
using namespace std;
void solve(ll x, ll y, ll k) {
ll num_sticks_for_coal = y * k;
ll total = num_sticks_for_coal + k;
ll trades = (total - 1) % (x - 1) == 0 ? (total - 1)/(x - 1) : (total - 1)/(x - 1) + 1;
cout << trades + k << '\n';
}
int main() {
int t;
cin >> t;
while (t--) {
ll x, y, k;
cin >> x >> y >> k;
solve(x, y, k);
}
}
|
d22b5804de51e41b4b5e5b4d10889291aaac1262 | b081cb2c14c69be0c5e0feb437c5f8a50be70787 | /Typeable.h | 5ae0037a835bcca27c91dbcc95515a8e734e785f | [] | no_license | konchunas/minicraft-psp | 9747239fb941ecd67ac90ec47a4b61b7b42e9b6d | 532a935da0253f7820dd75ce87012db649fe0b75 | refs/heads/master | 2020-04-13T14:35:25.467035 | 2015-01-09T21:52:26 | 2015-01-09T21:52:26 | 13,645,390 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 472 | h | Typeable.h | #ifndef TYPEABLE_H_
#define TYPEABLE_H_
enum ClassType
{
UNDEFINED,
MOB,
PLAYER,
TOOL_ITEM,
RESOURCE_ITEM,
POWERGLOVE_ITEM,
FURNITURE_ITEM,
FURNITURE,
AIR_WIZARD
};
//this class is intended to replace java instainceOf function using predefined enums
class Typeable {
public:
bool instanceOf(ClassType t)
{
if (this->classType() == t)
return true;
return false;
}
virtual ClassType classType()
{
return UNDEFINED;
}
};
#endif /* TYPEABLE_H_ */
|
0dfc3339f5ece350e4ad2addadc30f2b35a31b13 | 311525f7de84975434f55c00b545ccf7fe3dcce6 | /online/cf/244/match_and_catch.cpp | 43281bd22e4cb6f27065b6b0e8a0feb0cf5853a0 | [] | no_license | fishy15/competitive_programming | 60f485bc4022e41efb0b7d2e12d094213d074f07 | d9bca2e6bea704f2bfe5a30e08aa0788be6a8022 | refs/heads/master | 2023-08-16T02:05:08.270992 | 2023-08-06T01:00:21 | 2023-08-06T01:00:21 | 171,861,737 | 29 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,971 | cpp | match_and_catch.cpp | /*
* We can create the suffix array for s1$s2. If there is a unique common substring between the two strings,
* they have to be next to each other in the suffix array. We can also use the LCP array to compare on both
* sides to see if the common substring is longer than adjacent common substrings (which would mean that it
* is not unique in each string).
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <array>
#include <algorithm>
#include <utility>
#include <map>
#include <queue>
#include <set>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <numeric>
#define ll long long
#define ld long double
#define eps 1e-8
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define INFLL 0x3f3f3f3f3f3f3f3f
// change if necessary
#define MAXN 1000000
using namespace std;
int n, m;
string s1, s2;
string tot;
vector<int> sa, lcp;
vector<int> suffix_array(const string &s) {
int n = s.size();
vector<int> sa(n), c(n);
for (int i = 0; i < n; i++) {
sa[i] = n - i - 1;
c[i] = s[i];
}
stable_sort(sa.begin(), sa.end(), [&s](int i, int j) { return s[i] < s[j]; });
for (int len = 1; len < n; len *= 2) {
vector<int> old_c(c), idx(n), old_sa(sa);
iota(idx.begin(), idx.end(), 0);
for (int i = 0; i < n; i++) {
bool same = i > 0 && sa[i - 1] + len < n
&& old_c[sa[i - 1]] == old_c[sa[i]]
&& old_c[sa[i - 1] + len / 2] == old_c[sa[i] + len / 2];
c[sa[i]] = same ? c[sa[i - 1]] : i;
}
for (int i = 0; i < n; i++) {
int loc = old_sa[i] - len;
if (loc >= 0) {
sa[idx[c[loc]]++] = loc;
}
}
}
return sa;
}
vector<int> find_lcp(const string &s, const vector<int> &sa) {
int n = s.size();
vector<int> rank(n);
for (int i = 0; i < n; i++) {
rank[sa[i]] = i;
}
int len = 0;
vector<int> lcp(n - 1);
for (int i = 0; i < n; i++) {
if (rank[i] == n - 1) {
len = 0;
} else {
int j = sa[rank[i] + 1];
while (max(i, j) + len < n && s[i + len] == s[j + len]) len++;
lcp[rank[i]] = len;
if (len > 0) len--;
}
}
return lcp;
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> s1 >> s2;
n = s1.size();
m = s2.size();
tot = s1 + "$" + s2;
sa = suffix_array(tot);
lcp = find_lcp(tot, sa);
int ans = INF;
for (int i = 0; i < n + m; i++) {
auto [lo, hi] = minmax(sa[i], sa[i + 1]);
if (lo < n && hi > n) {
int prev = i == 0 ? 0 : lcp[i - 1];
int cur = lcp[i];
int nxt = i == n + m - 1 ? 0 : lcp[i + 1];
if (max(prev, nxt) < cur) {
ans = min(ans, max(prev, nxt) + 1);
}
}
}
if (ans == INF) ans = -1;
cout << ans << '\n';
return 0;
}
|
283b7bc69d8f43a3e0c35e7d79951c0119d85e3e | d390a36a08e0b2bd3b6235749b81b95e36128784 | /Dxproj/Sound/AudioComponent/ListenerComponent/ListenerComponent.h | 9e7b91835afdae17dbd2c13c1854b5385468fdee | [] | no_license | hasepon/XAudio2Test | 4214f7c8ca78aa5add5343468d49b52e9113e6df | f0d9be75dc48edbc2f761e3aed5d03d2f1e77039 | refs/heads/master | 2021-08-23T09:08:48.912090 | 2017-12-04T12:29:10 | 2017-12-04T12:29:10 | 81,212,809 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 595 | h | ListenerComponent.h | #pragma once
class CSoundComponent;
#include"../../Sound.h"
#include"../SoundComponent/SoundComponent.h"
#include"../../../Calculation.h"
#include"../../XAudio2/X3DAudio/X3DSound/X3DSound.h"
/*
*
* CListenerComponent
* リスナーを設定する用のComponent
*
*/
class CListenerComponent
: public CSoundComponent
{
public:
CListenerComponent();
~CListenerComponent();
void Init(D3DXMATRIX* matrix);
// 更新処理
void ComponentUpdate() override;
void SetListener(D3DXMATRIX* matrix);
private:
X3DAUDIO_LISTENER m_listener;
D3DXMATRIX* m_listenerMtx;
bool m_Uselistener;
}; |
9edd8786cca997dce080990b9c8e2ab57c4bb143 | af5e6a7b02262edb9512deddc00a3d85e66792af | /MyCppGame/Classes/src/FlameEmitter.cpp | 9185440544841f9da674040874a1131d9a15e3c7 | [
"MIT"
] | permissive | ChristopherBuggy/FYP | 0f72905d402ac448c6be3838cebc2d761abee0de | bc5edcd8396ca48ac217f8ee876c09b7ef298708 | refs/heads/master | 2021-01-10T18:20:38.338627 | 2016-04-25T08:27:53 | 2016-04-25T08:27:53 | 45,679,206 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,421 | cpp | FlameEmitter.cpp | #include "FlameEmitter.h"
USING_NS_CC;
FlameEmitter::FlameEmitter(GameStates & gameState) :
m_gameState(gameState),
m_touched(false)
{
}
FlameEmitter * FlameEmitter::create(Vec2 position, GameStates & gameState, int i)
{
std::shared_ptr<GameData> ptr = GameData::sharedGameData();
auto spritecache = SpriteFrameCache::getInstance();
spritecache->addSpriteFramesWithFile(ptr->m_textureAtlasPlistFile);
FlameEmitter* pSprite = new FlameEmitter(gameState);
if (pSprite && pSprite->initWithFile("GameScreen/flameEmitter.png"))
{
// This means the sprite will be deleted when it has no references to it.
pSprite->autorelease();
// This sets the initial sprite position to the parameter 'position'
pSprite->initOptions(position);
// More on this below
//pSprite->addEvents();
auto midPlatBody = PhysicsBody::createBox(Size(pSprite->getContentSize().width, (pSprite->getContentSize().height)), PhysicsMaterial(0, 0, 0));
midPlatBody->setCollisionBitmask(0x000003);
midPlatBody->setRotationEnable(false);
midPlatBody->setContactTestBitmask(true);
midPlatBody->setDynamic(false);
//Assign the body to the platform sprite
pSprite->setPhysicsBody(midPlatBody);
//Set the anchor point. Probably not needed but I'd rather have it done!
pSprite->setAnchorPoint(Point(0.5f, 0.5f));
pSprite->setScale(1.5);
return pSprite;
}
CC_SAFE_DELETE(pSprite);
return NULL;
}
void FlameEmitter::initOptions(Vec2 position)
{
Point origin = Director::getInstance()->getVisibleOrigin();
this->setPosition(position.x + origin.x, position.y + origin.y);
}
void FlameEmitter::addEvents()
{
// Create a "one by one" touch event listener that processes one
// touch at a time.
auto listener = cocos2d::EventListenerTouchOneByOne::create();
// When "swallow touches" is true, then returning 'true' from the onTouchBegan
//method will "swallow" the touch event, preventing other listeners from using it.
listener->setSwallowTouches(true);
// Example of using a lambda expression to implement onTouchBegan event callback function
// In simple terms, at the start of a touch event, this callback function is triggered when the user touches the screen.
// If the touch area is over this sprite, the method returns true to indicate the event was consumed
listener->onTouchBegan = [&](cocos2d::Touch* touch, cocos2d::Event* event)
{
cocos2d::Vec2 pos = touch->getLocation();
cocos2d::Rect rect = this->getBoundingBox();
if (rect.containsPoint(pos))
{
return true; // to indicate that we have consumed it.
}
return false; // we did not consume this event, pass through.
};
// This callback function is triggered when the user releases their touch on this sprite.
// The handleTouchEvent method is then called.
listener->onTouchEnded = [=](cocos2d::Touch* touch, cocos2d::Event* event)
{
handleTouchEvent(touch);
};
// This adds an event listener for the above touch events. If this line is not
// added, the sprite will not respond to touch events.
cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener, 30);
}
void FlameEmitter::handleTouchEvent(cocos2d::Touch* touch)
{
// Change gameState in response to sprite touched
//Put your movement stuff in here (but in your main obvioudly)
m_gameState = GameStates::GameInit;
m_touched = true;
}
bool FlameEmitter::isTouched() const
{
return m_touched;
}
|
45742500f41d08fda07e3e1ef02ad36d727dc593 | 9a1314af456bee446bc3dd6bf49a4be51599ebe9 | /rem/rem.cc | 03e21533c148fae6cf686f6bfc0fa82a9857e2d7 | [] | no_license | joshrands/adhoc-routing-framework | 614808b86a3045baf2bf0bea24cb3d0bbf016b34 | ba26544cdcb271d298f084190d5ce744ede909b8 | refs/heads/master | 2021-06-24T13:58:08.944846 | 2021-02-12T16:10:07 | 2021-02-12T16:10:07 | 205,958,978 | 2 | 2 | null | 2020-10-26T17:09:55 | 2019-09-03T00:48:10 | C++ | UTF-8 | C++ | false | false | 8,469 | cc | rem.cc | #include "rem.h"
#include "assert.h"
#include <chrono>
#include <ctime>
#include <string.h>
void REM::initialize(IP_ADDR parentIp)
{
m_parentIp = parentIp;
simStartTime = this->_getCurrentTimeMS();
if (REM_DEBUG)
cout << "[DEBUG]: Initializing REM monitoring service for node " << getStringFromIp(m_parentIp) << endl;
localBatteryModel.HOP_COUNT = HOP_COUNT;
localBatteryModel.modelParameters.UPDATE_FREQUENCY = localBatteryModel.UPDATE_FREQUENCY;
// initialize this node's battery model
initializeBatteryModel();
}
void REM::initializeBatteryModel()
{
if (localBatteryModel.getDataCount() < localBatteryModel.INIT_COUNT)
{
localBatteryModel.setState(ModelState::INIT);
if (BATTERY_DEBUG)
cout << "[DEBUG]: Insufficient data to build battery model" << endl;
// this model is for parent of this network monitoring object
localBatteryModel.ownerIp = getParentIp();
localBatteryModel.initialize();
}
else
{
if (BATTERY_DEBUG)
cout << "[WARNING]: This model should not be being initialized" << endl;
}
}
void REM::initializeRssModel(IP_ADDR pairIp)
{
// create a new model
RssModel model;
model.ownerIp = m_parentIp;
model.pairIp = pairIp;
model.dataCount = 0;
model.HOP_COUNT = this->HOP_COUNT;
model.initialize();
if (REM_DEBUG)
cout << "[DEBUG]: Local RSS model initialized." << endl;
model.setState(ModelState::STABLE);
localRssModels[pairIp] = model;
}
void REM::updateLocalModels()
{
if (MONITOR_DEBUG)
cout << "[DEBUG]: Updating local models" << endl;
updateLocalBatteryModel(this->getCurrentBatteryLevel());
// this function is being continously called by a thread and upon updating pair data
localMonitoringData[m_parentIp].batteryLevel = getBatteryLevel();
// clear pair monitoring data and update with new
pairMonitoringData.clear();
routing->resetLinks();
auto it = localRssModels.begin();
while (it != localRssModels.end())
{
if (it->second.getState() == ModelState::STABLE)
{
pair_data data;
data.pairIp = it->first;
data.rss = it->second.getDataPoint(_getCurrentTimeMS());
if (data.rss > RSS_OUT_OF_RANGE)
{
// if (MONITOR_DEBUG)
// std::cout << "[REM]: Adding link to node " << to_string(data.pairIp) << std::endl;
pairMonitoringData[m_parentIp].push_back(data);
routing->addLink(data.pairIp);
}
}
it++;
}
}
void REM::handleMonitoringPacketBuffer(char* packet, int length, IP_ADDR source, int port)
{
// current packet structure (double check sendUpdatedModel)
/********8********16********24********32
* Node IP Address
* Resrv | Time to live |Model Type
* Mu (float)
* Beta (float)
* Sigma (float)
* Pair IP (Optional)
***************************************/
// decode the packet
ModelParameters params;
// buffer is in REMModelPacket format
REMModelPacket modelPacket;
memcpy(&modelPacket, packet, sizeof(modelPacket));
params.ownerId = modelPacket.parentIp;
params.type = (ModelType)modelPacket.type;
params.timeToLive = modelPacket.timeToLive;
params.mu = modelPacket.mu;
params.beta = modelPacket.beta;
params.sigma = modelPacket.sigma;
if (REM_DEBUG)
cout << "[DEBUG]: REM model type: " << params.type << endl;
// Create model!
switch (params.type)
{
case ModelType::BATTERY:
{
if (REM_DEBUG)
cout << "[DEBUG]: Adding network battery model for node " << getStringFromIp(params.ownerId) << endl;
BatteryModel batteryModel;
batteryModel.modelParameters = params;
batteryModel.ownerIp = params.ownerId;
batteryModel.setState(ModelState::STABLE);
// add the model to the list of network models
netBatteryModels[params.ownerId] = batteryModel;
}
break;
case ModelType::RSS:
{
// pair data!
params.pairId = modelPacket.pairIp;
if (REM_DEBUG)
cout << "[DEBUG]: Adding network rss model for node " << getStringFromIp(params.ownerId) << " between " << getStringFromIp(params.pairId) << endl;
RssModel rssModel;
rssModel.modelParameters = params;
rssModel.ownerIp = params.ownerId;
rssModel.setState(ModelState::STABLE);
netRssModels[params.ownerId][params.pairId] = rssModel;
}
break;
default:
cout << "[ERROR]: Unknown REM model type." << endl;
break;
}
}
double REM::getBatteryLevel(IP_ADDR ownerIp)
{
if (signed(ownerIp) == -1)
{
return localBatteryModel.getDataPoint(_getCurrentTimeMS());
}
else
{
return netBatteryModels[ownerIp].getDataPoint(_getCurrentTimeMS());
}
}
double REM::getRSSBetweenNodes(IP_ADDR pairIp, IP_ADDR ownerIp = -1)
{
if (signed(ownerIp) == -1)
{
// this is a local model
return localRssModels[pairIp].getDataPoint(_getCurrentTimeMS());
}
else
{
return netRssModels[ownerIp][pairIp].getDataPoint(_getCurrentTimeMS());
}
}
void REM::updateLocalBatteryModel(double batteryLevel)
{
// adding a new point might result in a new model...
localBatteryModel.addDataPoint(batteryLevel, _getCurrentTimeMS());
// if the model needs to be broadcasted, do it!
if (localBatteryModel.needsToBeBroadcasted)
{
if (REM_DEBUG)
cout << "[DEBUG]: Sending updated battery model from node " << getStringFromIp(m_parentIp) << endl;
sendUpdatedModel(&localBatteryModel, getIpFromString(BROADCAST_STR));
// model has been broadcasted
localBatteryModel.needsToBeBroadcasted = false;
}
}
void REM::updateLocalRSSModel(IP_ADDR pairIp, double rss)
{
// check if node already has this model
if (localRssModels.count(pairIp) <= 0)
{
initializeRssModel(pairIp);
}
if (REM_DEBUG)
cout << "[DEBUG]: Updating local RSS model between " << getStringFromIp(m_parentIp) << " and " << getStringFromIp(pairIp) << endl;
// adding a data point might result in a new model...
localRssModels[pairIp].addDataPoint(rss, _getCurrentTimeMS());
// if the model needs to be broadcasted, do it!
if (localRssModels[pairIp].needsToBeBroadcasted)
{
sendUpdatedModel(&(localRssModels[pairIp]), getIpFromString(BROADCAST_STR));
// model has been broadcasted
localRssModels[pairIp].needsToBeBroadcasted = false;
}
}
void REM::updateNetworkBatteryModel(IP_ADDR ownerIp, BatteryModel model)
{
netBatteryModels[ownerIp] = model;
}
void REM::updateNetworkRSSModel(IP_ADDR ownerIp, IP_ADDR pairIp, RssModel model)
{
netRssModels[ownerIp][pairIp] = model;
}
void REM::sendUpdatedModel(PredictionModel* model, IP_ADDR dest)
{
/********8********16********24********32
* Node IP Address
* Resrv | Time to live |Model Type
* Mu (float)
* Beta (float)
* Sigma (float)
* Pair IP (Optional)
***************************************/
REMModelPacket packet = model->createREMModelPacket();
// allocate 20 bytes for a model packet
int size = sizeof(packet);
if (REM_DEBUG)
cout << "[DEBUG]: Sending REM model packet. Size = " << size << endl;
if (routing == nullptr)
cout << "[ERROR]: NO ROUTING PROTOCOL" << endl;
else
{
char* buffer = (char*)(malloc(size));
memcpy(buffer, &packet, size);
routing->sendPacket(this->getPortId(), buffer, size, getIpFromString(BROADCAST_STR), MONITOR_PORT);
delete buffer;
}
}
void REM::updatePairData(pair_data pairData)
{
if (REM_DEBUG)
cout << "[DEBUG]: Updating pair data for REM model" << endl;
updateLocalRSSModel(pairData.pairIp, pairData.rss);
}
double REMTest::getCurrentBatteryLevel()
{
return m_battery;
}
uint64_t REMTest::_getCurrentTimeMS()
{
return m_clock_MS;
}
void REMTest::drainBattery()
{
m_battery -= 2;
}
|
400898967a3ce2252e3567ee2e7ad17a18645bfe | 41823c261082cc74037f56be62996600422fe518 | / world-opponent-network/wonapi/WONLobby/LanTypes.h | 2ffab1c7799f2580d2607f35fe176000095ffbc5 | [] | no_license | ECToo/world-opponent-network | 90adf14ca8b324898a1f0b2202c1cfb2b4bdeb03 | fbb35876ae26006606d07b6297d557bd53234066 | refs/heads/master | 2021-01-25T07:40:21.063935 | 2014-05-16T16:02:54 | 2014-05-16T16:02:54 | 32,217,407 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,241 | h | LanTypes.h | #ifndef __WON_LANTYPES_H__
#define __WON_LANTYPES_H__
namespace WONAPI
{
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
enum LanBroadcastMsgType
{
LanBroadcastMsgType_GameInfo = 1,
LanBroadcastMsgType_Heartbeat = 2,
LanBroadcastMsgType_GameDeleted = 3,
LanBroadcastMsgType_GameInfoRequest = 4
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
enum LanMsgType
{
LanMsgType_RegisterRequest = 1,
LanMsgType_RegisterReply = 2,
LanMsgType_ClientJoined = 3,
LanMsgType_ClientLeft = 4,
LanMsgType_ChatRequest = 5,
LanMsgType_Chat = 6,
LanMsgType_KeepAlive = 7,
LanMsgType_GameMessage = 8
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
enum LanRegisterStatus
{
LanRegisterStatus_Success = 0,
LanRegisterStatus_None = 1,
LanRegisterStatus_BadPassword = 2,
LanRegisterStatus_NotOnSubnet = 3
};
} // namespace WONAPI
#endif |
2cf35643a76e7df63cab124a198f28ca309af532 | 71234b346984f6cf5fdeb8d6d3fe9440a04bb1c8 | /NxtLibrary/connection.h | 7a7f5aa551935042ae1fc9ba2239f2a8577c70e6 | [
"MIT"
] | permissive | fvigneault/NXT-FTL | a4c1d0441f064c97912a02417adbb79dea5b9fc7 | 86585f228ca0af1802a1def47b5240d5ade8bb6b | refs/heads/master | 2020-03-17T11:52:03.217004 | 2018-04-12T15:12:34 | 2018-04-12T15:12:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,186 | h | connection.h | #ifndef CONNECTIONH
#define CONNECTIONH
#include <string>
#define NXT_BUFFER_SIZE 64
using namespace std;
/**
* Connection type enumeration
@see Connection#get_type
*/
enum Connection_type {
/**
* Bluetooth connection
*/
BT = 0x00,
/**
* Network connection
*/
NXT_NETWORK = 0x01
};
/**
* Network server mode enumeration
* @see Server_settings_t
* @see Nxt_network#Connect
*/
enum Server_mode{
/**
* The server will close down when BT communication with the NXT is lost
*/
CLOSE_DOWN = 0,
/**
* The server will (try) reconnect to the NXT when BT communication is lost
*/
RECONNECT = 1
};
/**
* Struct used to retriece server settings when a network connection is used
* @see Nxt_network#Connect
* @see Server_mode
*/
struct Server_settings_t{
/**
* The mode of the server
*/
Server_mode mode;
/**
* The timeout of the client in milliseconds. If clients are
* inactive for more than the timeout they will be thrown off. If timeout is zero timeout has been disabled
*/
unsigned int timeout;
};
/**
* typedef for Server_settings_t
* @see Server_settings_t
* @see Nxt_network#Connect
*/
typedef Server_settings_t Server_settings;
/**
* Abstract class for connections
*/
class Connection {
public:
virtual ~Connection(){};
/**
* Send a byte string
* (must be implemented in sub class)
* @param *buffer [a pointer to a buffer that can hold the bytes to send]
* @param num_bytes [the number of bytes to send]
*/
virtual void send(unsigned char *buffer,unsigned int num_bytes)=0;
/**
* Connect to the NXT using BT
* (Dummy method does nothing - is implemented in sub class)
* @param comport [specify the comport that is to used for the BT connection between the NXT and PC]
*/
virtual void connect(unsigned int comport){return;}
/**
* Connect to the NXT using a network connection
* (Dummy method does nothing - is implemented in sub class)
* @param port [specify the port that is to used for the network connection between the NXT and PC]
* @param ip_add [specify the IP-address]
* @param settings [used to retrive server settings]
* @param password [set the password]
* @see Server_settings_t
*/
virtual void connect(unsigned int port, string ip_add){return;}
/**
* Disconnect from the NXT
* (must be implemented in sub class)
*/
virtual void disconnect()=0;
/**
* Receive a byte string
* (must be implemented in sub class)
* @param *buffer [a pointer to a buffer that can hold the received bytes]
* @param length [the number of bytes to receive]
*/
virtual void receive(unsigned char *buffer, unsigned int length)=0;
/**
* Flush the input and output buffer
* (must be implemented in sub class)
*/
virtual void flush()=0;
/**
* Get the connection type
* (must be implemented in sub class)
* @return the connection type
*/
virtual Connection_type get_type()=0;
protected:
};
#endif
|
32198ba365062df94a5912ee0cccea205b9042cd | 7da4022520c45e170458368b6c073ad7b8298b64 | /546A.cpp | aa2c9362feaf5f87bcf814ef61827acb742d4e93 | [] | no_license | SebastianCD/coding-problems | a997c55924e34cb7f97617c35cbff9e8c589fc11 | 8bc24796cabdb391c0dd5e7baba0af4671573f8e | refs/heads/main | 2023-08-03T22:49:56.045656 | 2021-09-18T02:34:03 | 2021-09-18T02:34:03 | 405,277,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 203 | cpp | 546A.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
long long int n, m, k;
cin>>n>>m>>k;
k=(k*(k+1))/2;
k=k*n;
if(k-m>0){
cout<<k-m<<endl;
}
else{
cout<<0<<endl;
}
return 0;
} |
2d6a2c993e721d5534239a9eca45a2f1e333d21d | d8e7a11322f6d1b514c85b0c713bacca8f743ff5 | /7.6.00.32/V76_00_32/MaxDB_ORG/sys/src/SAPDB/SQLManager/Catalog/Catalog_ICallBack.hpp | dcdd4df7f82acc18cf1881fd964486437574ff4b | [] | no_license | zhaonaiy/MaxDB_GPL_Releases | a224f86c0edf76e935d8951d1dd32f5376c04153 | 15821507c20bd1cd251cf4e7c60610ac9cabc06d | refs/heads/master | 2022-11-08T21:14:22.774394 | 2020-07-07T00:52:44 | 2020-07-07T00:52:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,482 | hpp | Catalog_ICallBack.hpp | /*!
@file Catalog_ICallBack.hpp
@author ThomasA
@brief callback interface for catalog iterators
@ingroup Catalog
\if EMIT_LICENCE
========== licence begin GPL
Copyright (c) 2000-2005 SAP AG
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
========== licence end
\endif
*/
#ifndef Catalog_ICallBack_hpp
#define Catalog_ICallBack_hpp
class Catalog_Object;
/*!
@brief defines the interface of the callback called by Catalog_IAuthorization::ForEach
*/
class Catalog_ICallBack
{
public :
/*!
@brief this method is called for each authorization object found by Catalog_IAuthorization::ForEach
@param pContext pointer to the current authorization object
*/
virtual bool Callback(Catalog_Object* pContext) = 0;
};
#endif |
941d678e9cc0794918065a11d9449f39c286c9ed | 3656678dc7d03f91300de4e3a7a1ace9792fb512 | /upstairs/upstairs/源.cpp | 5257126569530ffede0ac91158349f8e66725b77 | [] | no_license | changtingwai/leetcode | ed29d32c7a3f8d93253066bb053726a668cc788d | 5b0eca6fd65b522db02776a36ad442cc858b0530 | refs/heads/master | 2021-01-10T13:31:34.933142 | 2016-03-10T03:06:34 | 2016-03-10T03:06:34 | 53,551,534 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | cpp | 源.cpp | #include <iostream>
#include <vector>
#include <set>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
if (nums.size()==0)
return false;
set<int> hs;
int i;
for ( i=0;i<nums.size();i++)
{
if(hs.count(nums[i]))
{
return true;
}
else
hs.insert(nums[i]);
}
return false;
}
};
int main()
{
Solution s1;
int a[]={0};
int i=0;
//for(i=0;i<5;i++)
// cout<<i;
cout<<s1.containsDuplicate(vector<int>(a,a+4));
system("pause");
return 0;
} |
af199afcba8736e45f833fd196621fb5a702bbd0 | fa652de84a51ec3a4e749caafe61af9279702351 | /gac1.cpp | 40d57f398a5e12b405edd94a68187bea0a6e212d | [] | no_license | sunny30/gcj | 20bc5bdaa1f417fb25be005b092c36b2287d0792 | da752debb551d64f34d611941fa926a4caeeacb1 | refs/heads/master | 2021-01-23T11:49:43.010594 | 2015-03-22T21:44:22 | 2015-03-22T21:44:22 | 32,696,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 837 | cpp | gac1.cpp | #include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<vector>
#include<string>
#include<string.h>
#include<set>
#include<map>
#include<fcntl.h>
#include<stack>
#include<queue>
#include<iostream>
using namespace std ;
typedef int64_t LL ;
int main(){
FILE *fp = freopen("1.in","r",stdin) ;
FILE *fp1 =freopen("1.out","w",stdout) ;
int test ;
scanf("%d",&test) ;
for(int i=1;i<=test;i++){
printf("Case #%d: ",i) ;
int n ;
cin>>n ;
vector<LL> v1 ;
vector<LL> v2 ;
for(int i=1;i<=n;i++){
int tmp ;
cin>>tmp ;
v1.push_back(tmp) ;
}
for(int i=1;i<=n;i++){
int tmp ;
cin>>tmp ;
v2.push_back(tmp) ;
}
sort(v1.begin(),v1.end()) ;
sort(v2.begin(),v2.end()) ;
LL ans = 0 ;
for(int i=0;i<n;i++){
ans+=(LL)(v1[i]*v2[n-1-i]) ;
//cout<<ans<<endl ;
}
cout<<ans<<endl ;
}
}
|
71ccef4523f9ab3811bdae9325df03c53eca7d2c | 79d3f311e5407280a5db0469e0c01cb5b7cb27f6 | /src/ShadertoyJSON.h | 1e5d8379b6e2f084eaccc362b87fc87696b44ac3 | [
"MIT"
] | permissive | kuzy000/runfragment | 0e102b2adb71ece4d8c6ec9fca43b294da8cda9c | 569195eeca11c80051e254c13bf1e7cd9dc7b829 | refs/heads/master | 2020-04-10T15:52:45.499674 | 2016-10-06T00:18:15 | 2016-10-06T00:18:15 | 51,010,407 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,204 | h | ShadertoyJSON.h | #pragma once
#include <vector>
#include <rapidjson/document.h>
namespace RunFragment {
struct ShadertoyJSON {
const std::string ver;
struct Info {
const std::string name;
const std::string username;
Info(const rapidjson::Document::ValueType& d)
: name {d["name"].GetString()}
, username {d["username"].GetString()}
{}
} info;
struct RenderPass {
struct Input {
const std::size_t id;
const std::string src;
const std::string ctype;
const std::size_t channel;
struct Sampler {
const std::string vflip;
Sampler(const rapidjson::Document::ValueType& d)
: vflip {d["vflip"].GetString()} {}
};
const Sampler sampler;
Input(const rapidjson::Document::ValueType& d)
: id {d["id"].GetUint()}
, src {d["src"].GetString()}
, ctype {d["ctype"].GetString()}
, channel {d["channel"].GetUint()}
, sampler {d["sampler"]}
{}
};
const std::vector<Input> inputs;
struct Output {
const std::size_t id;
const std::size_t channel;
Output(const rapidjson::Document::ValueType& d)
: id {d["id"].GetUint()}
, channel {d["channel"].GetUint()}
{}
};
const std::vector<Output> outputs;
const std::string code;
const std::string name;
const std::string type;
RenderPass(const rapidjson::Document::ValueType& d)
: inputs {
[&d] {
std::vector<Input> result;
for(const auto& input : d["inputs"].GetArray()) {
result.emplace_back(input);
}
return result;
} ()
}
, outputs {
[&d] {
std::vector<Output> result;
for(const auto& output : d["outputs"].GetArray()) {
result.emplace_back(output);
}
return result;
} ()
}
, code {d["code"].GetString()}
, name {d["name"].GetString()}
, type {d["type"].GetString()}
{}
};
const std::vector<RenderPass> renderpass;
ShadertoyJSON(const rapidjson::Document::ValueType& d)
: ver {d["Shader"]["ver"].GetString()}
, info {d["Shader"]["info"]}
, renderpass {
[&d] {
std::vector<RenderPass> result;
for(const auto& pass : d["Shader"]["renderpass"].GetArray()) {
result.emplace_back(pass);
}
return result;
} ()
} {}
};
}
|
fc31edcd3dcf77a69885cf85735eed4394b300a6 | c7e65a70caf87041afd27441fe45eac85e8cd1e4 | /apps/hls_examples/fanout_hls/pipeline.cpp | 9bdf3819c408961afdca9bcd2aa5a67566c444a9 | [
"MIT"
] | permissive | jeffsetter/Halide_CoreIR | adb8d9c4bc91b11d55e07a67e86643a0515e0ee6 | f2f5307f423a6040beb25a1f63a8f7ae8a93d108 | refs/heads/master | 2020-05-23T18:06:27.007413 | 2018-10-02T22:09:02 | 2018-10-02T22:09:02 | 84,777,366 | 7 | 1 | NOASSERTION | 2018-11-05T15:05:11 | 2017-03-13T02:50:55 | C++ | UTF-8 | C++ | false | false | 2,229 | cpp | pipeline.cpp | #include "Halide.h"
#include <string.h>
using namespace Halide;
using std::string;
Var x("x"), y("y"), c("c");
Var xo("xo"), xi("xi"), yi("yi"), yo("yo");
class MyPipeline {
public:
ImageParam input;
Func A;
Func B;
Func C;
Func hw_output;
Func output;
std::vector<Argument> args;
MyPipeline() : input(UInt(8), 1, "input"),
A("A"), B("B"), C("C"), hw_output("hw_output")
{
// define the algorithm
A = BoundaryConditions::repeat_edge(input);
B(x) = A(x-1) + A(x);
C(x) = A(x+1);
hw_output(x) = A(x) + A(x+1) + B(x) + B(x+1) + C(x);
output(x) = hw_output(x);
// define common schedule: tile output
args.push_back(input);
}
void compile_cpu() {
std::cout << "\ncompiling cpu code..." << std::endl;
//output.print_loop_nest();
//output.compile_to_lowered_stmt("pipeline_native.ir.html", args, HTML);
output.compile_to_header("pipeline_native.h", args, "pipeline_native");
output.compile_to_object("pipeline_native.o", args, "pipeline_native");
}
void compile_hls() {
std::cout << "\ncompiling HLS code..." << std::endl;
// HLS schedule: make a hw pipeline producing 'hw_output', taking
// inputs of 'clamped', buffering intermediates at (output, xo) loop
// level
A.compute_root();
hw_output.compute_root();
hw_output.split(x, xo, xi, 64);
hw_output.accelerate({A}, xi, xo);
A.fifo_depth(hw_output, 4).fifo_depth(C, 2);
B.linebuffer();
C.linebuffer();
//output.print_loop_nest();
// Create the target for HLS simulation
Target hls_target = get_target_from_environment();
hls_target.set_feature(Target::CPlusPlusMangling);
output.compile_to_lowered_stmt("pipeline_hls.ir.html", args, HTML, hls_target);
output.compile_to_hls("pipeline_hls.cpp", args, "pipeline_hls", hls_target);
output.compile_to_header("pipeline_hls.h", args, "pipeline_hls", hls_target);
}
};
int main(int argc, char **argv) {
MyPipeline p1;
p1.compile_cpu();
MyPipeline p2;
p2.compile_hls();
return 0;
}
|
83a34a84a408c0634c14aceff8250145f2bfd7c1 | 386a7666e7b5418bf9c7fe2626bea45a67fcaa19 | /Exhaustive_search/P69348.cc | 510902724d7ba907615cf0390a1e498928f264c8 | [] | no_license | sanchyy/Jutge-EDA | d6392b6f05407273561df0595b33645ea70b4b02 | 4d88e0a42236a05716467e49a0d89bc6f823d2fd | refs/heads/master | 2021-04-28T07:05:32.074448 | 2018-05-28T09:54:33 | 2018-05-28T09:54:33 | 122,217,246 | 0 | 1 | null | 2018-05-28T06:58:50 | 2018-02-20T15:34:01 | C++ | UTF-8 | C++ | false | false | 502 | cc | P69348.cc | #include <iostream>
#include <vector>
using namespace std;
void f(int n,int k, vector <int> &v,vector<bool> &b) {
if (k == n) {
cout << '(';
for (int i = 0; i < n; ++i)
cout << (i ? "," : "") << v[i];
cout << ')' << endl;
}
else {
for (int i = 1; i <= n; ++i) {
if (!b[i-1]){
v[k] = i; b[i-1] = true; f(n,k+1,v,b);
b[i-1]=false;
}
}
}
}
int main() {
int n; cin >> n;
vector <int> v(n);
vector <bool>visited(n,false);
f(n,0,v,visited);
}
|
1725b33389bd014f29816b47bd3a1722af110deb | 4a603a30603d52c3167eaad39913f349f480d3e8 | /algor.cpp | db1d74bdcf2c47515335572fc67b1ec4e4a93fbf | [] | no_license | Csraf/Algorithm | e1fed921f3ee42de15fb14926d2993601ba85a2f | 6cb735471c422887908bd7862a99b204099c19d3 | refs/heads/master | 2023-05-30T22:07:32.854425 | 2021-07-08T12:22:52 | 2021-07-08T12:22:52 | 383,974,676 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,262 | cpp | algor.cpp | #include<iostream>
#include<string>
#include<vector>
using namespace std;
bool hashTable[11]={false};
void dfs(int index, int n, string &item, string str, vector<string> &vs){
if(index == n){
vs.push_back(item);
cout<< "##### " << item << endl;
return ;
}
for(int i=0; i<n; i++){
cout << "index " << index << " i " << i << endl;
for(int j=0; j<2; j++){
cout << "hashTable[i] " << hashTable[j] << " ";
}
if(hashTable[i] == false){
hashTable[i] = true;
item.push_back(str[i]);
cout<< "before " << item << endl;
dfs(index+1, n, item, str, vs);
cout<< "after " << item << endl;
item.pop_back();
hashTable[i] = false;
cout << hashTable[i] << endl;
}
}
}
vector<string> Permutation(string str) {
vector<string> vs;
// for(int i=0; i<1001; i++){
// hashTable.push_back(false);
// }
string item="";
if(str.size() == 0) return vs;
dfs(0, str.size(), item, str, vs);
return vs;
}
int main(){
string str = "ab";
vector<string> v = Permutation(str);
for(int i=0; i<v.size(); i++){
cout << v[i] << endl;
}
return 0;
} |
785ff805c8f193a522e9d2fab85b77000464d64a | ee2c4386b2b6feafd06f0b767b37391f10925b88 | /arrowCSVReader.cpp | 0922bd5b06d161413dc20d3efe706a6062e108de | [] | no_license | mohandotyes/ApacheArrowTutorial | cdbe3fe5b0bc9258b0b913123df6af7c68a41423 | bc364f75905e7de1c558c879cdc4525c77e3e7ce | refs/heads/master | 2022-09-03T00:23:13.050263 | 2020-05-27T07:20:25 | 2020-05-27T07:20:25 | 267,248,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,062 | cpp | arrowCSVReader.cpp | #include <iostream>
#include <vector>
#include <arrow/api.h>
#include <arrow/csv/api.h>
#include <arrow/io/file.h>
#include <string>
#include <tuple>
#include <arrow/stl.h>
#include <algorithm>
#include <arrow/util/iterator.h>
#include <arrow/io/api.h>
#include <arrow/compute/kernel.h>
int main()
{
arrow::MemoryPool* pool = arrow::default_memory_pool();
std::shared_ptr<arrow::io::InputStream> input;
std::string csv_file = "yellow_tripdata_2019-01.csv";
auto cvsFile = arrow::io::ReadableFile::Open(csv_file);
if(cvsFile.ok()){
input = std::move(cvsFile).ValueOrDie();
auto read_options = arrow::csv::ReadOptions::Defaults();
auto parse_options = arrow::csv::ParseOptions::Defaults();
auto convert_options = arrow::csv::ConvertOptions::Defaults();
// Instantiate TableReader from input stream and options
auto reader = arrow::csv::TableReader::Make(pool, input, read_options, parse_options, convert_options);
if(reader.ok()){
std::shared_ptr<arrow::csv::TableReader>tableReader = std::move(reader).ValueOrDie();
auto t = tableReader->Read();
if(t.ok()){
std::shared_ptr<arrow::Table> table = std::move(t).ValueOrDie();
//int64_t rows = table->num_rows();
//int64_t columns = table->num_columns();
//std::cout << "rows:- " << rows << " columns:- " << columns << '\n';
std::shared_ptr<arrow::ChunkedArray> myfield = table->column(9);
//std::cout << myfield->length() << std::endl;
arrow::ArrayVector data = myfield->chunks();
std::vector<int64_t> vec;
for(int64_t i = 0 ; i < 656 ; i++){
auto int64_array = std::static_pointer_cast<arrow::Int64Array>(data[i]);
for(int64_t j = 0; j < data[i]->length() ; j++){
if(!int64_array->IsNull(j)){
vec.emplace_back(int64_array->Value(j));
}
}
}
//std::cout << vec.size() << std::endl;
std::sort(vec.begin(),vec.end());
auto [min,max] = std::minmax_element(vec.begin(),vec.end());
std::cout << "min " << *min << " max " << *max << std::endl;
}
}
}
}
|
cecb465c8f665e3d749b1e5355e4e5ee6e187da7 | b02e12c03cd07ef829a07a25f50b8ffd6a6b7548 | /src/libqdigibib/DBLibrary.h | 61542a07f67f3f7320209bf002c12ab433d7a65b | [] | no_license | uly55e5/QDigibib | 5fb1063c10a2dd014fbe4aab092cb77dd9701dda | 2bda0c3efb7c7d1de62648a08e44fa929b94ad70 | refs/heads/master | 2021-01-22T07:13:37.612859 | 2009-08-10T22:56:02 | 2009-08-10T22:56:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,018 | h | DBLibrary.h | /*
* DBLibrary.h
*
* Created on: 06.08.2009
* Author: uly55e5
*/
#ifndef DBLIBRARY_H_
#define DBLIBRARY_H_
#include <QObject>
#include <QStringList>
namespace QDigibib
{
class DBVolume;
typedef QList<DBVolume *> DBVolumeList; ///< A List of volumes
/*! \brief Manages a set of volumes from the "Digitale Bibliothek"
*
* A library is defined by a set of paths to folders, which are searched
* recursively for the volumes. Use setPaths(), addPath() and removePath() to
* manage these folders. Get the folders with paths().
*
*/
class DBLibrary: public QObject
{
Q_OBJECT
public:
DBLibrary();
virtual ~DBLibrary();
/*! \brief List of paths used for at library creation.
*
* \sa addPath(), removePath(), setPaths()
*
* \return A list of absolute paths
*/
QStringList paths();
/*! \brief Set the paths for the current library.
*
* The paths should be absolute canonical paths of folders.
*
* \sa paths(), addPath()
*
* \param paths A list of absolute paths
*/
void setPaths(const QStringList & paths);
/*! \brief Add a path to the library paths.
*
* The path should be a canonical path of a folder.
*
* \sa removePath(), setPaths()
* \param path An absolute path
*/
void addPath(const QString & path);
/*! \brief Remove a path from the library paths.
*
* First the method tries to match the path against the list of paths
* by string comparison. If this fails the canonical path is used.
*
* \sa addPath(), paths()
*
* \param path An absolute path
* \return True on success
*/
bool removePath(const QString & path);
private:
/*! \brief Find DB Volumes in the library paths.
*
* The methods searches for \c digibib.txt files in the paths set
* by _libraryPaths. Then a DBVolume instance is created for every file.
*/
void findVolumes();
QStringList _libraryPaths; ///< The paths where to search for volumes \sa paths()
DBVolumeList _volumeList; ///< List of Volumes in the Library
};
}
#endif /* DBLIBRARY_H_ */
|
2ef3efd021a800677e95dd85d71d9b2554525fbe | bd8bcdb88c102a1ddf2c0f429dbef392296b67af | /sources/Editor/EditorView.cpp | cbdec3329b07757adf673e39a95cd74fce4cf4b5 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | LukasBanana/ForkENGINE | be03cee942b0e20e30a01318c2639de87a72c79c | 8b575bd1d47741ad5025a499cb87909dbabc3492 | refs/heads/master | 2020-05-23T09:08:44.864715 | 2017-01-30T16:35:34 | 2017-01-30T16:35:34 | 80,437,868 | 14 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 17,557 | cpp | EditorView.cpp | /*
* Editor view file
*
* This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "EditorView.h"
#include "EditorViewSceneRenderer.h"
#include "EditorSelectionSceneRenderer.h"
#include "Frame/Main/MainFrame.h"
#include "Frame/Console/ConsoleFrame.h"
#include "Entity/EntitySelector.h"
#include "Entity/Entity.h"
#include "Project/ProjectFolder.h"
#include "Core/UIExtensions/UIScreenFrame.h"
#include "Core/WxHelper.h"
#include "Core/Devices.h"
#include "Core/StaticLayoutConfig.h"
#include "Core/StringModifier.h"
#include "Video/RenderSystem/RenderContextException.h"
#include "Video/RenderSystem/RenderSystem.h"
#include "Utility/RendererProfilerOutput.h"
#include "Scene/Renderer/BoundingBoxSceneRenderer.h"
namespace Fork
{
namespace Editor
{
/*
* Internal members
*/
using namespace Utility;
using namespace Devices;
static const float farPlaneProjector = 0.1f;
static const float farPlaneSelector = 0.2f;
/*
* EditorView class
*/
EditorView::GlobalConfiguration EditorView::globalConfig;
EditorView::EditorView(wxWindow* parent)
{
CreateScreenFrame(parent);
/* Setup initial background color */
ChangeBackgroundColor(defaultClearColor);
/* Initialize global states */
Utility::RendererProfilerOutput::InitInfoTextMaxWidth(defaultFont.get());
InitCameraSceneNode();
/*
Create resources for this editor view:
projector util, event handlers.
*/
CreateVisualProjector();
CreateEventHandlers();
}
EditorView::~EditorView()
{
IO::Keyboard::Instance()->RemoveEventHandler( keyboardEventHandler_ );
IO::Mouse ::Instance()->RemoveEventHandler( mouseEventHandler_ );
}
void EditorView::ProcessUserInteraction()
{
if (GetScreenFrame()->HasFocus())
{
cameraCtrl_.moveFactor = config.moveSpeed * TimeScale() * 2.5f;
cameraCtrl_.ProcessMovement(GetCamera());
}
}
void EditorView::Draw()
{
if (!GetScreenFrame()->IsShown())
return;
auto renderContext = GetScreenFrame()->GetRenderContext();
/*
Clear buffers
-> this will also make the render context to the currnet one
*/
renderContext->ClearBuffers();
/* Setup render states */
renderContext->ChangeState( editorViewRasterizerState.get() );
renderContext->ChangeState( renderSystem->GetDefaultDepthStencilState() );
renderContext->ChangeState( renderSystem->GetDefaultBlendState() );
UpdateProjectionAndView();
/* Draw the scene and front menus */
DrawScene();
DrawSelectionHighlight();
DrawFrontMenu3D();
DrawFrontMenu2D();
/* Show final result on the screen */
renderContext->Present();
}
void EditorView::ChangeBackgroundColor(const Video::ColorRGBAf& color)
{
/* Change the background color for the editor view's render context */
GetScreenFrame()->GetRenderContext()->SetupClearColor(color);
}
void EditorView::ChangeProjectorTransition(unsigned long long duration)
{
/* Transition duration of editor view's projector */
projector_->GetModel()->defaultTransitionDuration = duration;
}
void EditorView::MoveView(const Math::Vector3f& direction)
{
GetCamera()->transform.MoveLocal(direction * ViewMoveSpeed());
}
void EditorView::ZoomView(float direction)
{
auto projectorModel = projector_->GetModel();
if (projectorModel->GetProjection().GetOrtho())
{
/* Zoom range for orthogonal projections */
static const float minZoom = 0.01f;
static const float maxZoom = 100.0f;
/* Change view size for orthogonal projection */
auto projection = projectorModel->GetProjection();
{
/*
Use exponential function to smoothly zoom in and out.
Use natural logarithm to re-compute previous orthogonal size.
*/
auto size = std::log(projection.GetOrthoSize().width);
size += direction;
size = std::exp(size);
size = Math::Clamp(size, minZoom, maxZoom);
projection.SetOrthoSize({ size, size});
}
projectorModel->CancelTransition();
projectorModel->SetupProjection(projection);
}
}
bool EditorView::IsFrameOwner(const Platform::Frame* frame) const
{
return GetScreenFrame()->GetAbstractFrame() == frame;
}
/*
* ======= Private: =======
*/
void EditorView::CreateScreenFrame(wxWindow* parent)
{
/* Create screen frame and render context */
screenFrame_ = MakeWxObject<UIScreenFrame>(parent, wxPoint(0, 0), wxSize(300, 200));
screenFrame_->GetAbstractFrame()->userData = this;
if (!UIScreenFrame::CreateRenderContext(screenFrame_))
{
screenFrame_->Destroy();
throw RenderContextException("Render context creation for screen frame failed");
}
screenFrame_->SetResizeCallback([&](const Math::Size2i&){ Draw(); });
}
void EditorView::InitCameraSceneNode()
{
/* Initialize scene camera location */
static const float distanceToOrigin = 2.0f;
camera_.transform.SetPosition({ distanceToOrigin, distanceToOrigin, -distanceToOrigin });
camera_.transform.LookAt({});
camera_.projection.SetPlanes(0.1f, 1000.0f);
cameraCtrl_.SetupRotation(&camera_);
cameraCtrl_.moveFactor = 0.025f;
/* Initialize camera light node with global camera light source */
cameraLight_.lightSource = cameraLightSource;
}
void EditorView::CreateVisualProjector()
{
/* Create and initialize the visual projector util */
projector_ = std::make_unique<EditorViewProjector>(*this, cameraCtrl_);
projector_->GetModel()->SetupViewportDefaultVisual(
GetCamera()->projection.GetViewport(), 100,
0.0f, farPlaneProjector,
farPlaneSelector, 1.0f
);
projector_->GetModel()->SetupProjection(GetCamera()->projection);
}
void EditorView::CreateEventHandlers()
{
keyboardEventHandler_ = std::make_shared<KeyboardEventHandler>(this);
IO::Keyboard::Instance()->AddEventHandler(keyboardEventHandler_);
mouseEventHandler_ = std::make_shared<MouseEventHandler>(this);
IO::Mouse::Instance()->AddEventHandler(mouseEventHandler_);
}
void EditorView::UpdateProjectionAndView()
{
auto renderContext = GetScreenFrame()->GetRenderContext();
/*
Update projector viewport
-> depending on the render context resolution
*/
projector_->GetModel()->SetupViewportDefaultVisual(
{ { 0, 0 }, renderContext->GetVideoMode().resolution.Cast<int>() },
EditorView::globalConfig.projectorVisualSize,
0.0f, farPlaneProjector,
farPlaneSelector, 1.0f
);
/* Update camera view and projection */
GetCamera()->projection = projector_->GetModel()->GetProjection();
GetCamera()->UpdateView();
renderContext->SetupViewport(
projector_->GetModel()->GetProjection().GetViewport()
);
}
void EditorView::DrawScene()
{
/* Update light sources */
if (config.toggleCameraLight)
{
cameraLight_.transform = GetCamera()->transform;
simpleSceneRenderer->UpdateLightNodes({ &cameraLight_ });
}
/* Draw scene from editor camera view */
viewSceneRenderer->RenderSceneFromEditorView(*GetCamera(), config);
auto project = ProjectFolder::Active();
if (project)
{
auto sceneGraph = project->ActiveSceneGraph();
simpleSceneRenderer->RenderSceneFromCamera(sceneGraph, *GetCamera());
//boundingBoxSceneRenderer->RenderSceneFromCamera(sceneGraph, *GetCamera());//!!!
}
}
//TODO -> Optimize this function!!!
void EditorView::DrawSelectionHighlight()
{
const auto& selectedNodes = entitySelector->GetModel()->GetSelectedNodes();
if (!selectedNodes.empty())
{
std::vector<Scene::DynamicSceneNode*> selectedSceneNodes;
size_t i = 0;
for (auto node : selectedNodes)
{
auto entity = dynamic_cast<Entity*>(node);
entity->ForEachComponentWithSceneNode(
[&](Engine::Component* component, const Scene::DynamicSceneNodePtr& sceneNode)
{
selectedSceneNodes.push_back(sceneNode.get());
}
);
}
selectionSceneRenderer->RenderSelectionHighlights(selectedSceneNodes, *GetCamera());
}
}
void EditorView::DrawFrontMenu3D()
{
if (entitySelector->IsVisible())
DrawSelector();
DrawProjector();
}
void EditorView::DrawFrontMenu2D()
{
primitiveRenderer->BeginDrawing2D();
{
if (config.showProfiler)
DrawProfilerOutput(renderSystem->GetProfilerModel());
}
primitiveRenderer->EndDrawing2D();
}
void EditorView::DrawSelector()
{
auto renderContext = GetScreenFrame()->GetRenderContext();
/* Setup viewport for entity selector */
auto viewport = GetCamera()->projection.GetViewport();
{
viewport.minDepth = farPlaneProjector;
viewport.maxDepth = farPlaneSelector;
}
renderContext->SetupViewport(viewport);
/* Draw entity selector */
entitySelector->SetupView(*GetCamera());
entitySelector->DrawSelector();
}
void EditorView::DrawProjector()
{
/* Draw and update projector */
projector_->DrawAndUpdate();
}
void EditorView::DrawProfilerOutput(const Video::RendererProfilerModel& profilerModel)
{
Utility::RendererProfilerOutput::DrawInfo(
profilerModel,
engine->GetGlobalTimer(),
primitiveRenderer.get(),
defaultFont.get(),
StaticLayout::EditorViewLayout::profilerTextBorder
);
}
void EditorView::PickEntity(const Math::Point2i& mousePos)
{
static const float pickLength = 1000.0f;
/* Get picking ray by camera view */
auto pickingRay = GetCamera()->ViewRay(mousePos.Cast<float>());
/* Make intersection test with the physics world */
Physics::World::RayCastIntersection intersect;
if (physicsWorld->RayCast(pickingRay.ToLine(pickLength), intersect) && intersect.body && intersect.body->userData)
{
/* Select picked entity */
auto entity = reinterpret_cast<Entity*>(intersect.body->userData);
entitySelector->SelectWithModifier(entity);
}
else
entitySelector->SelectWithModifier(nullptr);
}
float EditorView::ViewMoveSpeed() const
{
auto projectorModel = projector_->GetModel();
if (projectorModel->GetProjection().GetOrtho())
{
static const float baseMoveSpeed = 0.003f;
auto size = projectorModel->GetProjection().GetOrthoSize().width;
return baseMoveSpeed * size;
}
return config.moveSpeed;
}
/*
* KeyboardEventHandler class
*/
EditorView::KeyboardEventHandler::KeyboardEventHandler(EditorView* view) :
view_{ view }
{
}
static void ChangeSelectorAlignmentOrMode(
const SelectorModel::TransformModes mode,
const SelectorModel::OrientationAlignments orientationAlignment,
const SelectorModel::PivotAlignments pivotAlignment)
{
if (IO::Keyboard::Instance()->KeyDown(IO::KeyCodes::KeyShift))
entitySelector->SetupOrientationAlignment(orientationAlignment);
else if (IO::Keyboard::Instance()->KeyDown(IO::KeyCodes::KeyControl))
entitySelector->SetupPivotAlignment(pivotAlignment);
else
entitySelector->SetupTransformMode(mode);
}
bool EditorView::KeyboardEventHandler::OnKeyDown(const IO::KeyCodes keyCode, const Platform::Frame* frame)
{
if (!view_->GetScreenFrame()->HasFocus())
return true;
auto& config = view_->config;
switch (keyCode)
{
case IO::KeyCodes::KeyF1:
{
config.showProfiler = !config.showProfiler;
}
break;
case IO::KeyCodes::KeyF3:
{
auto consoleFrame = MainFrame::Instance()->GetConsoleFrame();
consoleFrame->Show(!consoleFrame->IsShown());
}
break;
case IO::KeyCodes::KeyNumPad1:
case IO::KeyCodes::Key1:
{
ChangeSelectorAlignmentOrMode(
SelectorModel::TransformModes::Translate,
SelectorModel::OrientationAlignments::Global,
SelectorModel::PivotAlignments::MedianPoint
);
}
break;
case IO::KeyCodes::KeyNumPad2:
case IO::KeyCodes::Key2:
{
ChangeSelectorAlignmentOrMode(
SelectorModel::TransformModes::Rotate,
SelectorModel::OrientationAlignments::Local,
SelectorModel::PivotAlignments::IndividualOrigins
);
}
break;
case IO::KeyCodes::KeyNumPad3:
case IO::KeyCodes::Key3:
{
ChangeSelectorAlignmentOrMode(
SelectorModel::TransformModes::Scale,
SelectorModel::OrientationAlignments::View,
SelectorModel::PivotAlignments::ActiveElement
);
}
break;
case IO::KeyCodes::KeyNumPad4:
case IO::KeyCodes::Key4:
{
if (IO::Keyboard::Instance()->KeyDown(IO::KeyCodes::KeyControl))
entitySelector->SetupPivotAlignment(SelectorModel::PivotAlignments::BoundingBox);
}
break;
case IO::KeyCodes::KeyNumPad5:
case IO::KeyCodes::Key5:
{
if (IO::Keyboard::Instance()->KeyDown(IO::KeyCodes::KeyControl))
entitySelector->SetupPivotAlignment(SelectorModel::PivotAlignments::Minimum);
}
break;
case IO::KeyCodes::KeyNumPad6:
case IO::KeyCodes::Key6:
{
if (IO::Keyboard::Instance()->KeyDown(IO::KeyCodes::KeyControl))
entitySelector->SetupPivotAlignment(SelectorModel::PivotAlignments::Maximum);
}
break;
case IO::KeyCodes::KeyNumPad7:
case IO::KeyCodes::Key7:
{
if (IO::Keyboard::Instance()->KeyDown(IO::KeyCodes::KeyControl))
entitySelector->SetupPivotAlignment(SelectorModel::PivotAlignments::GlobalCursor);
}
break;
case IO::KeyCodes::KeyR:
{
entitySelector->SwitchRaster();
}
break;
case IO::KeyCodes::KeyDelete:
{
entitySelector->DeleteSelectedEntities();
}
break;
case IO::KeyCodes::KeyX:
{
if (IO::Keyboard::Instance()->KeyDown(IO::KeyCodes::KeyControl))
entitySelector->CutSelectedEntities();
}
break;
case IO::KeyCodes::KeyC:
{
if (IO::Keyboard::Instance()->KeyDown(IO::KeyCodes::KeyControl))
entitySelector->CopySelectedEntities();
}
break;
case IO::KeyCodes::KeyV:
{
if (IO::Keyboard::Instance()->KeyDown(IO::KeyCodes::KeyControl))
entitySelector->PasteSelectedEntities();
}
break;
default:
break;
}
return true;
}
/*
* MouseEventHandler class
*/
EditorView::MouseEventHandler::MouseEventHandler(EditorView* view) :
view_{ view }
{
}
bool EditorView::MouseEventHandler::OnButtonDown(const IO::MouseKeyCodes keyCode, const Platform::Frame* frame)
{
if (view_->IsFrameOwner(frame))
{
switch (keyCode)
{
case IO::MouseKeyCodes::MouseLeft:
/* Process picking only if no axis is selected */
if (entitySelector->GetModel()->GetSelectionState() == Utility::SelectorModel::SelectionStates::None)
view_->PickEntity(mousePos_);
break;
case IO::MouseKeyCodes::MouseRight:
lookMode_ = FreeLookModes::FreeLook;
LockFreeLook();
break;
case IO::MouseKeyCodes::MouseMiddle:
lookMode_ = FreeLookModes::MoveXY;
LockFreeLook();
break;
}
}
return true;
}
bool EditorView::MouseEventHandler::OnButtonDoubleClicked(const IO::MouseKeyCodes keyCode, const Platform::Frame* frame)
{
return OnButtonDown(keyCode, frame);
}
bool EditorView::MouseEventHandler::OnButtonUp(const IO::MouseKeyCodes keyCode, const Platform::Frame* frame)
{
if (view_->IsFrameOwner(frame))
{
switch (keyCode)
{
case IO::MouseKeyCodes::MouseMiddle:
case IO::MouseKeyCodes::MouseRight:
UnlockFreeLook();
break;
}
}
return true;
}
bool EditorView::MouseEventHandler::OnWheelMotion(int motion, const Platform::Frame* frame)
{
if (view_->IsFrameOwner(frame))
view_->ZoomView(static_cast<float>(-motion) * 0.1f);
return true;
}
bool EditorView::MouseEventHandler::OnLocalMotion(const Math::Point2i& position, const Platform::Frame* frame)
{
mousePos_ = position;
return true;
}
bool EditorView::MouseEventHandler::OnGlobalMotion(const Math::Vector2i& motion)
{
if (IsFreeLook())
{
switch (lookMode_)
{
case FreeLookModes::FreeLook:
{
view_->cameraCtrl_.ProcessRotation(
view_->GetCamera(), motion.Cast<float>() * (Math::deg2rad * 0.5f)
);
}
break;
case FreeLookModes::MoveXY:
{
const auto motionDir = motion.Cast<float>();
view_->MoveView({ motionDir.x, -motionDir.y, 0 });
}
break;
}
}
return true;
}
} // /namespace Editor
} // /namespace Fork
// ======================== |
5671ecdb6e4e5afa08ee3986ac70b8ce56ce6fda | d7674f20a362b0cad8ffb7782785bf21a69c9fd2 | /01_OLD/another_test/include/another_test/another_test.h | 9578deddf656f06c9b00cfd7ce7b2baea478b738 | [] | no_license | linjuk/adda_ros_multiple_cars | 9f7bef20ab1490a90502464cd146b8e33476e12d | 694191bf0377da8589abee773798cce4d7fbc1f4 | refs/heads/master | 2022-12-07T03:16:23.429104 | 2019-07-06T15:18:46 | 2019-07-06T15:18:46 | 145,716,743 | 0 | 1 | null | 2022-11-22T01:06:42 | 2018-08-22T13:58:32 | Python | UTF-8 | C++ | false | false | 954 | h | another_test.h | #ifndef another_test_H
#define another_test_H
#include <ros/ros.h>
#include <std_msgs/Bool.h>
//include <actionlib/client/simple_action_client.h>
namespace another_test{
//typedef actionlib::SimpleActionClient<bla_msgs::GoToAction> BlaActionClient;
class ClassName {
public:
ClassName(ros::NodeHandle& nh, ros::NodeHandle& private_nh );
virtual ~ClassName();
protected:
void boolCallback(const std_msgs::Bool &Bool_msg);
//void goToCmdActiveCB();
//void goToCmdFeedbackCB(const ias_robcom_msgs::GoToFeedbackConstPtr& feedback);
//void goToCmdDoneCb(const actionlib::SimpleClientGoalState& state,
//const ias_robcom_msgs::GoToResultConstPtr& result);
ros::NodeHandle& nh;
ros::NodeHandle& p_nh;
private:
ros::Publisher pub_; // uncommented this for TRYING 3
ros::Subscriber sub_;
//BlaActionClient* bla_action_client;
};
} // end of namespace another_test
#endif // another_test_H
|
0bce34bc96a6d14c5ee7a54eafdac232a779fef3 | d559527977731e9990ab909e77592348e89b96ab | /inc/string.h | 5139943c0df49b62d01a323a1577f7c16d4c3955 | [
"MIT"
] | permissive | Southeastern-Policy-Institute/ionia | f1c92c4b413a55558cade5039d5cecd18434b45e | 46adbe66104acf1f78d85b561977f05e2d00ea73 | refs/heads/main | 2023-07-05T22:05:54.537872 | 2023-06-29T05:53:00 | 2023-06-29T05:53:00 | 315,117,242 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,113 | h | string.h | /* STRING.H - Standard C Library Functions and Declarations
* Southeastern Policy Institute, 2023
*/
# ifndef _STRING_H_
# define _STRING_H_
# if !defined(NULL) && defined(__cplusplus)
# define NULL nullptr
# elif !defined(NULL) && !defined(__cplusplus)
# define NULL (void*)0U
# endif /* NULL */
# ifdef __cplusplus
namespace std {
extern "C" {
# endif /* __cplusplus */
// Size type
typedef __SIZE_TYPE__ size_t;
// Copies a block of memory
__attribute__ ((nonnull, returns_nonnull, nothrow))
void* memcpy (void*, const void*, size_t);
// Copies a block of memory by way of an intermediate buffer
__attribute__ ((nonnull, returns_nonnull, nothrow))
void* memmove (void*, const void*, size_t);
// Copies a string
__attribute__ ((nonnull, returns_nonnull, nothrow))
char* strcpy (char*, const char*);
// Copies a number of characters from a string
__attribute__ ((nonnull, returns_nonnull, nothrow))
char* strncpy (char*, const char*, size_t);
// Appends one string to the end of another
__attribute__ ((nonnull, returns_nonnull, nothrow))
char* strcat (char*, const char*);
// Appends a number of characters from one string to another
__attribute__ ((nonnull, returns_nonnull, nothrow))
char* strncat (char*, const char*, size_t);
// Determines the length of a string
__attribute__ ((nonnull, nothrow))
size_t strlen (const char*);
// Searches for the first occurrence of a character in a string
__attribute__ ((nonnull, returns_nonnull, nothrow))
char* strchr (const char*, int);
// Compare two strings
__attribute__ ((nonnull, nothrow))
int strcmp (const char*, const char*);
// Compares at most the first n bytes of two strings
__attribute__ ((nonnull, nothrow))
int strncmp (const char*, const char*, size_t);
// Searches a haystack for a needle
__attribute__ ((nonnull, returns_nonnull, nothrow))
char* strstr (const char*, const char*);
# ifdef __cplusplus
};
};
# endif /* __cplusplus */
# endif /* _STRING_H_ */
|
9cb9e0b64e10d34ab0f8e15a7ecaf89d97af1b54 | e926bede54cbddf08870036ae478124e0a6cec77 | /src/tests/unit_tests/bounding_box3_tests.cpp | e237ecf0828521e1a48523062a31120e6e6b8e64 | [
"MIT"
] | permissive | doyubkim/fluid-engine-dev | 2d1228c78690191fba8ff2c107af1dd06212ca44 | 94c300ff5ad8a2f588e5e27e8e9746a424b29863 | refs/heads/main | 2023-08-14T08:04:43.513360 | 2022-07-09T06:24:41 | 2022-07-09T06:24:41 | 58,299,041 | 1,725 | 275 | MIT | 2022-07-09T06:24:41 | 2016-05-08T06:05:38 | C++ | UTF-8 | C++ | false | false | 8,732 | cpp | bounding_box3_tests.cpp | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <unit_tests_utils.h>
#include <jet/bounding_box3.h>
using namespace jet;
TEST(BoundingBox3, Constructors) {
{
BoundingBox3D box;
EXPECT_DOUBLE_EQ(kMaxD, box.lowerCorner.x);
EXPECT_DOUBLE_EQ(kMaxD, box.lowerCorner.y);
EXPECT_DOUBLE_EQ(kMaxD, box.lowerCorner.z);
EXPECT_DOUBLE_EQ(-kMaxD, box.upperCorner.x);
EXPECT_DOUBLE_EQ(-kMaxD, box.upperCorner.y);
EXPECT_DOUBLE_EQ(-kMaxD, box.upperCorner.z);
}
{
BoundingBox3D box(Vector3D(-2.0, 3.0, 5.0), Vector3D(4.0, -2.0, 1.0));
EXPECT_DOUBLE_EQ(-2.0, box.lowerCorner.x);
EXPECT_DOUBLE_EQ(-2.0, box.lowerCorner.y);
EXPECT_DOUBLE_EQ(1.0, box.lowerCorner.z);
EXPECT_DOUBLE_EQ(4.0, box.upperCorner.x);
EXPECT_DOUBLE_EQ(3.0, box.upperCorner.y);
EXPECT_DOUBLE_EQ(5.0, box.upperCorner.z);
}
{
BoundingBox3D box(Vector3D(-2.0, 3.0, 5.0), Vector3D(4.0, -2.0, 1.0));
BoundingBox3D box2(box);
EXPECT_DOUBLE_EQ(-2.0, box2.lowerCorner.x);
EXPECT_DOUBLE_EQ(-2.0, box2.lowerCorner.y);
EXPECT_DOUBLE_EQ(1.0, box2.lowerCorner.z);
EXPECT_DOUBLE_EQ(4.0, box2.upperCorner.x);
EXPECT_DOUBLE_EQ(3.0, box2.upperCorner.y);
EXPECT_DOUBLE_EQ(5.0, box2.upperCorner.z);
}
}
TEST(BoundingBox3, BasicGetters) {
BoundingBox3D box(Vector3D(-2.0, 3.0, 5.0), Vector3D(4.0, -2.0, 1.0));
EXPECT_DOUBLE_EQ(6.0, box.width());
EXPECT_DOUBLE_EQ(5.0, box.height());
EXPECT_DOUBLE_EQ(4.0, box.depth());
EXPECT_DOUBLE_EQ(6.0, box.length(0));
EXPECT_DOUBLE_EQ(5.0, box.length(1));
EXPECT_DOUBLE_EQ(4.0, box.length(2));
}
TEST(BoundingBox3, Overlaps) {
// x-axis is not overlapping
{
BoundingBox3D box1(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
BoundingBox3D box2(Vector3D(5.0, 1.0, 3.0), Vector3D(8.0, 2.0, 4.0));
EXPECT_FALSE(box1.overlaps(box2));
}
// y-axis is not overlapping
{
BoundingBox3D box1(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
BoundingBox3D box2(Vector3D(3.0, 4.0, 3.0), Vector3D(8.0, 6.0, 4.0));
EXPECT_FALSE(box1.overlaps(box2));
}
// z-axis is not overlapping
{
BoundingBox3D box1(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
BoundingBox3D box2(Vector3D(3.0, 1.0, 6.0), Vector3D(8.0, 2.0, 9.0));
EXPECT_FALSE(box1.overlaps(box2));
}
// overlapping
{
BoundingBox3D box1(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
BoundingBox3D box2(Vector3D(3.0, 1.0, 3.0), Vector3D(8.0, 2.0, 7.0));
EXPECT_TRUE(box1.overlaps(box2));
}
}
TEST(BoundingBox3, Contains) {
// Not containing (x-axis is out)
{
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
Vector3D point(-3.0, 0.0, 4.0);
EXPECT_FALSE(box.contains(point));
}
// Not containing (y-axis is out)
{
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
Vector3D point(2.0, 3.5, 4.0);
EXPECT_FALSE(box.contains(point));
}
// Not containing (z-axis is out)
{
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
Vector3D point(2.0, 0.0, 0.0);
EXPECT_FALSE(box.contains(point));
}
// Containing
{
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
Vector3D point(2.0, 0.0, 4.0);
EXPECT_TRUE(box.contains(point));
}
}
TEST(BoundingBox3, Intersects) {
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
Ray3D ray1(Vector3D(-3, 0, 2), Vector3D(2, 1, 1).normalized());
EXPECT_TRUE(box.intersects(ray1));
Ray3D ray2(Vector3D(3, -1, 3), Vector3D(-1, 2, -3).normalized());
EXPECT_TRUE(box.intersects(ray2));
Ray3D ray3(Vector3D(1, -5, 1), Vector3D(2, 1, 2).normalized());
EXPECT_FALSE(box.intersects(ray3));
}
TEST(BoundingBox3, ClosestIntersection) {
BoundingBox3D box(Vector3D(-2.0, -2.0, -1.0), Vector3D(1.0, 0.0, 1.0));
Ray3D ray1(Vector3D(-4, -3, 0), Vector3D(1, 1, 0).normalized());
BoundingBoxRayIntersection3D intersection1 = box.closestIntersection(ray1);
EXPECT_TRUE(intersection1.isIntersecting);
EXPECT_DOUBLE_EQ(Vector3D(2, 2, 0).length(), intersection1.tNear);
EXPECT_DOUBLE_EQ(Vector3D(3, 3, 0).length(), intersection1.tFar);
Ray3D ray2(Vector3D(0, -1, 0), Vector3D(-2, 1, 1).normalized());
BoundingBoxRayIntersection3D intersection2 = box.closestIntersection(ray2);
EXPECT_TRUE(intersection2.isIntersecting);
EXPECT_DOUBLE_EQ(Vector3D(2, 1, 1).length(), intersection2.tNear);
}
TEST(BoundingBox3, MidPoint) {
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
Vector3D midPoint = box.midPoint();
EXPECT_DOUBLE_EQ(1.0, midPoint.x);
EXPECT_DOUBLE_EQ(0.5, midPoint.y);
EXPECT_DOUBLE_EQ(3.0, midPoint.z);
}
TEST(BoundingBox3, DiagonalLength) {
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
double diagLen = box.diagonalLength();
EXPECT_DOUBLE_EQ(std::sqrt(6.0 * 6.0 + 5.0 * 5.0 + 4.0 * 4.0), diagLen);
}
TEST(BoundingBox3, DiagonalLengthSquared) {
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
double diagLenSqr = box.diagonalLengthSquared();
EXPECT_DOUBLE_EQ(6.0 * 6.0 + 5.0 * 5.0 + 4.0 * 4.0, diagLenSqr);
}
TEST(BoundingBox3, Reset) {
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
box.reset();
static const double maxDouble = std::numeric_limits<double>::max();
EXPECT_DOUBLE_EQ(maxDouble, box.lowerCorner.x);
EXPECT_DOUBLE_EQ(maxDouble, box.lowerCorner.y);
EXPECT_DOUBLE_EQ(maxDouble, box.lowerCorner.z);
EXPECT_DOUBLE_EQ(-maxDouble, box.upperCorner.x);
EXPECT_DOUBLE_EQ(-maxDouble, box.upperCorner.y);
EXPECT_DOUBLE_EQ(-maxDouble, box.upperCorner.z);
}
TEST(BoundingBox3, Merge) {
// Merge with point
{
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
Vector3D point(5.0, 1.0, -1.0);
box.merge(point);
EXPECT_DOUBLE_EQ(-2.0, box.lowerCorner.x);
EXPECT_DOUBLE_EQ(-2.0, box.lowerCorner.y);
EXPECT_DOUBLE_EQ(-1.0, box.lowerCorner.z);
EXPECT_DOUBLE_EQ(5.0, box.upperCorner.x);
EXPECT_DOUBLE_EQ(3.0, box.upperCorner.y);
EXPECT_DOUBLE_EQ(5.0, box.upperCorner.z);
}
// Merge with other box
{
BoundingBox3D box1(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
BoundingBox3D box2(Vector3D(3.0, 1.0, 3.0), Vector3D(8.0, 2.0, 7.0));
box1.merge(box2);
EXPECT_DOUBLE_EQ(-2.0, box1.lowerCorner.x);
EXPECT_DOUBLE_EQ(-2.0, box1.lowerCorner.y);
EXPECT_DOUBLE_EQ(1.0, box1.lowerCorner.z);
EXPECT_DOUBLE_EQ(8.0, box1.upperCorner.x);
EXPECT_DOUBLE_EQ(3.0, box1.upperCorner.y);
EXPECT_DOUBLE_EQ(7.0, box1.upperCorner.z);
}
}
TEST(BoundingBox3, Expand) {
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
box.expand(3.0);
EXPECT_DOUBLE_EQ(-5.0, box.lowerCorner.x);
EXPECT_DOUBLE_EQ(-5.0, box.lowerCorner.y);
EXPECT_DOUBLE_EQ(-2.0, box.lowerCorner.z);
EXPECT_DOUBLE_EQ(7.0, box.upperCorner.x);
EXPECT_DOUBLE_EQ(6.0, box.upperCorner.y);
EXPECT_DOUBLE_EQ(8.0, box.upperCorner.z);
}
TEST(BoundingBox3, Corner) {
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
EXPECT_VECTOR3_EQ(Vector3D(-2.0, -2.0, 1.0), box.corner(0));
EXPECT_VECTOR3_EQ(Vector3D(4.0, -2.0, 1.0), box.corner(1));
EXPECT_VECTOR3_EQ(Vector3D(-2.0, 3.0, 1.0), box.corner(2));
EXPECT_VECTOR3_EQ(Vector3D(4.0, 3.0, 1.0), box.corner(3));
EXPECT_VECTOR3_EQ(Vector3D(-2.0, -2.0, 5.0), box.corner(4));
EXPECT_VECTOR3_EQ(Vector3D(4.0, -2.0, 5.0), box.corner(5));
EXPECT_VECTOR3_EQ(Vector3D(-2.0, 3.0, 5.0), box.corner(6));
EXPECT_VECTOR3_EQ(Vector3D(4.0, 3.0, 5.0), box.corner(7));
}
TEST(BoundingBox3D, IsEmpty) {
BoundingBox3D box(Vector3D(-2.0, -2.0, 1.0), Vector3D(4.0, 3.0, 5.0));
EXPECT_FALSE(box.isEmpty());
box.lowerCorner = Vector3D(5.0, 1.0, 3.0);
EXPECT_TRUE(box.isEmpty());
box.lowerCorner = Vector3D(2.0, 4.0, 3.0);
EXPECT_TRUE(box.isEmpty());
box.lowerCorner = Vector3D(2.0, 1.0, 6.0);
EXPECT_TRUE(box.isEmpty());
box.lowerCorner = Vector3D(4.0, 1.0, 3.0);
EXPECT_TRUE(box.isEmpty());
}
|
37803811301947c94496fb789a31037c868b606e | 67487d255d6d26bb93d486b14d8bf33a85ef61a2 | /cpsc585/cpsc585/LaserBeam.h | 37e8282fda2015057aa9e9d1027e3ea1176536bd | [] | no_license | ryosaku8/CPSC-585-Game-Project | aec2c5a1e70688ce8e4dc1f7ca5eee27ae1be2ad | 2711d94c4e51a9d7dff3229b3da27d53bb7d720a | refs/heads/master | 2021-05-26T20:10:20.182220 | 2012-04-16T18:50:22 | 2012-04-16T18:50:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | h | LaserBeam.h | #pragma once
#include "Mesh.h"
class LaserBeam
{
public:
LaserBeam(D3DXVECTOR3 startPoint, D3DXVECTOR3 endPoint);
~LaserBeam();
void writeVertices(Vertex* vertexList);
void update(float seconds);
bool destroyed;
static float vanishingSpeed;
private:
D3DXVECTOR3 start;
D3DXVECTOR3 end;
static float halfThickness;
float beamLength;
float timeUntilFinished;
float currentTime;
};
|
30a97d7d0309e0b3992cc25265ff2c82fd0e59a3 | 66f57f944e93ee7c61edb2b3dc5f346bac502d3a | /CH.5 Entry3_Math/3_4 Primes/B1007.cpp | cbcf086ce07d82a3158691da4f4179968cc63012 | [] | no_license | Preburnism/PAT | 5fa4ace51643b0ed075d4f64443d32279a6ceb44 | 9cde9c7b9805d328699156169b3151276c9aef2c | refs/heads/master | 2022-11-11T22:48:39.741823 | 2022-10-23T10:38:29 | 2022-10-23T10:38:29 | 143,695,292 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | cpp | B1007.cpp | #include <cstdio>
#include <cmath>
bool isPrime(int n)
{
int sqr = sqrt(n * 1.0);
for (int i = 2; i <= sqr; i++)
{
if (n % i == 0)
return false;
}
return true;
}
int main()
{
int n;
scanf("%d", &n);
int count = 0;
for (int i = 3; i <= n - 2; i += 2)
{
if (isPrime(i) && isPrime(i + 2))
count++;
}
printf("%d", count);
return 0;
} |
8593091a8ebd31854f84ce687dcfaa692bbd7227 | b4ede0ffe374e783c34a234198bb11f31e2499e2 | /Source/MainMenuScene.cpp | b910d9d17249256908f7581ada8277ee4f989c60 | [] | no_license | S3lfik/ccs2dx_smpl | a787af88a0031ede03b93e39cd14dcc7ca5090b8 | ccb434bb7ee404abafe15901214f5e32107f2733 | refs/heads/master | 2021-01-10T16:16:03.791798 | 2015-11-18T13:40:23 | 2015-11-18T13:40:23 | 46,106,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,722 | cpp | MainMenuScene.cpp | #include "MainMenuScene.h"
#include "GameScene.h"
#include "SimpleAudioEngine.h"
#include <iostream>
MainMenuLayer::~MainMenuLayer()
{
}
CCScene* MainMenuLayer::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
MainMenuLayer *layer = MainMenuLayer::create();
// Add layer as a child to scene
scene->addChild(layer);
// Return the scene
return scene;
}
// on "init" you need to initialize your instance
bool MainMenuLayer::init()
{
if (!CCLayer::init())
return false;
// Create main loop
this->schedule(schedule_selector(MainMenuLayer::update));
this->setTouchEnabled(true);
this->setAccelerometerEnabled(true);
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
//CCSprite* sprite = CCSprite::create("./textures/Bg.png");
CCSprite* sprite = CCSprite::create("Bg.png");
sprite->setPosition(CCPoint(visibleSize.width / 2, visibleSize.height / 2));
this->addChild(sprite, -1);
CCMenuItemImage* menuItem = CCMenuItemImage::create("./textures/UI_play.png", "./textures/UI_play.png", this, menu_selector(MainMenuLayer::goToGameScene));
menuItem->setPosition(visibleSize.width / 2, visibleSize.height / 2);
CCMenu* menu = CCMenu::create(menuItem, NULL);
menu->setPosition(CCPointZero);
this->addChild(menu);
return true;
}
void MainMenuLayer::draw()
{
}
void MainMenuLayer::update(float dt)
{
}
void MainMenuLayer::goToGameScene(CCObject* sender)
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("audio/pop.wav", false);
CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(1.f, GameScene::scene()));
} |
7a88f00bf4ef229fa79f1ad76fee7c100f491001 | 2f4b60f961945496f91c1a8c81f28ebf07467cfc | /src/parallel_jacobi.h | 5a807c7ac9b8c95a8363cbd9562ce763dc0b46e6 | [] | no_license | simonhorlick/parallel-jacobi | 33277c767525b423cb76e9a69e5ab987acd40e76 | 9b9dbb41d0c67cb243bcf0053d8219f69adb41a7 | refs/heads/master | 2016-09-05T23:52:34.887849 | 2010-04-17T10:30:54 | 2010-04-17T10:30:54 | 32,095,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,385 | h | parallel_jacobi.h | #pragma once
#include <vector>
#include <limits>
#include <cmath>
#ifdef enable_openmp
#include <omp.h>
#endif
#include "matrix.h"
#include "timer.h"
namespace parallel_jacobi
{
//==========================================================================
// Computes the minimum and maximum of two elements of arbitrary types
//==========================================================================
template<typename T>
inline void minmax(T a, T b, T& min, T& max) {
if(a > b) {
max=a;
min=b;
} else {
min=a;
max=b;
}
}
//==========================================================================
// Functions to determine convergence
//==========================================================================
class converge_off_threshold {
const double t;
double tlast;
public:
// eps = tol*||A||_F
converge_off_threshold(const double tolerance, const matrix& mat)
: t(tolerance * frobenius_norm(mat)) { }
bool not_converged(matrix& mat) {
tlast = off_diagonal_magnitude(mat);
return tlast > t;
}
void print() {
std::cout << "threshold " << tlast << "/" << t << "\n";
}
};
class converge_max_iterations {
int i;
const int imax;
public:
converge_max_iterations(const int iterations)
: imax(iterations), i(0) { }
bool not_converged(matrix& mat) {
return ++i < imax;
}
void print() {
std::cout << "iteration " << i << "/" << imax << ".\n";
}
};
class converge_off_difference {
double lastnorm;
double lastnorm2;
const double t;
public:
converge_off_difference(const double tolerance)
: t(tolerance)
, lastnorm(std::numeric_limits<double>::max()) { }
bool not_converged(matrix& mat) {
double o = off_diagonal_magnitude(mat);
if((lastnorm-o)<t)
return false;
lastnorm2=lastnorm;
lastnorm=o;
return true;
}
void print() {
std::cout << "off-diagonal difference " << (lastnorm2-lastnorm) << "/" << t << ".\n";
}
};
class music_permutation {
std::vector<int> top, bot;
const int n;
public:
music_permutation(int n) : n(n) {
const int m=n/2;
top.resize(m);
bot.resize(m);
for(int i=0; i<m; ++i) {
top[i]=2*i;
bot[i]=2*i+1;
}
}
inline void get(int k, int& p, int& q) {
minmax(top[k],bot[k],p,q);
}
void permute() {
// no permutation possible for 2x2 matrix
if(n == 2) return;
int m=n/2;
// Store end element to move down after bottom row is shifted.
int e=top[m-1];
// Cycle top elements right and bottom elements left, being careful
// not to overwrite anthing important.
top[0]=bot[0];
for(int k=0,l=m-1; k<m-1; ++k,--l) {
bot[k]=bot[k+1];
top[l]=top[l-1];
}
// Move stored end element down to bot.
bot[m-1]=e;
// Fix first top value.
top[0]=0;
}
};
//==========================================================================
// Symmetric Schur decomposition
// Source: Algorithm 8.4.1 from Golub/Van Loan p.428
//==========================================================================
template<typename T>
void symmetric_schur_new(const matrix& A, const unsigned int p,
const unsigned int q, T& c, T& s)
{
const T epsilon = 1e-6;
if(fabs(A(p,q)) > epsilon)
{
T tau = (A(q,q) - A(p,p)) / (2.0 * A(p,q));
T t;
if(tau >= 0) t = 1.0 / (tau + sqrt(1.0 + tau*tau));
else t = -1.0 / (-tau + sqrt(1.0 + tau*tau));
c = 1.0 / sqrt(1.0 + t*t);
s = t*c;
}
else
{
c = 1.0;
s = 0.0;
}
}
//==========================================================================
// Pre-multiply Jacobi rotation matrix
//==========================================================================
template<typename T>
inline void premultiply(matrix& mat, const int p, const int q, const T c,
const T s)
{
typedef matrix::value_type value_type;
const int n=mat.size();
value_type *rowp=mat.get_row(p),
*rowq=mat.get_row(q);
for(int i=0; i<n; ++i,++rowp,++rowq)
{
const value_type mpi=*rowp,
mqi=*rowq;
*rowp = c*mpi + -s*mqi;
*rowq = s*mpi + c*mqi;
}
}
//==========================================================================
// Post-multiply Jacobi rotation matrix
//==========================================================================
template<typename T>
inline void postmultiply(matrix& mat, const int p, const int q, const T c,
const T s)
{
typedef matrix::value_type value_type;
for(int i=0; i<mat.size(); ++i)
{
const value_type mip=mat(i,p),
miq=mat(i,q);
mat(i,p) = c*mip + -s*miq;
mat(i,q) = s*mip + c*miq;
}
}
//==========================================================================
// Run the parallel jacobi algorithm
// mat - the matrix to operate on
// sc - a class with a function not_converged(mat) to determine when to stop
// the algorithm.
//==========================================================================
template<class StoppingCriterion, class Permutation>
void run(matrix& mat, StoppingCriterion& sc, Permutation& pe, timer& root)
{
typedef matrix::value_type value_type;
const int n=mat.size();
const int m=n/2;
// Store sine-cosine pairs as recalculating them for post-multiplication
// gives different values causing the algorithm to fail.
value_type* si = new value_type[m];
value_type* co = new value_type[m];
// Set up timers.
timer* convergence = new timer("convergence");
timer* permute = new timer("permute");
timer* premult = new timer("pre-multiplication");
timer* postmult = new timer("post-multiplication");
root.add(convergence);
root.add(premult);
root.add(postmult);
root.add(permute);
const bool isodd = (n > mat.actual_size());
bool not_converged = true;
root.start();
while(not_converged) {
// Do n sets of non-conflicting rotations.
for(int set=0; set<n; ++set) {
//std::cout << "set: " << set << "\n";
premult->start();
// Pre-multiply mat with each of the non-conflicting Jacobi
// rotation matrices in the set concurrently.
#ifdef enable_openmp
#pragma omp parallel for default(none) shared(mat, n, si, co, pe, isodd)
#endif
for(int k=0; k<m; ++k) {
int p,q;
pe.get(k,p,q);
// Skip this transformation if it is on the padding row of
// an odd sized matrix.
if(isodd && (p==n || q==n)) continue;
symmetric_schur_new(mat, p, q, co[k], si[k]);
premultiply(mat, p, q, co[k], si[k]);
}
premult->end();
postmult->start();
// Similarly, post-multiply mat with each of the non-conflicting
// Jacobi rotation matrices in the set concurrently.
#ifdef enable_openmp
#pragma omp parallel for default(none) shared(mat, n, si, co, pe, isodd)
#endif
for(int k=0; k<m; ++k) {
int p,q;
pe.get(k,p,q);
// Skip this transformation if it is on the padding row of
// an odd sized matrix.
if(isodd && (p==n || q==n)) continue;
postmultiply(mat,p,q,co[k],si[k]);
}
postmult->end();
// Calculate the next set of non-conflicting rotations.
permute->start();
pe.permute();
permute->end();
}
convergence->start();
not_converged = sc.not_converged(mat);
convergence->end();
// Print how near stopping condition is to being satisfied.
sc.print();
}
root.end();
delete[] si;
delete[] co;
}
}
|
2edfcb3878bf609bccdef93bc08436f6e1677be2 | bc0a4dc5bfca4718b348d4a1d872d5ff7205f927 | /USBCA/CA_ViewER/src/demo_control.cpp | 345defb963f098f437fe1c4c22a1d7eecda6ed8b | [] | no_license | adas-eye/CA378-AOIS_USB3-IFB | cdf190d4cfec9632178cbdadebbfcaef1052aad3 | 26b40a49b554db0567a6c468044fa7b6896af02b | refs/heads/master | 2022-02-25T03:20:09.349914 | 2019-10-01T09:40:54 | 2019-10-01T09:40:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,588 | cpp | demo_control.cpp | /*
Copyright (c) 2017-2019, CenturyArks
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
#include "stdafx.h"
#include "USBCAExtensionUnit.h"
#include "demo_control.h"
#include "capture.h"
#include "af_control.h"
#include "tool.hpp"
#include "mode.h"
using namespace cv;
using std::cout; using std::cerr; using std::endl;
/***************************************************************
* Defines for Demo Control
**************************************************************/
#define SETTING_FILENAME "CA_ViewER.ini"
/***************************************************************
* Global variable for Demo Control
**************************************************************/
CUSBCAExtensionUnit* g_pExpUnit = NULL; // USBCA Extension Unit DLL
/*******************************************************************************
* @brief Initialize Demo software
*
* @param param Parameters
*
* @return 0 Success, other Failure
******************************************************************************/
int DemoInit(ST_PARAM* param)
{
int ret;
uint8_t enable, table_number;
uint16_t value, r_value, g_value, b_value;
ReadSettingFile(SETTING_FILENAME, param);
param->select_mode = CheckSelectMode(param->select_mode);
SetSelectMode(param->select_mode);
// Load USBCA Extension Unit DLL
if (g_pExpUnit == NULL)
{
if (param->usb_connected)
{
g_pExpUnit = new CUSBCAExtensionUnit();
}
}
if (g_pExpUnit)
{
// Exposure
ret = g_pExpUnit->CA378_GetExposure(&value);
if (ret == 0)
{
param->exposure = value;
}
// Analog Gain
ret = g_pExpUnit->CA378_GetAnalogGain(&value);
if (ret == 0)
{
param->analog_gain = value / 256.0;
}
// White Balance
ret = g_pExpUnit->CA378_GetWhiteBalance(&r_value, &g_value, &b_value);
if (ret == 0)
{
param->white_balance_r = r_value / 256.0;
param->white_balance_g = g_value / 256.0;
param->white_balance_b = b_value / 256.0;
}
// Black Level
ret = g_pExpUnit->CA378_GetBlackLevel(&enable, &value);
if (ret == 0)
{
param->enable_black_level = (bool)enable;
param->black_level = value;
}
// Lens Shading Correction
ret = g_pExpUnit->CA378_GetLensShading(&table_number);
if (ret == 0)
{
switch (table_number)
{
case 1:
param->enable_lsc = true;
param->lsc_table_number = 1;
break;
case 2:
param->enable_lsc = true;
param->lsc_table_number = 2;
break;
case 3:
param->enable_lsc = true;
param->lsc_table_number = 3;
break;
default:
param->enable_lsc = false;
break;
}
}
// Defect Pixel
ret = g_pExpUnit->CA378_GetDefectPixel(&enable);
if (ret == 0)
{
switch (enable)
{
case 1:
param->defect_pixel_mapped = true;
param->defect_pixel_dynamic = false;
break;
case 2:
param->defect_pixel_mapped = false;
param->defect_pixel_dynamic = true;
break;
case 3:
param->defect_pixel_mapped = true;
param->defect_pixel_dynamic = true;
break;
default:
param->defect_pixel_mapped = false;
param->defect_pixel_dynamic = false;
break;
}
}
#ifdef CA378_AOIS
// Focus Position
switch (param->focus_mode)
{
case FOCUS_MODE_DIRECT:
param->focus_position = param->manual_focus_position;
break;
case FOCUS_MODE_INFINITY:
param->focus_position = 0;
break;
case FOCUS_MODE_MACRO:
param->focus_position = 1024;
break;
default:
break;
}
DemoControl(param, CMD_MANUAL_FOCUS);
// OIS Mode
uint8_t mode;
ret = g_pExpUnit->CA378_GetOISMode(&mode);
if (ret == 0)
{
param->ois_mode = mode;
}
#endif
}
return 0;
}
/*******************************************************************************
* @brief Exit Demo software
*
* @param param Parameters
*
* @return 0 Success, other Failure
******************************************************************************/
int DemoExit(ST_PARAM* param)
{
// Stop Capture
StopCapture();
WriteSettingFile(SETTING_FILENAME, param);
// Free USBCA Extension Unit DLL
if (g_pExpUnit)
{
delete g_pExpUnit;
}
return 0;
}
/*******************************************************************************
* @brief Control Demo software
*
* @param param Parameters
* @param cmd Command
*
* @return 0 Success, other Failure
******************************************************************************/
int DemoControl(ST_PARAM* param, E_DEMO_CMD cmd)
{
if (!param->usb_connected)
{
return -1;
}
int ret = 0;
switch (cmd)
{
case CMD_SELECT_MODE: // Select Mode
{
StopCapture();
SetSelectMode(param->select_mode);
EnableGamma(param->enable_gamma);
if (param->enable_gamma)
{
if (param->enable_srgb_gamma)
{
UpdateSRGBGammaTable();
}
else
{
UpdateGammaTable(param->gamma_value);
}
}
EnableCCM(param->enable_ccm);
if (param->enable_ccm)
{
UpdateCCMTable(param->ccm);
}
EnableContrast(param->enable_contrast, param->contrast_value);
StartCapture();
}
break;
case CMD_EXPOSURE: // Exposure
{
uint16_t value;
value = param->exposure;
ret = g_pExpUnit->CA378_SetExposure(value);
cout <<
format("CA378_SetExposure: value = %d, ret = %X", value, ret)
<< endl;
}
break;
case CMD_ANALOG_GAIN: // Analog Gain
{
uint16_t value;
value = (uint16_t)(param->analog_gain * 0x100 + 0.5);
ret = g_pExpUnit->CA378_SetAnalogGain(value);
cout <<
format("CA378_SetAnalogGain: value = %.3lf (0x%04X), ret = %X", value / 256.0, value, ret)
<< endl;
}
break;
case CMD_WHITE_BALANCE: // White Balance
{
uint16_t r_value, g_value, b_value;
r_value = (uint16_t)(param->white_balance_r * 0x100 + 0.5);
g_value = (uint16_t)(param->white_balance_g * 0x100 + 0.5);
b_value = (uint16_t)(param->white_balance_b * 0x100 + 0.5);
ret = g_pExpUnit->CA378_SetWhiteBalance(r_value, g_value, b_value);
cout <<
format("CA378_SetWhiteBalance: R = %.3lf (0x%04X), G = %.3lf (0x%04X), B = %.3lf (0x%04X), ret = %X",
r_value / 256.0, r_value, g_value / 256.0, g_value, b_value / 256.0, b_value, ret)
<< endl;
}
break;
case CMD_BLACK_LEVEL: // Black Level
{
uint8_t enable;
uint16_t value;
enable = param->enable_black_level;
value = param->black_level;
ret = g_pExpUnit->CA378_SetBlackLevel(enable, value);
cout <<
format("CA378_SetBlackLevel: enable = %d, value = %d, ret = %X", enable, value, ret)
<< endl;
}
break;
case CMD_LSC: // LSC(Lens Shading Correction)
{
uint8_t table_number;
if (param->enable_lsc)
{
table_number = param->lsc_table_number;
}
else
{
table_number = 0;
}
ret = g_pExpUnit->CA378_SetLensShading(table_number);
cout <<
format("CA378_SetLensShading: table_number = %d, ret = %X", table_number, ret)
<< endl;
}
break;
case CMD_DEFECT_PIXEL: // Defect Pixel
{
uint8_t enable;
if (param->defect_pixel_mapped == true &&
param->defect_pixel_dynamic == true)
{
enable = 3;
}
else
if (param->defect_pixel_mapped == false &&
param->defect_pixel_dynamic == true)
{
enable = 2;
}
else
if (param->defect_pixel_mapped == true &&
param->defect_pixel_dynamic == false)
{
enable = 1;
}
else
{
enable = 0;
}
ret = g_pExpUnit->CA378_SetDefectPixel(enable);
cout <<
format("CA378_SetDefectPixel: enable = %d, ret = %X", enable, ret)
<< endl;
}
break;
case CMD_GAMMA: // Gamma Correction
{
SetGammaValue(param->gamma_value);
EnableGamma(param->enable_gamma);
if (param->enable_gamma)
{
if (param->enable_srgb_gamma)
{
UpdateSRGBGammaTable();
}
else
{
UpdateGammaTable(param->gamma_value);
}
}
}
break;
case CMD_CCM: // CCM(Color Corretion Matrix)
{
if (param->enable_ccm)
{
cout << "Enable Color Correction Matrix" << endl;
UpdateCCMTable(param->ccm);
EnableCCM(true);
}
else
{
cout << "Disable Color Correction Matrix" << endl;
EnableCCM(false);
}
}
break;
case CMD_HISTOGRAM: // Histogram
{
DisplayHistogram(param->display_histogram);
}
break;
case CMD_CONTRAST: // Contrast
{
EnableContrast(param->enable_contrast, param->contrast_value);
}
break;
#ifdef CA378_AOIS
case CMD_MANUAL_FOCUS: // Manual Focus
{
uint16_t value;
switch (param->focus_mode)
{
case FOCUS_MODE_DIRECT:
param->manual_focus_position = param->focus_position;
break;
case FOCUS_MODE_INFINITY:
param->focus_position = 0x0;
break;
case FOCUS_MODE_MACRO:
param->focus_position = 0x3FF;
break;
default:
break;
}
value = param->focus_position;
ret = g_pExpUnit->CA378_SetFocusPosition(value);
cout <<
format("CA378_SetFocusPosition: position = %d, ret = %X", value, ret)
<< endl;
}
break;
case CMD_AUTO_FOCUS: // Auto Focus
{
if (param->enable_auto_focus)
{
// Set first AF position
int position = GetFocusPosition();
SetAfPosition(position);
}
SetAutoFocus(param);
}
break;
case CMD_GET_AF_POSITION: // Get AF position
{
param->focus_position = GetAfPosition();
}
break;
case CMD_OIS: // OIS
{
uint8_t mode;
mode = param->ois_mode;
ret = g_pExpUnit->CA378_SetOISMode(mode);
cout <<
format("CA378_SetOISMode: mode = %d, ret = %X", mode, ret)
<< endl;
}
break;
#endif
case CMD_EEPROM_SAVE: // Save EEPROM
{
uint8_t table_number;
table_number = param->eeprom_table_number;
ret = g_pExpUnit->CA378_SaveEEPROM(table_number);
cout <<
format("CA378_SaveEEPROM: table_number = %d, ret = %X", table_number, ret)
<< endl;
}
break;
case CMD_EEPROM_LOAD: // Load EEPROM
{
uint8_t table_number;
uint8_t table_value[16] = { 0 };
uint16_t value;
uint16_t r_value, g_value, b_value;
table_number = param->eeprom_table_number;
ret = g_pExpUnit->CA378_LoadEEPROM(table_number, table_value);
cout <<
format("CA378_LoadEEPROM: table_number = %d, ret = %X", table_number, ret)
<< endl;
if (ret == CA378_SUCCESS)
{
value = (table_value[0] << 8) + table_value[1];
param->exposure = value;
cout <<
format(" Exposure : %d", value)
<< endl;
value = (table_value[2] << 8) + table_value[3];
param->analog_gain = value / 256.0;
cout <<
format(" AnalogGain : %.3lf (0x%04X)", value / 256.0, value)
<< endl;
r_value = (table_value[4] << 8) + table_value[5];
g_value = (table_value[6] << 8) + table_value[7];
b_value = (table_value[8] << 8) + table_value[9];
param->white_balance_r = r_value / 256.0;
param->white_balance_g = g_value / 256.0;
param->white_balance_b = b_value / 256.0;
cout <<
format(" WhiteBalance: R = %.3lf (0x%04X), G = %.3lf (0x%04X), B = %.3lf (0x%04X)",
r_value / 256.0, r_value, g_value / 256.0, g_value, b_value / 256.0, b_value)
<< endl;
value = (table_value[11] << 8) + table_value[12];
param->enable_black_level = table_value[10];
param->black_level = value;
param->defect_pixel_mapped = (table_value[13] & 0x1);
param->defect_pixel_dynamic = (table_value[13] & 0x2) >> 1;
param->enable_lsc = table_value[14] ? true : false;
param->lsc_table_number = table_value[14];
cout <<
format(" BlackLevel : enable = %d, value = %d", table_value[10], value)
<< endl;
cout <<
format(" DefectPixel : enable = %d", table_value[13])
<< endl;
cout <<
format(" LensShading : table_number = %d", table_value[14])
<< endl;
}
}
break;
case CMD_EEPROM_UPLOAD_LSC: // Upload LSC to EEPROM
{
uint8_t table_number;
uint8_t bayer_num = 4;
uint8_t data[96] = { 0 };
char bayer_id[][4] = { "R", "GR", "GB", "B" };
char* pPath = NULL;
table_number = param->save_lsc_table_number;
switch (table_number)
{
case 1:
pPath = (char*)param->lsc_table1_path.c_str();
break;
case 2:
pPath = (char*)param->lsc_table2_path.c_str();
break;
case 3:
pPath = (char*)param->lsc_table3_path.c_str();
break;
default:
break;
}
for (int bayer_index = 0; bayer_index < bayer_num; bayer_index++)
{
ret = LoadLensShadingTable(pPath, bayer_index, data);
if (ret == 0)
{
ret = g_pExpUnit->CA378_SaveEEPROM_LSC(table_number, bayer_index, data);
cout <<
format("CA378_SaveEEPROM_LSC: table_number = %d, bayer = %s, ret = %X",
table_number, bayer_id[bayer_index], ret)
<< endl;
cout << format(" LSC data: ");
for (int i = 0; i < sizeof(data); i += 2)
{
if (i % 16 == 0) cout << endl;
cout << format("%3d(0x%03X) ", (data[i] << 8) + data[i + 1], (data[i] << 8) + data[i + 1]);
}
cout << endl << endl;
}
else
{
cout << format("Failed to Load LSC Table.(%s)") << endl;
break;
}
}
}
break;
case CMD_EEPROM_DOWNLOAD_LSC: // Download LSC from EEPROM
{
uint8_t table_number;
uint8_t bayer_num = 4;
uint8_t data[96] = { 0 };
char bayer_id[][4] = { "R", "GR", "GB", "B" };
char* pPath = NULL;
table_number = param->save_lsc_table_number;
switch (table_number)
{
case 1:
pPath = (char*)param->lsc_table1_path.c_str();
break;
case 2:
pPath = (char*)param->lsc_table2_path.c_str();
break;
case 3:
pPath = (char*)param->lsc_table3_path.c_str();
break;
default:
break;
}
for (int bayer_index = 0; bayer_index < bayer_num; bayer_index++)
{
ret = g_pExpUnit->CA378_LoadEEPROM_LSC(table_number, bayer_index, data);
if (ret == CA378_SUCCESS)
{
SaveLensShadingTable(pPath, bayer_index, data);
}
cout <<
format("CA378_LoadEEPROM_LSC: table_number = %d, bayer = %s, ret = %X",
table_number, bayer_id[bayer_index], ret)
<< endl;
cout << format(" LSC data: ");
for (int i = 0; i < sizeof(data); i += 2)
{
if (i % 16 == 0) cout << endl;
cout << format("%3d(0x%03X) ", (data[i] << 8) + data[i + 1], (data[i] << 8) + data[i + 1]);
}
cout << endl << endl;
}
}
break;
case CMD_EEPROM_DEFAULT: // Set Default Table number for EEPROM
{
uint8_t table_number;
table_number = param->eeprom_table_number;
ret = g_pExpUnit->CA378_DefaultEEPROM(table_number);
cout <<
format("CA378_DefaultEEPROM: table_number = %d, ret = %X", table_number, ret)
<< endl;
}
break;
case CMD_EEPROM_CLEAR: // Clear EEPROM
{
ret = g_pExpUnit->CA378_ClearEEPROM();
cout <<
format("CA378_ClearEEPROM: ret = %X", ret)
<< endl;
}
break;
case CMD_CAPTURE: // Still Capture
StillCapture();
break;
case CMD_MOVIE: // Movie Record
MovieRecord(param->record_frame);
break;
case CMD_MAX_RECORD_FRAME: // Max Record Frame
param->max_record_frame = GetMaxRecordFrame(param->select_mode);
break;
case CMD_RECORD_PROGRESS:
param->record_progress = GetRecordProgress();
break;
case CMD_CONVERT_PROGRESS:
param->convert_progress = GetConvertProgress();
break;
case CMD_GET_AVERAGE_FPS: // Get Average FPS
param->average_fps = GetAverageFps();
break;
case CMD_GET_CAPTURED_FRAMES: // Get Captured Frames
param->captured_frames = GetCapturedFrames();
break;
default:
cout << "Bad Command I/F!" << endl;
ret = -1;
break;
}
return ret;
}
/*******************************************************************************
* @brief Focus direct moving
*
* @param position Focus target position
*
* @return void
******************************************************************************/
void DirectMove(int position)
{
if (g_pExpUnit)
{
g_pExpUnit->CA378_SetFocusPosition(position);
}
}
/*******************************************************************************
* @brief Get Focus position
*
* @param void
*
* @return Focus position
******************************************************************************/
int GetFocusPosition(void)
{
uint16_t position = 0x200;
if (g_pExpUnit)
{
g_pExpUnit->CA378_GetFocusPosition(&position);
}
return position;
}
|
0ccf3a8fa5e048f6f776f6d21f42ec2c148ba516 | 49e125a9e43d22706cea8f304e88c96dd20197ae | /Codeforces/bowow.cpp | c712614c3bb3dc36351e6eface81ae72bd07d4a5 | [] | no_license | tahsinsoha/Problem-solving- | b0382b7afa539715dafb1fbc40666e4051b5f7db | 7049dcc7ab9e4a59977787c2e9052055bff560a8 | refs/heads/master | 2023-01-06T02:35:56.822736 | 2020-11-04T12:15:43 | 2020-11-04T12:15:43 | 280,789,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | cpp | bowow.cpp | #include<bits/stdc++.h>
#define mod 1000000007
using namespace std;
unsigned long long Pow(unsigned long long x, unsigned long long y){
unsigned long long res = 1;
while(y>0){
if(y&1)
res = (res*x)%mod ;
x= (x*x)%mod;
y>>=1;
}
return res;
}
int main(){
string s;
cin>>s;
unsigned long long sz = 0;
unsigned long long num= 0;
for(unsigned long long i=s.size()-1;i>=0;i--){
if(s[i]=='1') num = num+ Pow(2,sz);
sz++;
}
unsigned long long temp=0;
for(unsigned long long i=0;;i++){
if(i>0) temp = i;
if(pow(4,i)>=num) {
cout<<temp<<endl;
return 0;
}
}
return 0;
}
|
907059ea7dfd29b922af2f70e20c3ed8ab806055 | 6728f511ffb966da8d9c7e27c752aa318e66da54 | /test/functional/steps/TriangleSteps.cpp | 99df4b1bb44345cdc54292e1fc909f2e2114ebe3 | [] | no_license | tkadauke/raytracer | 32bf28f6a3368dc6c75a950cc929a81157b6c06d | 013cf2817c925bbce763d277b8db7ebd428ae8df | refs/heads/master | 2023-02-07T05:00:40.258183 | 2023-01-28T09:54:58 | 2023-01-28T09:54:58 | 6,061,333 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 873 | cpp | TriangleSteps.cpp | #include "test/functional/support/RaytracerFeatureTest.h"
#include "test/functional/support/GivenWhenThen.h"
#include "raytracer/primitives/Triangle.h"
using namespace testing;
using namespace raytracer;
GIVEN(RaytracerFeatureTest, "a centered triangle") {
auto triangle = std::make_shared<Triangle>(Vector3d(-1, -1, 0), Vector3d(-1, 1, 0), Vector3d(1, -1, 0));
triangle->setMaterial(test->redDiffuse());
test->add(triangle);
}
GIVEN(RaytracerFeatureTest, "a displaced triangle") {
auto triangle = std::make_shared<Triangle>(Vector3d(-1, 20, 0), Vector3d(-1, 21, 0), Vector3d(1, 20, 0));
triangle->setMaterial(test->redDiffuse());
test->add(triangle);
}
THEN(RaytracerFeatureTest, "i should see the triangle") {
ASSERT_TRUE(test->objectVisible());
}
THEN(RaytracerFeatureTest, "i should not see the triangle") {
ASSERT_FALSE(test->objectVisible());
}
|
eb08d8d090d19a7b0b1fefbcf91bf4c7d71bbb35 | 569d64661f9e6557022cc45428b89eefad9a6984 | /code/gameholder/buff_func_base.h | f03d26868a378facdc922b0483b38d67ab07c5e3 | [] | no_license | dgkang/ROG | a2a3c8233c903fa416df81a8261aab2d8d9ac449 | 115d8d952a32cca7fb7ff01b63939769b7bfb984 | refs/heads/master | 2020-05-25T02:44:44.555599 | 2019-05-20T08:33:51 | 2019-05-20T08:33:51 | 187,584,950 | 0 | 1 | null | 2019-05-20T06:59:06 | 2019-05-20T06:59:05 | null | UTF-8 | C++ | false | false | 1,772 | h | buff_func_base.h | /*
* buff 功能基类
*/
#ifndef buff_func_base_h__
#define buff_func_base_h__
#include "battle_define.h"
class Buff;
class BuffData;
class BattleUnit;
class BuffController;
class BuffFuncBase
{
public:
typedef std::map<uint32, int32> PropertyMap;
BuffFuncBase(uint32 funcId);
virtual ~BuffFuncBase();
BattleUnit* GetOwner();
BuffController* GetOwnerBuffController();
uint32 GetFuncId() {return m_FuncId;}
virtual void Start() {}
virtual void Update(uint32 delta_time) {}
virtual void End();
virtual void OnUpdateValue() {}
virtual void ResetLifeTime(int32 lifeTime) {}
void SetBuff(Buff* pBuff) {m_pBuff = pBuff;}
void SetArgs(int32 arg1, int32 arg2, uint32 val_index) {m_arg1 = arg1; m_arg2 = arg2; m_BuffValIndex = val_index;}
int32 GetArg1() {return m_arg1;}
int32 GetArg2() {return m_arg2;}
int32 GetBuffVal();
const PropertyMap& GetPropertyMap() const {return m_property_map;}
void AddProperty(uint32 property_id, int32 val);
void SubProperty(uint32 property_id, int32 val);
void SetProperty(uint32 property_id, int32 value);
int32 GetProperty(uint32 property_id);
void AddDamage(const DamageValue& damage);
void AddHeal(int32 heal);
virtual bool CanDead() {return true;}
virtual DAMAGE_INFO FilterDamage(DAMAGE_INFO damage) {return damage;}
protected:
Buff* m_pBuff;
uint32 m_FuncId; // buff功能Id
private:
PropertyMap m_property_map; // 改变的属性集合<m_PropertyId, m_PropertyValue>
int32 m_arg1; // 功能参数1
int32 m_arg2; // 功能参数2
uint32 m_BuffValIndex; // 使用第几个buff数值
};
#endif // buff_func_base_h__
|
393b6182ea8c4932a5c0a5925f1c6a121b5f8e91 | b4f19ec1b2956d336cf56a409546d9c7502106c3 | /Thanadolos World/Utils.hpp | 9ced57234c161576cee83025a4f57fe57b58b2d4 | [] | no_license | w0dm4n/Thanadolos | d3095a8aec322270cf94d70f4709396ef6275cd2 | 35086d7658175735c6490a188d42580afdbd6c14 | refs/heads/master | 2021-03-16T05:54:11.638301 | 2017-06-19T22:54:17 | 2017-06-19T22:54:17 | 90,393,751 | 18 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 588 | hpp | Utils.hpp | #pragma once
#ifndef UTILS_HPP
# define UTILS_HPP
#include <time.h>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#define Split std::vector<std::string>
class Utils
{
public:
static int getRand(int min, int max);
static const int getIntValueFromString(const std::string);
static std::vector<std::string> split(const std::string &s, char delim);
template<typename Out>
static void split(const std::string &s, char delim, Out result);
static std::string strToLower(std::string value);
static long int getUnixTimestamp();
};
#endif |
e61e77ad49a0ce9f82391a5fc490f8e206ca3586 | f5f0d506bc7e0c7bc8a67d40ff24abb1d93f975d | /005_cache/cache.cpp | 8eabd5e223dd0ce7e276b8324d62724e572ff3fd | [] | no_license | akshayjee/cache-hierarchy-simulator | dfd326d788f285bfd7fb07047ea5d6bf37575b2a | 1bc73446cf1e669f04f4f604ec8cc2255972281c | refs/heads/master | 2020-03-07T17:02:21.422825 | 2018-04-01T06:07:06 | 2018-04-01T06:07:06 | 127,600,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,891 | cpp | cache.cpp | #include "stghold.h"
#include "cache.h"
#include "cmdCenter.h"
int cache::getWay(string & ass){
int ans;
//HERE TO IMPLEMENT
string ass_int;
string::iterator it;
if( !ass.empty() ) {
for( it = ass.begin(); it != ass.end(); it++) {
ass_int.push_back(*it);
}
}
stringstream ss;
ss<<std::dec<<ass_int;
ss>>ans;
return ans;
}
replacer * cache::createReplacer(){
if (rep == "FIFO"){
return( new FIFO(set,way));
}
else if(rep == "LRU"){
return( new LRU(set,way));
}
else if(rep == "NMRU"){
return( new NMRU(set,way));
}
else if(rep == "RND"){
return( new RND(set,way));
}
else{
return NULL;
}
}
void cache::askCacheInfo(scout & cachInfo){
//if fully
if(cachInfo.assoc == "FULLY"){
set = 1;
way = cachInfo.cap/cachInfo.bsize;
}
else if(cachInfo.assoc == "DIRECT"){
way = 1;
set = cachInfo.cap/cachInfo.bsize;
}
else{
way = getWay(cachInfo.assoc); //get way according to associativity
int setTimesWay = cachInfo.cap/cachInfo.bsize;
set = setTimesWay/way;
}
rep = cachInfo.rep;
wralloc = cachInfo.wralloc;
blockSize = cachInfo.bsize;
wpRecorder = vector<vector<weapon> > (set);
for (int i = 0; i < (int) wpRecorder.size();++i){
wpRecorder[i] = vector<weapon> (way);
}
repPolicy = createReplacer();//create replacement class
}
void cache::decoder::decodeAddr(string & oneLine, cache * Info){
//read one line and store it
//and decode that line;
//figure out what index and tag is for this addr
string line_addr (oneLine.begin()+2,oneLine.end());
//Convert oneLine string from Hex to Binary:
stringstream hexLine;
string binaryLine;
unsigned n;
hexLine << hex << line_addr;
hexLine >> n;
bitset<32> b(n);
binaryLine = b.to_string();
//For a Fully Associative Cache:
if (Info->set == 1) {
string tempBin(binaryLine.begin(),binaryLine.end() - log2(Info->blockSize));
tag = tempBin;
index = 0;
}
//For an n-Way set associative Cache as well as Direct Mapped:
else{
string tempBin(binaryLine.begin(), binaryLine.end() - log2(Info->blockSize) - log2(Info->set));
tag = tempBin;
string index_s(binaryLine.end() - log2(Info->blockSize) - log2(Info->set), binaryLine.end() - log2(Info->blockSize));
//stringstream index_ss (index_s);
bitset <32> temp_string(index_s);
stringstream index_ss;
index_ss << temp_string.to_ulong();
index_ss >> index;
}
line = oneLine;
}
int cache::isSetFull(int whichSet){ //This function check whether any of the block in certain set has invalid bit, if any, return that index,otherwise
//return 0
for(int i = 0; i < (int) wpRecorder[whichSet].size(); ++i){
if (!wpRecorder[whichSet][i].isValid){
return i;
}
}
return -1;
}
void cache::replaceBlock(int set, int index, cache::decoder & enigma, bool needDirty){
//vector<weapon> weapon_line = wpRecorder[set];
weapon replaceWeapon = wpRecorder[set][index];
replaceWeapon.tag = enigma.tag;
replaceWeapon.addr = enigma.line;
replaceWeapon.isValid = 1;
if(needDirty == true) {
replaceWeapon.isDirty = 1; //check dirty bit for different conditions
}
else{
replaceWeapon.isDirty = 0;
}
wpRecorder[set][index] = replaceWeapon;
}
int cache::tagComparator(int set, string tag){
int bucket = 0;
vector<weapon> weapon_line;
weapon_line = wpRecorder[set];
vector<weapon>::iterator it;
for(it = weapon_line.begin(); it != weapon_line.end(); it++) {
if(it->tag == tag) {
return bucket;
}
bucket++;
}
return -1;
}
void cache::addMiss(int m){
++missTimes;
switch(m) {
case 0: ++dataReadMisses;
break;
case 1: ++dataWriteMisses;
break;
case 2: ++instMisses;
break;
default: ++miscMisses;
break;
}
}
void cache::writeMissInvalid(cache::decoder & enigma, cmdCenter *cmd, int code, int whichBlock){
addMiss(code);
if(wralloc == true){
if (level_cache == 2){
cmd->accessTime+=cmd->memAccTime;
replaceBlock(enigma.index,whichBlock,enigma,true);
if (rep == "LRU" || rep == "NMRU"){ //Don't have this for direct map
repPolicy->update(enigma.index,whichBlock);
}
}
else{
cmd->read(0,cmd->level_2,enigma.line); //bring the block into this level
replaceBlock(enigma.index,whichBlock,enigma,true);
if (rep == "LRU" || rep == "NMRU"){ //Don't have this for direct map
repPolicy->update(enigma.index,whichBlock);
}
}
}
else{
if (level_cache == 2) {
//if this is level 2, then we have a write miss on level 2. It's not write allocate, we directly write into next level, in this case main memory
//the way to do this is by incrementing main memory access time
cmd->accessTime+=cmd->memAccTime;
}
else { //this means we have a write miss on level 1. And it is not write allocated, we directly write into next level, in this case level 2. NOTE that we will only write something into data cache. Instruction cache can never be written.
cmd->write(code,cmd->level_2,enigma.line);
}
}
}
void cache::writeMiss(cache::decoder & enigma, cmdCenter *cmd, int code){
//Some code
addMiss(code);
//if allocate on write miss is yes(= true in bool) - do same as read miss
if (wralloc == true) {
//if this is level_2, we reach the end
if (level_cache == 2){
//this means we have a writeMiss in level_2
//add main memory access Time
cmd->accessTime+=cmd->memAccTime;
//find the block to replace according to replace information
int which2Kick = 0;
if (repPolicy != NULL){ //set or fully associative
which2Kick = repPolicy->which2Replace(enigma.index);
}
//if dirty
if(wpRecorder[enigma.index][which2Kick].isDirty){
//write this block to next level(new task)
//the way to write to mem is by adding access time
cmd->accessTime+=cmd->memAccTime;
}
//replace the block(overwrite)
replaceBlock(enigma.index,which2Kick,enigma,true); //remember set to dirty!
//update replacement information
if(repPolicy != NULL){ //set or fully associative doesn't have replacement policy
repPolicy->update(enigma.index,which2Kick);
}
}
//else(it's not level_2 cache(level_1))
//we have a write miss on level_1 (and it's write allocated)
else{
//since it's write allocated, you need to first bring the block you are going to write to into this level's cache, the way to do this is by reading the same address from the next level. You will only write to data cache or unified cache, so you will only read from data cache or unified cache.
cmd->read(0,cmd->level_2,enigma.line); //bring the block into this level
//find the block to replace according to replace information
int which2Kick = 0;
if (repPolicy != NULL){
which2Kick = repPolicy->which2Replace(enigma.index);
}
//if dirty
if(wpRecorder[enigma.index][which2Kick].isDirty){
//write to next level(new task)
//int code = cmd->getCode(wpRecorder[engima.index][which2Kick].addr);
cmd->write(1,cmd->level_2,wpRecorder[enigma.index][which2Kick].addr); //you will never write into instruction cache
}
//replace the block(overwrite)
replaceBlock(enigma.index,which2Kick,enigma,true); //enigma.index->which2Kick //remember set to dirty
//tag information is in enigma
if (repPolicy != NULL){
repPolicy->update(enigma.index, which2Kick);
}
//update replacement information
}
}
//if allocate on write miss is NO
else {
if (level_cache == 2) {
//if this is level 2, then we have a write miss on level 2. It's not write allocate, we directly write into next level, in this case main memory
//the way to do this is by incrementing main memory access time
cmd->accessTime+=cmd->memAccTime;
}
else { //this means we have a write miss on level 1. And it is not write allocated, we directly write into next level, in this case level 2. NOTE that we will only write something into data cache. Instruction cache can never be written.
cmd->write(code,cmd->level_2,enigma.line);
}
}
}
void cache::readMissInvalid(cache::decoder & enigma, cmdCenter * cmd, int code, int whichBlock){
addMiss(code);
if(level_cache == 2){
cmd->accessTime+=cmd->memAccTime;
replaceBlock(enigma.index,whichBlock,enigma,false);
if (rep == "LRU" || rep == "NMRU"){ //Don't have this for direct map
repPolicy->update(enigma.index,whichBlock);
}
}
else{
cmd->read(code,cmd->level_2,enigma.line);
//find the block to replace according to replace information
//if this block is invalid, we don't use replacement Policy just replace this block immediately
replaceBlock(enigma.index,whichBlock,enigma,false);
if (rep == "LRU" || rep == "NMRU"){ //Don't have this for direct map
repPolicy->update(enigma.index,whichBlock);
}
}
}
void cache::readMiss(cache::decoder & enigma,cmdCenter * cmd,int code){
addMiss(code);
//if this is level_2, we reach the end
if (level_cache == 2){
//this means we have a readMiss in level_2
//add main memory access Time
cmd->accessTime+=cmd->memAccTime;
//find the block to replace according to replace information
//valid miss
int which2Kick = 0;
if(repPolicy != NULL){ //FULLY OR SET ASSOCIATIVE
which2Kick = repPolicy->which2Replace(enigma.index);
} //if dirty
if(wpRecorder[enigma.index][which2Kick].isDirty){
//write this block to next level(new task)
//the way to write to mem is by adding access time
cmd->accessTime+=cmd->memAccTime;
}
//replace the block(overwrite)
replaceBlock(enigma.index,which2Kick,enigma,false);
//update replacement information
if (repPolicy != NULL){ //Don't have this for direct
repPolicy->update(enigma.index,which2Kick);
}
}
//else(it's not level_2 cache(level_1))
//we miss on level_1
else{
cmd->read(code,cmd->level_2,enigma.line); //read from next level
int which2Kick = 0;
if (repPolicy != NULL){ //SET OR FULLY
which2Kick = repPolicy->which2Replace(enigma.index);
}
//if dirty
if(wpRecorder[enigma.index][which2Kick].isDirty){
//write to next level(new task)
//int code = cmd->getCode(wpRecorder[engima.index][which2Kick].addr); //you need code because you need to know what type of cache you need to write to
//you will always write to data cache
cmd->write(1,cmd->level_2,wpRecorder[enigma.index][which2Kick].addr);
}
//replace the block(overwrite)
replaceBlock(enigma.index,which2Kick,enigma,false); //enigma.indx->which2Kick
//tag information is in enigma
if (repPolicy != NULL){ //SET OR FULLY
repPolicy->update(enigma.index, which2Kick);
}
}
//update replacement information
}
void cache::readCache(int code, cmdCenter * cmd, string & line){
//add hitTime to accessTime(because anyway this will access the cache of this level)
cmd->accessTime = cmd->accessTime + hitTime;
if (code == 0)
++accHowManyR; //Accessing number + 1
else
++accHowManyI;
//create a decoder
decoder enigma;
//decode the line,fill the information into decoder
enigma.decodeAddr(line, this);
//according to decoded info find the set we are looking for
//compare to each tag in this set find which tag it is
int whichBlock = tagComparator(enigma.index, enigma.tag);
//if find one
if (whichBlock != -1){
//if valid
if(wpRecorder[enigma.index][whichBlock].isValid){
//this is a hit
//update replacement information if it's NMRU or LRU(FIFO and RND only need to be updated when kickout)
if(rep == "NMRU" || rep == "LRU"){
repPolicy->update(enigma.index,whichBlock);
}
//simply return
return;
}
else{
readMissInvalid(enigma,cmd,code,whichBlock);
}
//if not found or invalid then it's a miss
}
else{
int whichBlock = isSetFull(enigma.index);
if (whichBlock == -1){ //If there is still invalid block in this set
//that means the set is not full
//when we replace we don't follow replacement policy
readMiss(enigma,cmd,code);
}
else{
readMissInvalid(enigma,cmd,code,whichBlock);
}
}
}
void cache::writeCache(int code, cmdCenter * cmd, string & line){
//add hitTime to accessTime(because anyway this will access the cache of this level)
cmd->accessTime = cmd->accessTime + hitTime;
++accHowManyW; //Number of Accesses + 1
//create a decoder
decoder enigma;
//decode the line,fill the information into decoder
enigma.decodeAddr(line, this);
//according to decoded info find the set we are looking for
//compare to each tag in this set find which tag it is
int whichBlock = tagComparator(enigma.index, enigma.tag);
//if find one
if (whichBlock != -1){
//if valid
if(wpRecorder[enigma.index][whichBlock].isValid){
//this is a write hit, you write and change dirty bit to 1
wpRecorder[enigma.index][whichBlock].isDirty = true;
//update replacement information if it's NMRU or LRU(FIFO and RND only need to be updated when kickout)
if(rep == "NMRU" || rep == "LRU"){
repPolicy->update(enigma.index,whichBlock);
}
//simply return
return;
}
else{
writeMissInvalid(enigma,cmd,code,whichBlock);
}
}
//if not found or invalid then it's a miss
else{
int whichBlock = isSetFull(enigma.index);
if (whichBlock == -1){ //If there is still invalid block in this set
//that means the set is not full
//when we replace we don't follow replacement policy
writeMiss(enigma,cmd,code);
}
else{
writeMissInvalid(enigma,cmd,code,whichBlock);
}
}
}
|
67c38a8b1bbf77473fe24852cddf8637268aa0fa | ba4db75b9d1f08c6334bf7b621783759cd3209c7 | /src_main/public/dme_controls/AttributeBasePickerPanel.h | 4e1f4f793c23aa0c14a9761dd6ac1d21a5649019 | [] | no_license | equalent/source-2007 | a27326c6eb1e63899e3b77da57f23b79637060c0 | d07be8d02519ff5c902e1eb6430e028e1b302c8b | refs/heads/master | 2020-03-28T22:46:44.606988 | 2017-03-27T18:05:57 | 2017-03-27T18:05:57 | 149,257,460 | 2 | 0 | null | 2018-09-18T08:52:10 | 2018-09-18T08:52:09 | null | WINDOWS-1252 | C++ | false | false | 1,328 | h | AttributeBasePickerPanel.h | //====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifndef ATTRIBUTEBASEPICKERPANEL_H
#define ATTRIBUTEBASEPICKERPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include "dme_controls/AttributeTextPanel.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class CDmElement;
namespace vgui
{
class Button;
}
//-----------------------------------------------------------------------------
// CAttributeBasePickerPanel
//-----------------------------------------------------------------------------
class CAttributeBasePickerPanel : public CAttributeTextPanel
{
DECLARE_CLASS_SIMPLE( CAttributeBasePickerPanel, CAttributeTextPanel );
public:
CAttributeBasePickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info );
// Inherited from Panel
virtual void OnCommand( const char *cmd );
virtual void PerformLayout();
private:
// Inherited classes must implement this
virtual void ShowPickerDialog() = 0;
vgui::Button *m_pOpen;
};
#endif // ATTRIBUTEBASEPICKERPANEL_H
|
7c94780b460e1780e64f0483f1bbe7576c3c05e5 | 855af63c1c6cf2546ceae7bc47572dcd93fdc8ce | /fork_ex_1/01-simple-fork.cpp | cd24de89212fbfc71423412ee75355278f96b0a1 | [] | no_license | BenTarman/fork-exec-pipe-examples | 5390538d9701cce6d62b1130dd8274796e5fe305 | 8158c098f6e7d42ce36e6842d016cbf56f21fc9f | refs/heads/master | 2021-05-11T04:33:27.924122 | 2018-01-18T06:35:54 | 2018-01-18T06:35:54 | 117,942,492 | 0 | 0 | null | 2018-01-18T06:31:58 | 2018-01-18T06:31:58 | null | UTF-8 | C++ | false | false | 437 | cpp | 01-simple-fork.cpp | /**
* Simple program demonstrating fork(), a system call that spawns a new process.
*
* man fork
*/
#include <iostream>
#include <unistd.h>
using namespace std;
int main() {
// Fork a new child process. After this system call, there will be two
// processes executing.
pid_t pid = fork();
cout << "My pid is: " << pid << endl;
// In practice, you should always check for errors when using system calls!
return 0;
}
|
e7c6e3b34395f1e9b4979da0574c1fcdc7d26cc5 | 06aa3647ea9caf1e5fe6cd37c76651f6fece1a3b | /src/mxFindDialog.cpp | 3ab76075eaf2ad7935180b0e467009e61d1050b1 | [] | no_license | SoftwareIDE/ZinjaI | 6731dc9a5a67a9f138f547f02f8c62a67d42f8d5 | a3d752bf5fa971a726fc4ba036d860edf6588b5f | refs/heads/master | 2020-12-24T19:46:21.098172 | 2016-05-04T20:45:52 | 2016-05-04T20:45:52 | 58,789,743 | 3 | 4 | null | null | null | null | ISO-8859-1 | C++ | false | false | 26,156 | cpp | mxFindDialog.cpp | #include <wx/sizer.h>
#include <wx/combobox.h>
#include <wx/arrstr.h>
#include <wx/button.h>
#include <wx/stattext.h>
#include <wx/textfile.h>
#include "mxFindDialog.h"
#include "mxUtils.h"
#include "mxBitmapButton.h"
#include "mxSource.h"
#include "mxMainWindow.h"
#include "mxMessageDialog.h"
#include "ids.h"
#include "ProjectManager.h"
#include "mxHelpWindow.h"
#include "mxSizers.h"
#include "Language.h"
#include "mxCommonConfigControls.h"
BEGIN_EVENT_TABLE(mxFindDialog, wxDialog)
EVT_BUTTON(mxID_HELP_BUTTON,mxFindDialog::OnHelpButton)
EVT_BUTTON(mxID_FIND_FIND_NEXT,mxFindDialog::OnFindNextButton)
EVT_BUTTON(mxID_FIND_FIND_PREV,mxFindDialog::OnFindPrevButton)
EVT_BUTTON(mxID_FIND_REPLACE,mxFindDialog::OnReplaceButton)
EVT_BUTTON(mxID_FIND_REPLACE_ALL,mxFindDialog::OnReplaceAllButton)
EVT_BUTTON(mxID_FIND_CANCEL, mxFindDialog::OnCancel)
EVT_COMBOBOX(mxID_FIND_SCOPE, mxFindDialog::OnComboScope)
EVT_CLOSE(mxFindDialog::OnClose)
END_EVENT_TABLE()
mxFindDialog::mxFindDialog(wxWindow* parent, wxWindowID id, const wxPoint& pos , const wxSize& size , long style) : wxDialog(parent, id, LANG(FIND_CAPTION,"Buscar"), pos, size, style) {
wxBoxSizer *mySizer= new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer *optSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *butSizer = new wxBoxSizer(wxVERTICAL);
optSizer->Add(new wxStaticText(this, wxID_ANY, LANG(FIND_SEARCH_FOR,"Texto a buscar:"), wxDefaultPosition, wxDefaultSize, 0), sizers->BA5);
combo_find = new wxComboBox(this, wxID_ANY);
optSizer->Add(combo_find,sizers->BLB5_Exp0);
optSizer->Add(replace_static = new wxStaticText(this, wxID_ANY, LANG(REPLACE_WITH,"Reemplazar por:"), wxDefaultPosition, wxDefaultSize, 0), sizers->BA5);
combo_replace = new wxComboBox(this, wxID_ANY);
optSizer->Add(combo_replace,sizers->BLB5_Exp0);
check_word = mxDialog::AddCheckBox(optSizer,this,LANG(FIND_WHOLE_WORD,"Solo palabras completas"),false);
check_start = mxDialog::AddCheckBox(optSizer,this,LANG(FIND_BEGINNING_OF_WORD,"Solo al comienzo de la palabra"),false);
check_case = mxDialog::AddCheckBox(optSizer,this,LANG(FIND_MATCH_CASE,"Distinguir mayusculas y minusculas"),false);
check_nocomments = mxDialog::AddCheckBox(optSizer,this,LANG(FIND_IGNORE_COMMENTS,"Ignorar comentarios"),false);
check_regexp = mxDialog::AddCheckBox(optSizer,this,LANG(FIND_USE_REGULAR_EXPRESSIONS,"Es una expresion regular"),false);
wxArrayString scopes;
scopes.Add(LANG(FIND_SELECTION,"Seleccion"));
scopes.Add(LANG(FIND_CURRENT_FILE,"Archivo actual"));
scopes.Add(LANG(FIND_ALL_OPENED_FILES,"Todos los Archivos Abiertos"));
scopes.Add(LANG(FIND_ALL_PROJECT_SOURCES,"Todos los Fuentes del Proyecto"));
scopes.Add(LANG(FIND_ALL_PROJECT_HEADERS,"Todas las Cabeceras del Proyecto"));
scopes.Add(LANG(FIND_ALL_PROJECT_OTHERS,"Todos los Otros Archivos del Proyecto"));
scopes.Add(LANG(FIND_ALL_PROJECT_FILES,"Todos los Archivos del Proyecto"));
combo_scope = mxDialog::AddComboBox(optSizer,this,LANG(FIND_FIND_SCOPE,"Buscar en"),scopes,1,mxID_FIND_SCOPE);
check_close = mxDialog::AddCheckBox(optSizer,this,LANG(FIND_CLOSE_AFTER_FIND,"Cerrar este dialogo después de encontrar"),true);
replace_button = new mxBitmapButton (this, mxID_FIND_REPLACE, bitmaps->buttons.replace, LANG(FIND_REPLACE,"Reemplazar"));
replace_all_button = new mxBitmapButton (this, mxID_FIND_REPLACE_ALL, bitmaps->buttons.replace, LANG(FIND_REPLACE_ALL,"Reemplazar Todo"));
next_button = new mxBitmapButton (this, mxID_FIND_FIND_NEXT, bitmaps->buttons.find, LANG(FIND_FIND_NEXT,"Buscar Siguiente"));
prev_button = new mxBitmapButton (this, mxID_FIND_FIND_PREV, bitmaps->buttons.find, LANG(FIND_FIND_PREVIOUS,"Buscar Anterior"));
wxButton *cancel_button = new mxBitmapButton (this, mxID_FIND_CANCEL, bitmaps->buttons.cancel, LANG(FIND_CANCEL,"Cancelar"));
wxBitmapButton *help_button = new wxBitmapButton (this,mxID_HELP_BUTTON,*(bitmaps->buttons.help));
butSizer->Add(replace_button,sizers->BA5_Exp0);
butSizer->Add(replace_all_button,sizers->BA5_Exp0);
butSizer->Add(next_button,sizers->BA5_Exp0);
butSizer->Add(prev_button,sizers->BA5_Exp0);
butSizer->Add(cancel_button,sizers->BA5_Exp0);
butSizer->AddStretchSpacer();
butSizer->Add(help_button,sizers->BA5_Right);
mySizer->Add(optSizer,sizers->BA5_Exp1);
mySizer->Add(butSizer,sizers->BA5_Exp0);
SetSizerAndFit(mySizer);
combo_find->Append(wxString());
combo_replace->Append(wxString());
SetEscapeId(mxID_FIND_CANCEL);
}
void mxFindDialog::ShowFind(mxSource *source) {
replace_mode=false;
check_close->SetValue(true);
if (source && !check_regexp->GetValue()) {
int i=source->GetSelectionStart();
int f=source->GetSelectionEnd();
// if (i==f) {
// int s=source->WordStartPosition(i,true);
// int e=source->WordEndPosition(i,true);
// if (s!=e)
// combo_find->SetValue(source->GetTextRange(s,e));
// } else if (source->LineFromPosition(i)==source->LineFromPosition(f)) {
if (i!=f && source->LineFromPosition(i)==source->LineFromPosition(f)) {
combo_find->SetSelection(combo_find->GetCount()-1);
if (i<f)
combo_find->SetValue(source->GetTextRange(i,f));
else
combo_find->SetValue(source->GetTextRange(f,i));
} else {
if (combo_scope->GetSelection()==0) combo_scope->SetSelection(1);
if (combo_find->GetCount()>1)
combo_find->SetSelection(combo_find->GetCount()-2);
}
}
replace_static->Hide();
combo_replace->Hide();
replace_all_button->Hide();
replace_button->Hide();
next_button->SetDefault();
SetTitle(LANG(FIND_FIND,"Buscar"));
GetSizer()->SetSizeHints(this);
Fit();
combo_find->SetFocus();
Show();
Raise();
}
void mxFindDialog::ShowReplace(mxSource *source) {
replace_mode=true;
check_close->SetValue(false);
if (combo_scope->GetSelection()>1) {
combo_scope->SetSelection(1);
wxCommandEvent cmd; OnComboScope(cmd);
}
if (combo_replace->GetCount()>1)
combo_replace->SetSelection(combo_find->GetCount()-2);
if (source && !check_regexp->GetValue()) {
int i=source->GetSelectionStart();
int f=source->GetSelectionEnd();
// if (i==f) {
// int s=source->WordStartPosition(i,true);
// int e=source->WordEndPosition(i,true);
// if (s!=e)
// combo_find->SetValue(source->GetTextRange(s,e));
// } else if (source->LineFromPosition(i)==source->LineFromPosition(f)) {
if (i!=f && source->LineFromPosition(i)==source->LineFromPosition(f)) {
combo_find->SetSelection(combo_find->GetCount()-1);
if (i<f)
combo_find->SetValue(source->GetTextRange(i,f));
else
combo_find->SetValue(source->GetTextRange(f,i));
} else {
if (combo_find->GetCount()>1)
combo_find->SetSelection(combo_find->GetCount()-2);
}
}
replace_static->Show();
combo_replace->Show();
replace_all_button->Show();
replace_button->Show();
replace_button->SetDefault();
SetTitle(LANG(FIND_REPLACE,"Reemplazar"));
GetSizer()->SetSizeHints(this);
Fit();
combo_find->SetFocus();
Show();
Raise();
}
bool mxFindDialog::FindPrev() {
if (main_window->notebook_sources->GetPageCount()!=0) {
mxSource *source = (mxSource*)(main_window->notebook_sources->GetPage(main_window->notebook_sources->GetSelection()));
int f,t,p;
if (only_selection) { // seleccion
f = source->GetSelectionStart();
p = t = source->GetSelectionEnd();
if (t>f) { // acomodar el sentido de la seleccion
t=f;
f=p;
p=t;
}
if (f==t || (f-t==int(last_search.Len()) && source->GetTextRange(t,f).CmpNoCase(last_search)==0) ) { // si no hay seleccion tomar el fuente
t=0;
p=f;
f=source->GetLength();
}
} else { // fuente
p=source->GetSelectionStart();
t=0;
f=source->GetLength();
}
// buscar
source->SetSearchFlags(last_flags);
source->SetTargetStart(p);
source->SetTargetEnd(t);
int ret = source->SearchInTarget(last_search);
// si hay que ignorar los comentarios, y esta en comentario, buscar otra
while (check_nocomments->GetValue() && ret!=wxSTC_INVALID_POSITION && source->IsComment(ret)) {
source->SetTargetStart(ret);
source->SetTargetEnd(t);
ret = source->SearchInTarget(last_search);
}
if (ret==wxSTC_INVALID_POSITION && p!=f) {
source->SetTargetStart(f);
if (last_flags&wxSTC_FIND_REGEXP)
source->SetTargetEnd(t);
else
source->SetTargetEnd(p-last_search.Len());
ret=source->SearchInTarget(last_search);
// si hay que ignorar los comentarios, y esta en comentario, buscar otra
while (check_nocomments->GetValue() && ret!=wxSTC_INVALID_POSITION && source->IsComment(ret)) {
source->SetTargetStart(ret);
source->SetTargetEnd(t);
ret = source->SearchInTarget(last_search);
}
}
if (ret>=0) {
source->EnsureVisibleEnforcePolicy(source->LineFromPosition(ret));
source->SetSelection(source->GetTargetStart(),source->GetTargetEnd());
return true;
} else {
return false;
}
}
return false;
}
bool mxFindDialog::FindNext() {
if (main_window->notebook_sources->GetPageCount()!=0) {
mxSource *source = (mxSource*)(main_window->notebook_sources->GetPage(main_window->notebook_sources->GetSelection()));
int f,t,p;
if (only_selection) { // seleccion
p = f = source->GetSelectionStart();
t = source->GetSelectionEnd();
if (t<f) { // acomodar el sentido de la seleccion
f=t;
t=p;
p=f;
}
if (f==t || (t-f==int(last_search.Len()) && source->GetTextRange(f,t).CmpNoCase(last_search)==0) ) { // si no hay seleccion tomar el fuente
f=0;
p=t;
t=source->GetLength();
}
} else { // fuente
p=source->GetSelectionEnd();
f=0;
t=source->GetLength();
}
// buscar
source->SetSearchFlags(last_flags);
source->SetTargetStart(p);
source->SetTargetEnd(t);
int ret = source->SearchInTarget(last_search);
// si hay que ignorar los comentarios, y esta en comentario, buscar otra
while (check_nocomments->GetValue() && ret!=wxSTC_INVALID_POSITION && source->IsComment(ret)) {
source->SetTargetStart(ret+last_search.Len());
source->SetTargetEnd(t);
ret = source->SearchInTarget(last_search);
}
if (ret==wxSTC_INVALID_POSITION && p!=f) {
source->SetTargetStart(f);
if (last_flags&wxSTC_FIND_REGEXP)
source->SetTargetEnd(t);
else
source->SetTargetEnd(p+last_search.Len());
ret = source->SearchInTarget(last_search);
// si hay que ignorar los comentarios, y esta en comentario, buscar otra
while (check_nocomments->GetValue() && ret!=wxSTC_INVALID_POSITION && source->IsComment(ret)) {
source->SetTargetStart(ret+last_search.Len());
source->SetTargetEnd(p+last_search.Len());
ret = source->SearchInTarget(last_search);
}
}
if (ret!=wxSTC_INVALID_POSITION) {
source->EnsureVisibleEnforcePolicy(source->LineFromPosition(ret));
source->SetSelection(source->GetTargetStart(),source->GetTargetEnd());
return true;
} else {
return false;
}
}
return false;
}
void mxFindDialog::OnFindNextButton(wxCommandEvent &event) {
num_results=0;
if (combo_find->GetValue().Len()==0) {
combo_find->SetFocus();
return;
}
if (combo_scope->GetSelection()>2) {
if (!project) {
mxMessageDialog(this,LANG(FIND_NO_PROJECT,"No hay ningun proyecto abierto actualmente."))
.Title(LANG(GENERAL_ERROR,"Error")).IconInfo().Run();
return;
}
} else {
if (!main_window->notebook_sources->GetPageCount()) {
return;
}
}
last_search = combo_find->GetValue();
if (last_search!=combo_find->GetString(combo_find->GetCount()-1)) {
combo_find->SetString(combo_find->GetCount()-1,last_search);
combo_find->Append(wxString());
}
int scope = combo_scope->GetSelection();
only_selection = (scope==0);
last_flags =
(check_case->GetValue()?wxSTC_FIND_MATCHCASE:0) |
(check_word->GetValue()?wxSTC_FIND_WHOLEWORD:0) |
(check_start->GetValue()?wxSTC_FIND_WORDSTART:0) |
(check_regexp->GetValue()?wxSTC_FIND_REGEXP:0) ;
if (scope<2) {
if (FindNext()) {
if (check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise(); combo_find->SetFocus();
}
} else {
mxMessageDialog(main_window,LANG1(FIND_NOT_FOUND,"La cadena \"<{1}>\" no se encontro.",last_search))
.Title(LANG(FIND_FIND_CAPTION,"Buscar")).IconInfo().Run();
Raise();
}
} else if (scope==2) {
if (FindInSources() && check_close->GetValue()) {
MyHide();
} else {
Raise();
combo_find->SetFocus();
}
} else {
switch (scope) {
case 3:
if (FindInProject(FT_SOURCE) && check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
break;
case 4:
if (FindInProject(FT_HEADER) && check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
break;
case 5:
if (FindInProject(FT_OTHER) && check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
break;
default:
if (FindInProject(FT_NULL) && check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
break;
}
}
}
void mxFindDialog::OnFindPrevButton(wxCommandEvent &event) {
num_results=0;
if (combo_find->GetValue().Len()==0) {
combo_find->SetFocus();
return;
}
if (combo_scope->GetSelection()>2) {
if (!project) {
mxMessageDialog(this,LANG(FIND_NO_PROJECT,"No hay ningun proyecto abierto actualmente."))
.Title(LANG(GENERAL_ERROR,"Error")).IconInfo().Run();
return;
}
} else {
if (!main_window->notebook_sources->GetPageCount()) {
mxMessageDialog(this,LANG(FIND_NO_FILE,"No hay ningun archivo abierto actualmente."))
.Title(LANG(GENERAL_ERROR,"Error")).IconInfo().Run();
return;
}
}
last_search = combo_find->GetValue();
if (last_search!=combo_find->GetString(combo_find->GetCount()-1)) {
combo_find->SetString(combo_find->GetCount()-1,last_search);
combo_find->Append(wxString());
}
int scope = combo_scope->GetSelection();
only_selection = (scope==0);
last_flags =
(check_case->GetValue()?wxSTC_FIND_MATCHCASE:0) |
(check_word->GetValue()?wxSTC_FIND_WHOLEWORD:0) |
(check_start->GetValue()?wxSTC_FIND_WORDSTART:0) |
(check_regexp->GetValue()?wxSTC_FIND_REGEXP:0) ;
if (scope<2) {
if (FindPrev()) {
if (check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
} else {
mxMessageDialog(main_window,LANG1(FIND_NOT_FOUND,"La cadena \"<{1}>\" no se encontro.",last_search))
.Title(LANG(FIND_FIND_CAPTION,"Buscar")).IconInfo().Run();
}
} else if (scope==2) {
if (FindInSources() && check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
} else {
switch (scope) {
case 3:
if (FindInProject(FT_SOURCE) && check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
break;
case 4:
if (FindInProject(FT_HEADER) && check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
break;
case 5:
if (FindInProject(FT_OTHER) && check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
break;
default:
if (FindInProject(FT_NULL) && check_close->GetValue()) {
MyHide(); /*main_window->Raise();*/
} else {
Raise();
combo_find->SetFocus();
}
break;
}
}
}
void mxFindDialog::OnReplaceButton(wxCommandEvent &event) {
if (combo_find->GetValue().Len()==0) {
combo_find->SetFocus();
return;
}
if (combo_scope->GetSelection()>2) {
mxMessageDialog(this,LANG1(FIND_CANT_REPLACE_IN,""
"No es posible realizar reemplazos en \"<{1}>\",\n"
"esta opcion aun no esta disponible.",combo_scope->GetValue()))
.Title(LANG(GENERAL_ERROR,"Error")).IconInfo().Run();
return;
}
if (!main_window->notebook_sources->GetPageCount()) {
mxMessageDialog(this,LANG(FIND_NO_FILE,"No hay ningun archivo abierto actualmente."))
.Title(LANG(GENERAL_ERROR,"Error")).IconInfo().Run();
return;
}
last_search = combo_find->GetValue();
if (last_search!=combo_find->GetString(combo_find->GetCount()-1)) {
combo_find->SetString(combo_find->GetCount()-1,last_search);
combo_find->Append(wxString());
}
last_replace = combo_replace->GetValue();
if (last_replace.Len() && last_replace!=combo_replace->GetString(combo_replace->GetCount()-1)) {
combo_replace->SetString(combo_replace->GetCount()-1,last_replace);
combo_replace->Append(wxString());
}
int scope = combo_scope->GetSelection();
only_selection = (scope==0);
last_flags =
(check_case->GetValue()?wxSTC_FIND_MATCHCASE:0) |
(check_word->GetValue()?wxSTC_FIND_WHOLEWORD:0) |
(check_start->GetValue()?wxSTC_FIND_WORDSTART:0) |
(check_regexp->GetValue()?wxSTC_FIND_REGEXP:0) ;
mxSource *source = (mxSource*)(main_window->notebook_sources->GetPage(main_window->notebook_sources->GetSelection()));
int f,t;
source->SetTargetStart(f=source->GetSelectionStart());
source->SetTargetEnd(t=source->GetSelectionEnd());
if (source->SearchInTarget(last_search)!=wxSTC_INVALID_POSITION && ( (source->GetTargetStart()==f && source->GetTargetEnd()==t) || (source->GetTargetStart()==t && source->GetTargetEnd()==f) ) ) {
if (last_flags&wxSTC_FIND_REGEXP)
source->ReplaceTargetRE(last_replace);
else
source->ReplaceTarget(last_replace);
source->SetSelection(source->GetTargetEnd(),source->GetTargetEnd());
}
FindNext();
}
void mxFindDialog::OnReplaceAllButton(wxCommandEvent &event) {
if (combo_find->GetValue().Len()==0) {
combo_find->SetFocus();
return;
}
if (combo_scope->GetSelection()>2) {
mxMessageDialog(this,LANG1(FIND_CANT_REPLACE_IN,""
"No es posible realizar reemplazos en \"<{1}>\",\n"
"esta opcion aun no esta disponible.",combo_scope->GetValue()))
.Title(LANG(GENERAL_ERROR,"Error")).IconInfo().Run();
return;
}
if (!main_window->notebook_sources->GetPageCount()) {
mxMessageDialog(this,LANG(FIND_NO_FILE,"No hay ningun archivo abierto actualmente."))
.Title(LANG(GENERAL_ERROR,"Error")).IconInfo().Run();
return;
}
last_search = combo_find->GetValue();
if (last_search!=combo_find->GetString(combo_find->GetCount()-1)) {
combo_find->SetString(combo_find->GetCount()-1,last_search);
combo_find->Append(wxString());
}
last_replace = combo_replace->GetValue();
if (last_replace.Len() && last_replace!=combo_replace->GetString(combo_replace->GetCount()-1)) {
combo_replace->SetString(combo_replace->GetCount()-1,last_replace);
combo_replace->Append(wxString());
}
int scope = combo_scope->GetSelection();
only_selection = (scope==0);
last_flags =
(check_case->GetValue()?wxSTC_FIND_MATCHCASE:0) |
(check_word->GetValue()?wxSTC_FIND_WHOLEWORD:0) |
(check_start->GetValue()?wxSTC_FIND_WORDSTART:0) |
(check_regexp->GetValue()?wxSTC_FIND_REGEXP:0) ;
mxSource *source = (mxSource*)(main_window->notebook_sources->GetPage(main_window->notebook_sources->GetSelection()));
int f,t;
if (only_selection) {
f=source->GetSelectionStart();
t=source->GetSelectionEnd();
if (t<f) {
int a=f;
f=t;
t=a;
}
source->SetSelection(f,t);
} else {
f=0;
t=source->GetLength();
}
int c=0; // contador de reemplazos
// primera busqueda
source->SetSearchFlags(last_flags);
source->SetTargetStart(f);
source->SetTargetEnd(t);
int ret = source->SearchInTarget(last_search);
mxSource::UndoActionGuard undo_action(source,false);
while (ret!=wxSTC_INVALID_POSITION) {
undo_action.Begin();
int l = source->GetTargetEnd()-source->GetTargetStart(); // para saber si cambio el largo de la seleccion despues de reemplazar
if (last_flags&wxSTC_FIND_REGEXP) // el remplazo propiamente dicho
source->ReplaceTargetRE(last_replace);
else
source->ReplaceTarget(last_replace);
t+=(source->GetTargetEnd()-source->GetTargetStart())-l; // actualizar el largo del bloque donde se busca
c++; // contar
// buscar otra vez
source->SetTargetStart(source->GetTargetEnd());
source->SetTargetEnd(t);
ret = source->SearchInTarget(last_search);
}
undo_action.End();
if (only_selection) source->SetSelection(f,t);
if (c==0) {
mxMessageDialog(this,LANG(FIND_NO_REPLACE_DONE,"No se realizo ningun reemplazo."))
.Title(LANG(FIND_REPLACE_CAPTION,"Reemplazar")).IconInfo().Run();
} else if (c==1) {
mxMessageDialog(this,LANG(FIND_ONE_REPLACE_DONE,"Se realizo un remplazo."))
.Title(LANG(FIND_REPLACE_CAPTION,"Reemplazar")).IconInfo().Run();
} else {
mxMessageDialog(this,LANG1(FIND_MANY_REPLACES,"Se realizaron <{1}> reemplazos.",wxString()<<c))
.Title(LANG(FIND_REPLACE_CAPTION,"Reemplazar")).IconInfo().Run();
}
Raise();
}
bool mxFindDialog::FindInSources() {
wxString res; int count=0;
for (unsigned int j=0;j<main_window->notebook_sources->GetPageCount();j++) {
count+=FindInSource((mxSource*)(main_window->notebook_sources->GetPage(j)),res);
}
return MultifindAux(count,res);
}
bool mxFindDialog::MultifindAux(int count, const wxString &res) {
if (count==0) {
mxMessageDialog(this,LANG(FIND_IN_FILES_NOT_FOUND,"No se encontraron coincidencias"))
.Title(LANG(FIND_IN_FILES_CAPTION,"Buscar en archivos")).IconWarning().Run();
return false;
} else {
wxString html("<HTML><HEAD><TITLE>");
html<<LANG(FIND_FIND_IN_FILES,"Buscar en archivos")<<"</TITLE></HEAD><BODY><B>";
html<<LANG2(FIND_IN_FILES_RESULT,"Resultados para la busqueda \"<I><{1}></I>\" (<{2}> resultados):",mxUT::ToHtml(last_search),wxString()<<count);
html<<"</B><BR><TABLE>"<<res<<"</TABLE><BR><BR></BODY></HTML>";
main_window->ShowInQuickHelpPanel(html);
return true;
}
}
/**
* @brief Auxiliar function for generaten the html (result for searchs in multiple files)
*
* This function will handle the results limit, if the count exceeds 500 only the first
* 500 will be shown (trying to show a huge html will virtually freeze the application).
*
* @param fname the full path to de filename, to be included in href in the link
* @param line the base 0 line number for the coincidence
* @param pos the base 0 position for the coincidence within that line
* @param len the len of the coincidence
* @param falias the friendly short filename to display in the text
* @param the_line the content of the line, to display trimmed and with the coincidence in bold
**/
wxString mxFindDialog::GetHtmlEntry(wxString fname, int line, int pos, int len, wxString falias, wxString the_line) {
wxString res;
if (++num_results==500) {
return wxString("<TR><TD><B>...</B></TD>")<<LANG(FIND_TOO_MANY_RESULTS,"demasiados resultados, solo se muestran los primeros 500")<<"<TD></TD></TR>";
} else if (num_results>500) return "";
res<<"<TR><TD><A href=\"gotolinepos:"<<fname<<":"<<line<<":"<<pos<<":"<<len<<"\">"<<falias<<": "<<LANG(FIND_LINE,"linea")<<" "<<line+1<<"</A></TD>";
res<<"<TD>"<<mxUT::ToHtml(the_line.Mid(0,pos).Trim(false))+"<B>"+mxUT::ToHtml(the_line.Mid(pos,len))+"</B>"+mxUT::ToHtml(the_line.Mid(pos+len).Trim(true))<<"</TD></TR>";
return res;
}
int mxFindDialog::FindInSource(mxSource *source,wxString &res) {
int count=0;
wxString file_name = source->GetFullPath();
wxString page_text = mxUT::ToHtml(source->page_text);
source->SetSearchFlags(last_flags);
int l = source->GetLength();
source->SetTargetStart(0);
source->SetTargetEnd(l);
int i = source->SearchInTarget(last_search);
while (i!=wxSTC_INVALID_POSITION) {
count++;
int line=source->LineFromPosition(i); i-=source->PositionFromLine(line);
res<<GetHtmlEntry(file_name,line,i,source->GetTargetEnd()-source->GetTargetStart(),page_text,source->GetLine(line));
source->SetTargetStart(source->GetTargetEnd());
source->SetTargetEnd(l);
i = source->SearchInTarget(last_search);
}
return count;
}
bool mxFindDialog::FindInProject(eFileType where) {
wxArrayString array;
project->GetFileList(array,where);
wxString res;
int p,count=0;
last_flags =
(check_case->GetValue()?wxSTC_FIND_MATCHCASE:0) |
(check_word->GetValue()?wxSTC_FIND_WHOLEWORD:0) ;
wxString what=last_search;
if (!(last_flags&wxSTC_FIND_MATCHCASE)) what.MakeUpper();
for (unsigned int i=0;i<array.GetCount();i++) {
mxSource *src=main_window->IsOpen(array[i]);
if (src) {
count+=FindInSource(src,res);
} else {
wxTextFile fil(array[i]);
if (fil.Exists()) {
fil.Open();
int l=0;
for ( wxString str_orig, str = fil.GetFirstLine(); !fil.Eof(); str = fil.GetNextLine() ) {
int ac=0; str_orig=str;
if (!(last_flags&wxSTC_FIND_MATCHCASE)) str.MakeUpper();
while (wxNOT_FOUND!=(p=str.Find(what))) {
bool is_ok=true;
if (last_flags&wxSTC_FIND_WHOLEWORD) {
is_ok = is_ok && !(p>0&&(mxSource::IsKeywordChar(str[p-1])));
is_ok = is_ok && !(p+what.Len()<str.Len()&&(mxSource::IsKeywordChar(str[p+what.Len()])));
}
if (is_ok) {
count++;
res<<GetHtmlEntry(array[i],l,ac+p,what.Len(),wxFileName(array[i]).GetFullName(),str_orig);
}
int todel=p+what.Len(); ac+=todel; str.Remove(0,todel);
}
l++;
}
fil.Close();
}
}
}
return MultifindAux(count,res);
}
void mxFindDialog::OnComboScope(wxCommandEvent &event) {
int scope = combo_scope->GetSelection();
check_regexp->Enable(scope<=2);
check_start->Enable(scope<=2);
check_nocomments->Enable(scope<=2);
next_button->Enable(scope<=2||project);
prev_button->Enable(scope<=2||project);
replace_button->Enable(scope<2);
replace_all_button->Enable(scope<2);
}
void mxFindDialog::OnHelpButton(wxCommandEvent &event) {
mxHelpWindow::ShowHelp("search_dialog.html");
}
void mxFindDialog::OnCancel(wxCommandEvent &event) {
MyHide(); /*main_window->Raise();*/
}
void mxFindDialog::OnClose(wxCloseEvent &event) {
MyHide();
}
void mxFindDialog::MyHide() {
Hide(); wxYield();
if (config->Init.autohiding_panels) main_window->Raise();
main_window->FocusToSource();
}
void mxFindDialog::FindAll (const wxString & what) {
combo_find->SetValue(what);
combo_scope->SetSelection(project?6:2);
check_case->SetValue(true);
check_regexp->SetValue(false);
check_word->SetValue(true);
wxCommandEvent evt;
OnFindNextButton(evt);
}
|
eeff17c70419eb82c8e5d8e90efd40f3869a1cb7 | baa5f93607ae921cb015633c984c090def12299b | /src/Ecs.hpp | 598d9b7966196534dd673cecffb92c56eb76e92f | [
"MIT"
] | permissive | tkln/TemplateECS | 5a54f8a2058c486897af921d93b41fc2f581eddf | bd04001a7e1d1656a580db0569ab145b9b206880 | refs/heads/master | 2020-05-12T23:51:45.231178 | 2019-04-10T22:52:07 | 2019-04-10T22:52:07 | 181,567,275 | 0 | 0 | null | 2019-04-15T21:18:04 | 2019-04-15T21:18:03 | null | UTF-8 | C++ | false | false | 6,961 | hpp | Ecs.hpp | //
// Created by Lehdari on 2.4.2018.
//
#ifndef TEMPLATEECS_ECS_HPP
#define TEMPLATEECS_ECS_HPP
#include "Types.hpp"
#include "System.hpp"
#include <vector>
#include <functional>
#include <tuple>
/// Use this in component header files
#define DECLARE_COMPONENT_TEMPLATES(COMPONENT)\
extern template uint64_t Ecs::typeId<COMPONENT>();
/// Use this in component source files
#define DEFINE_COMPONENT_TEMPLATES(COMPONENT)\
template uint64_t Ecs::typeId<COMPONENT>();
class Ecs {
public:
Ecs();
Ecs(const Ecs&) = delete;
Ecs(Ecs&&) = delete;
~Ecs();
Ecs& operator=(const Ecs&) = delete;
Ecs& operator=(Ecs&&) = delete;
/// Add component
template <typename T_Component>
void addComponent(const EntityId& eId, const T_Component& component);
/// Get component
template <typename T_Component>
T_Component* getComponent(const EntityId& eId);
/// Remove component
template <typename T_Component>
void removeComponent(const EntityId& eId);
/// Run system
template <typename T_DerivedSystem, typename... T_Components>
void runSystem(System<T_DerivedSystem, T_Components...>& system);
private:
/// Wrapper type for components
template <typename T_Component>
struct ComponentWrapper {
EntityId eId;
T_Component component;
ComponentWrapper(const EntityId& eId, const T_Component& c = T_Component()) :
eId(eId), component(c) {}
};
/// TypeId system
static uint64_t typeIdCounter;
template <typename T_Component>
static uint64_t typeId();
/// Component vector handling stuff
template <typename T_Component>
using ComponentVector = typename std::vector<ComponentWrapper<T_Component>>;
template <typename T_Component>
using ComponentIterator = typename ComponentVector<T_Component>::iterator;
template <typename T_Component>
struct IteratorWrapper {
ComponentIterator<T_Component> it;
ComponentIterator<T_Component> end;
IteratorWrapper(const ComponentIterator<T_Component>& it,
const ComponentIterator<T_Component>& end) :
it(it), end(end)
{}
bool isValid();
bool increase(const EntityId& eId);
};
template <typename T_Component>
ComponentVector<T_Component>& accessComponents();
template <typename T_Component>
bool findComponent(ComponentVector<T_Component>& cVector,
ComponentIterator<T_Component>& it,
const EntityId& eId);
template <typename T_Component>
void deleteComponents(uint64_t cVectorId);
template <typename... T_Components>
static bool checkIterators(IteratorWrapper<T_Components>&... itWrappers);
template <typename... T_Components>
static bool increaseIterators(const EntityId& eId, IteratorWrapper<T_Components>&... itWrappers);
/// Entity ID handling stuff
inline void checkEntityId(const EntityId& eId);
/// Component vector handling data structures
std::vector<void*> _components;
std::vector<std::function<void()>> _componentDeleters;
/// Entity ID storage
std::vector<EntityId> _entityIds;
};
/// Public member functions
template <typename T_Component>
void Ecs::addComponent(const EntityId& eId, const T_Component& component)
{
checkEntityId(eId);
auto& v = accessComponents<T_Component>();
ComponentIterator<T_Component> it;
if (findComponent(v, it, eId))
return;
else
v.emplace(it, eId, component);
}
template<typename T_Component>
T_Component* Ecs::getComponent(const EntityId& eId)
{
auto& v = accessComponents<T_Component>();
ComponentIterator<T_Component> it;
if (findComponent(v, it, eId))
return &(it->component);
else
return nullptr;
}
template<typename T_Component>
void Ecs::removeComponent(const EntityId& eId)
{
auto& v = accessComponents<T_Component>();
ComponentIterator<T_Component> it;
if (findComponent(v, it, eId))
v.erase(it);
}
template <typename T_DerivedSystem, typename... T_Components>
void Ecs::runSystem(System<T_DerivedSystem, T_Components...>& system)
{
auto cIters = std::make_tuple(
IteratorWrapper<T_Components>(accessComponents<T_Components>().begin(),
accessComponents<T_Components>().end())...);
if (!checkIterators(std::get<IteratorWrapper<T_Components>>(cIters)...))
return;
for (auto eId : _entityIds) {
if (increaseIterators<T_Components...>(eId, std::get<IteratorWrapper<T_Components>>(cIters)...))
system(eId, std::get<IteratorWrapper<T_Components>>(cIters).it->component...);
}
}
/// Private member functions
template <typename T_Component>
uint64_t Ecs::typeId()
{
static uint64_t tId = typeIdCounter++;
return tId;
}
template<typename T_Component>
Ecs::ComponentVector<T_Component>& Ecs::accessComponents()
{
auto tId = typeId<T_Component>();
if (_components.size() <= tId)
_components.resize(tId+1, nullptr);
if (_components[tId] == nullptr) {
_components[tId] = new ComponentVector<T_Component>;
_componentDeleters.push_back(
std::bind(&Ecs::deleteComponents<T_Component>, this, (uint64_t)tId));
}
return *static_cast<ComponentVector<T_Component>*>(_components[tId]);
}
template<typename T_Component>
bool Ecs::findComponent(Ecs::ComponentVector<T_Component>& cVector,
ComponentIterator<T_Component>& it,
const EntityId& eId)
{
// TODO implement binary tree search instead of linear one
it = cVector.begin();
for (; it != cVector.end() && it->eId < eId; ++it);
if (it == cVector.end() || it->eId > eId)
return false;
return true;
}
template<typename T_Component>
void Ecs::deleteComponents(uint64_t cVectorId) {
delete static_cast<ComponentVector<T_Component>*>(_components.at(cVectorId));
}
template<typename T_Component>
bool Ecs::IteratorWrapper<T_Component>::isValid()
{
return it != end;
}
template<typename T_Component>
bool Ecs::IteratorWrapper<T_Component>::increase(const EntityId& eId)
{
while (it != end && it->eId < eId)
++it;
return (it->eId > eId || it == end) ? false : true;
}
template<typename... T_Components>
bool Ecs::checkIterators(IteratorWrapper<T_Components>&... itWrappers)
{
return (itWrappers.isValid() && ...);
}
template<typename... T_Components>
bool Ecs::increaseIterators(const EntityId& eId, IteratorWrapper<T_Components>&... itWrappers)
{
return (itWrappers.increase(eId) && ...);
}
void Ecs::checkEntityId(const EntityId& eId)
{
// TODO implement binary tree search instead of linear one
auto it = _entityIds.begin();
for (; it != _entityIds.end() && *it < eId; ++it);
if (it == _entityIds.end() || *it > eId)
it = _entityIds.emplace(it, eId);
}
#endif //TEMPLATEECS_ECS_HPP
|
3dd651f0a4758c4f519d414f8b4bf516809859d1 | c013714b28ab69d3946ee68f00ce47215c058f4f | /AcaciaNI/src/Acacia.cpp | a792cd81255f1b9e7d7ff19d43a94b957ab2613e | [] | no_license | gaborpapp/apps | f0195bfd41c30a6f7ab1430bbc0ffda35fbc4ed5 | 82d06ec9009f81440abc34f996da5ba64583750c | refs/heads/master | 2020-06-02T07:59:23.172058 | 2014-09-17T16:11:27 | 2014-09-17T16:11:27 | 1,826,410 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,722 | cpp | Acacia.cpp | /*
Copyright (C) 2012 Gabor Papp
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/>.
*/
#include "cinder/Cinder.h"
#include "cinder/app/AppBasic.h"
#include "cinder/gl/Texture.h"
#include "cinder/ImageIo.h"
#include "cinder/Rand.h"
#include "cinder/Utilities.h"
#include "cinder/Filesystem.h"
#include "cinder/Font.h"
#include "cinder/ip/Resize.h"
#include "cinder/Rect.h"
#include "ciMsaFluidSolver.h"
#include "ciMsaFluidDrawerGl.h"
#include "CinderOpenCV.h"
#include "PParams.h"
#include "NI.h"
#include "Leaves.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class Acacia : public ci::app::AppBasic
{
public:
void prepareSettings(Settings *settings);
void setup();
void shutdown();
void resize(ResizeEvent event);
void keyDown(KeyEvent event);
void mouseDown(MouseEvent event);
void mouseDrag(MouseEvent event);
void update();
void draw();
private:
ci::params::PInterfaceGl mParams;
int mMaxLeaves;
int mLeafCount;
float mAging;
float mGravity;
float mVelThres;
float mVelDiv;
bool mAddLeaves;
bool mDrawAtmosphere;
bool mDrawCamera;
bool mDrawFeatures;
void clearLeaves();
vector< gl::Texture > loadTextures( const fs::path &relativeDir );
vector< gl::Texture > mBWTextures;
ciMsaFluidSolver mFluidSolver;
ciMsaFluidDrawerGl mFluidDrawer;
static const int sFluidSizeX;
void addToFluid( Vec2f pos, Vec2f vel, bool addColor, bool addForce );
LeafManager mLeaves;
Vec2i mPrevMouse;
OpenNI mNI;
gl::Texture mOptFlowTexture;
void chooseFeatures( cv::Mat currentFrame );
void trackFeatures( cv::Mat currentFrame );
cv::Mat mPrevFrame;
vector<cv::Point2f> mPrevFeatures, mFeatures;
vector<uint8_t> mFeatureStatuses;
static const int MAX_FEATURES = 128;
#define CAMERA_WIDTH 160
#define CAMERA_HEIGHT 120
static const Vec2f CAMERA_SIZE; //( CAMERA_WIDTH, CAMERA_HEIGHT );
ci::Font mFont;
};
const int Acacia::sFluidSizeX = 128;
const Vec2f Acacia::CAMERA_SIZE( CAMERA_WIDTH, CAMERA_HEIGHT );
void Acacia::prepareSettings(Settings *settings)
{
settings->setWindowSize(640, 480);
}
void Acacia::setup()
{
// params
string paramsXml = getResourcePath().string() + "/params.xml";
params::PInterfaceGl::load( paramsXml );
mParams = params::PInterfaceGl("Japan akac", Vec2i(200, 300));
mParams.addPersistentSizeAndPosition();
mParams.addPersistentParam( "Max leaves", &mMaxLeaves, 1000, " min=100, max=4000, step=100 " );
mLeafCount = 0;
mParams.addParam( "Leaf count", &mLeafCount, "", true );
mParams.addPersistentParam( "Leaf Aging", &mAging, 0.995, " min=0, max=1, step=.005 " );
mParams.addPersistentParam( "Gravity", &mGravity, 0.8, " min=0, max=10, step=.25 " );
mParams.addPersistentParam( "Add leaves", &mAddLeaves, true );
mParams.addPersistentParam( "Velocity threshold", &mVelThres, 5., " min=0, max=50, step=.1 " );
mParams.addPersistentParam( "Velocity divisor", &mVelDiv, 5, " min=1, max=50 " );
mParams.addButton( "Clear leaves", std::bind(&Acacia::clearLeaves, this), " key=SPACE ");
mParams.addSeparator();
mParams.addPersistentParam( "Atmosphere", &mDrawAtmosphere, false );
mParams.addPersistentParam( "Camera", &mDrawCamera, false );
mParams.addPersistentParam( "Features", &mDrawFeatures, false );
mBWTextures = loadTextures( "bw" );
// fluid
mFluidSolver.setup( sFluidSizeX, sFluidSizeX );
mFluidSolver.enableRGB(false).setFadeSpeed(0.002).setDeltaT(.5).setVisc(0.00015).setColorDiffusion(0);
mFluidSolver.setWrap( false, true );
mFluidDrawer.setup( &mFluidSolver );
mLeaves.setFluidSolver( &mFluidSolver );
// OpenNI
try
{
mNI = OpenNI( OpenNI::Device() );
/*
string path = getAppPath().string();
#ifdef CINDER_MAC
path += "/../";
#endif
path += "rec-12022610062000.oni";
mNI = OpenNI( path );
*/
}
catch (...)
{
console() << "Could not open Kinect" << endl;
quit();
}
mNI.setMirrored( false );
mNI.setDepthAligned();
//mNI.setVideoInfrared();
mNI.start();
mFont = Font("Lucida Grande", 12.0f);
gl::enableAlphaBlending();
gl::disableDepthWrite();
gl::disableDepthRead();
gl::disableVerticalSync();
}
void Acacia::shutdown()
{
params::PInterfaceGl::save();
}
void Acacia::clearLeaves()
{
mLeaves.clear();
}
vector< gl::Texture > Acacia::loadTextures( const fs::path &relativeDir )
{
vector< gl::Texture > textures;
fs::path dataPath = getAssetPath( relativeDir );
for (fs::directory_iterator it( dataPath ); it != fs::directory_iterator(); ++it)
{
if (fs::is_regular_file(*it) && (it->path().extension().string() == ".png"))
{
console() << relativeDir.string() + "/" + it->path().filename().string() << endl;
gl::Texture t = loadImage( loadAsset( relativeDir / it->path().filename() ) );
textures.push_back( t );
}
}
return textures;
}
void Acacia::resize(ResizeEvent event)
{
mFluidSolver.setSize( sFluidSizeX, sFluidSizeX / getWindowAspectRatio() );
mFluidDrawer.setup( &mFluidSolver );
mLeaves.setWindowSize( event.getSize() );
}
void Acacia::addToFluid( Vec2f pos, Vec2f vel, bool addColor, bool addForce )
{
// balance the x and y components of speed with the screen aspect ratio
float speed = vel.x * vel.x +
vel.y * vel.y * getWindowAspectRatio() * getWindowAspectRatio();
if ( speed > 0 )
{
pos.x = constrain( pos.x, 0.0f, 1.0f );
pos.y = constrain( pos.y, 0.0f, 1.0f );
const float colorMult = 100;
const float velocityMult = 30;
if ( addColor )
{
//Color drawColor( CM_HSV, ( getElapsedFrames() % 360 ) / 360.0f, 1, 1 );
Color drawColor( Color::white() );
mFluidSolver.addColorAtPos( pos, drawColor * colorMult );
mLeaves.addLeaf( pos * Vec2f( getWindowSize() ),
mBWTextures[ Rand::randInt( mBWTextures.size() ) ] );
}
if ( addForce )
mFluidSolver.addForceAtPos( pos, vel * velocityMult );
}
}
void Acacia::chooseFeatures( cv::Mat currentFrame )
{
cv::goodFeaturesToTrack( currentFrame, mFeatures, MAX_FEATURES, 0.005, 3.0 );
}
void Acacia::trackFeatures( cv::Mat currentFrame )
{
vector<float> errors;
mPrevFeatures = mFeatures;
cv::calcOpticalFlowPyrLK( mPrevFrame, currentFrame, mPrevFeatures, mFeatures, mFeatureStatuses, errors );
}
void Acacia::update()
{
mFluidSolver.update();
mLeaves.setGravity( mGravity );
mLeaves.setMaximum( mMaxLeaves );
mLeaves.setAging( mAging );
mLeaves.update( getElapsedSeconds() );
mLeafCount = mLeaves.getCount();
if (mNI.checkNewDepthFrame())
{
Surface surface( Channel8u( mNI.getVideoImage() ) );
Surface smallSurface( CAMERA_WIDTH, CAMERA_HEIGHT, false );
ip::resize( surface, &smallSurface );
mOptFlowTexture = gl::Texture( smallSurface );
cv::Mat currentFrame( toOcv( Channel( smallSurface ) ) );
if ( mPrevFrame.data )
{
// pick new features once every 30 frames, or the first frame
if ( mFeatures.empty() || getElapsedFrames() % 30 == 0 )
chooseFeatures( mPrevFrame );
trackFeatures( currentFrame );
}
mPrevFrame = currentFrame;
}
}
void Acacia::draw()
{
gl::clear(Color(0, 0, 0));
gl::setMatricesWindow( getWindowSize() );
if ( mDrawCamera && mOptFlowTexture )
{
gl::color( ColorA( 1, 1, 1, .3 ) );
gl::draw( mOptFlowTexture, getWindowBounds() );
}
if (mDrawAtmosphere)
{
gl::color( Color::white() );
mFluidDrawer.draw( 0, 0, getWindowWidth(), getWindowHeight() );
}
mLeaves.draw();
if ( !mPrevFeatures.empty() )
{
RectMapping camera2Screen( Rectf(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT),
getWindowBounds() );
if ( mDrawFeatures )
{
gl::color( Color::white() );
for ( vector<cv::Point2f>::const_iterator featureIt = mFeatures.begin
(); featureIt != mFeatures.end(); ++featureIt )
gl::drawStrokedCircle( camera2Screen.map( fromOcv( *featureIt ) ), 2 );
}
for ( size_t idx = 0; idx < mFeatures.size(); ++idx )
{
if( mFeatureStatuses[idx] )
{
Vec2f p0 = fromOcv( mFeatures[idx] );
Vec2f p1 = fromOcv( mPrevFeatures[idx] );
if ( p0.distance( p1 ) > mVelThres )
{
addToFluid( p0 / CAMERA_SIZE,
(p0 - p1) / mVelDiv / CAMERA_SIZE,
mAddLeaves, true );
gl::color( Color( 1, 0, 0 ) );
}
else
gl::color( Color::white() );
if ( mDrawFeatures )
{
gl::drawLine( camera2Screen.map( p0 ), camera2Screen.map( p1 ) );
}
}
}
}
gl::drawString("FPS: " + toString(getAverageFps()), Vec2f(10.0f, 10.0f),
Color::white(), mFont);
params::PInterfaceGl::draw();
}
void Acacia::keyDown(KeyEvent event)
{
if (event.getChar() == 'f')
setFullScreen(!isFullScreen());
if (event.getCode() == KeyEvent::KEY_ESCAPE)
quit();
}
void Acacia::mouseDrag(MouseEvent event)
{
Vec2f mouseNorm = Vec2f( event.getPos() ) / getWindowSize();
Vec2f mouseVel = Vec2f( event.getPos() - mPrevMouse ) / getWindowSize();
addToFluid( mouseNorm, mouseVel, event.isLeftDown(), true );
mPrevMouse = event.getPos();
}
void Acacia::mouseDown(MouseEvent event)
{
Vec2f mouseNorm = Vec2f( event.getPos() ) / getWindowSize();
Vec2f mouseVel = Vec2f( event.getPos() - mPrevMouse ) / getWindowSize();
addToFluid( mouseNorm, mouseVel, false, true );
mPrevMouse = event.getPos();
}
CINDER_APP_BASIC(Acacia, RendererGl( RendererGl::AA_MSAA_4 ) )
|
cda45a2f76fcf770043e43a452978e7aa25ba0c2 | 395f5870ba1a3d428a3294cf166d63891b3346e0 | /robot2005/src/simulator/simulatorRobot.cpp | d64acded3c39a938a4b94c90e0abd38db95a1ab1 | [] | no_license | BackupTheBerlios/robotm6 | 08a57f8cbb9100734c85ef0e444260f16e7efa6f | dc26ad2d1f3575c016c6c9104bd49ec6fb4d812d | refs/heads/master | 2021-01-01T19:25:40.673078 | 2005-06-03T21:18:04 | 2005-06-03T21:18:04 | 39,962,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,584 | cpp | simulatorRobot.cpp | /**
* @file simulatorServer.h
*
* @author Laurent Saint-Marcel
*
* Systeme de simulation du robot et de son environnement
*/
#include "simulator.h"
#include "simulatorRobot.h"
#include "simulatorGrsBall.h"
#include "simulatorSkittle.h"
SimulatorRobot::SimulatorRobot() :
RobotBase("Simulated robot", CLASS_SIMULATOR),
name_("NoName"), weight_(SIMU_WEIGHT_MEDIUM), model_(ROBOT_MODEL_ATTACK),
brick_(false), D_(300), motorK_(0.004),
jackin_(false), emergencyStop_(false), lcdBtnYes_(false), lcdBtnNo_(false),
lcdMessage_("Booting\nPlease wait..."),
realPos_(), estimatedPos_(),
speedLeft_(0), speedRight_(0),
pwmLeft_(0), pwmRight_(0),
motorLeft_(0), motorRight_(0),
needSendDisplayInfo_(false),
matchStatus_(SIMU_STATUS_WAIT_START),
motorLeftOld_(0), motorRightOld_(0),
realPosOld_(),
odomK_(1), odomSpeedL_(1), odomSpeedR_(1), odomLeft_(0), odomRight_(0),
motorSpeedL_(-1), motorSpeedR_(-1),
simuMotorNoise_(false), simuPosFirst_(true), isValid_(true), isDead_(0)
{
setBorderRobotAttack();
}
SimulatorRobot::~SimulatorRobot()
{
}
void SimulatorRobot::updateOdometer()
{
if (dist(realPosOld_.center, realPos_.center) < 100) {
double simuSpeed = SimulatorCL::instance()->getSimulationSpeed();
Point odoLeftOld=odomLeftPt_, odoLeft=odomLeftPt_;
Point odoRightOld=odomRightPt_, odoRight=odomRightPt_;
Geometry2D::convertToOrthogonalCoord(realPos_.center, realPos_.direction,
odoLeft);
Geometry2D::convertToOrthogonalCoord(realPos_.center, realPos_.direction,
odoRight);
Geometry2D::convertToOrthogonalCoord(realPosOld_.center, realPosOld_.direction,
odoLeftOld);
Geometry2D::convertToOrthogonalCoord(realPosOld_.center, realPosOld_.direction,
odoRightOld);
odomLeft_ += (CoderPosition)(odomSpeedL_*simuSpeed*dist(odoLeft, odoLeftOld)/odomK_*(((na2PI(dir(odoLeftOld, odoLeft)-realPos_.direction,-M_PI/2))<(M_PI/2))?1:-1));
odomRight_ += (CoderPosition)(odomSpeedR_*simuSpeed*dist(odoRight, odoRightOld)/odomK_*(((na2PI(dir(odoRightOld, odoRight)-realPos_.direction,-M_PI/2))<(M_PI/2))?1:-1));
if (odomLeft_<SHRT_MIN) odomLeft_+=USHRT_MAX;
if (odomLeft_>SHRT_MAX) odomLeft_-=USHRT_MAX;
if (odomRight_<SHRT_MIN) odomRight_+=USHRT_MAX;
if (odomRight_>SHRT_MAX) odomRight_-=USHRT_MAX;
}
}
void SimulatorRobot::updatePosition()
{
if (isDead_) return;
if (brick_) return;
// sauve l'etat courant au cas ou la nouvelle position soit invalide
realPosOld_ = realPos_;
double simuSpeed = SimulatorCL::instance()->getSimulationSpeed();
// Calcule de la position des odometres
motorLeftOld_ = motorLeft_;
motorRightOld_ = motorRight_;
// calcul variation des deplacements des moteurs
motorRight_+= (int)((simuSpeed*motorSpeedR_*speedRight_
+(simuMotorNoise_?(10*rand()/(RAND_MAX+1.0)):0)));
motorLeft_ += (int)((simuSpeed*motorSpeedL_*speedLeft_
+(simuMotorNoise_?(10*rand()/(RAND_MAX+1.0)):0)));
double deltaRight=0, deltaLeft=0;
double deltaTheta=0, deltaSum=0;
double KRight = sign(motorSpeedR_)*motorK_*motorRight_;
double KLeft = sign(motorSpeedL_)*motorK_*motorLeft_;
if (simuPosFirst_) {
motorRightOld_ = motorRight_;
motorLeftOld_ = motorLeft_;
simuPosFirst_ = false;
} else {
if (motorLeft_ - motorLeftOld_ > SHRT_MAX) { // short max =unsigned short max /2
motorLeftOld_ += USHRT_MAX; // unsigned short max
} else if (motorLeft_ - motorLeftOld_ < SHRT_MIN) {
motorLeftOld_ -= USHRT_MAX;
}
if (motorRight_ - motorRightOld_ > SHRT_MAX) { // short max =unsigned short max /2
motorRightOld_ += USHRT_MAX; // unsigned short max
} else if (motorRight_ - motorRightOld_ < SHRT_MIN) {
motorRightOld_ -= USHRT_MAX;
}
}
deltaRight = (KRight - sign(motorSpeedR_)*motorK_*motorRightOld_);
deltaLeft = (KLeft - sign(motorSpeedL_)*motorK_*motorLeftOld_);
deltaSum = (deltaRight + deltaLeft)/2.;
// calcul position reelle
Radian oldDir = realPos_.direction;
deltaTheta = (deltaRight-deltaLeft)/(D_);
realPos_.direction += deltaTheta;
if (fabs(deltaTheta) > 0.0001) {
realPos_.center.x += deltaSum *
(sin(realPos_.direction)-sin(oldDir))/deltaTheta;
realPos_.center.y += -deltaSum *
(cos(realPos_.direction)-cos(oldDir))/deltaTheta;
} else {
deltaTheta = (realPos_.direction +oldDir)/2.;
realPos_.center.x += deltaSum * cos(deltaTheta);
realPos_.center.y += deltaSum * sin(deltaTheta);
}
// calcul position estimee // ne tient pas compte des collisions
oldDir = estimatedPos_.direction;
deltaTheta = (deltaRight-deltaLeft)/(D_);
estimatedPos_.direction += deltaTheta;
if (fabs(deltaTheta) > 0.0001) {
estimatedPos_.center.x += deltaSum *
(sin(estimatedPos_.direction)-sin(oldDir))/deltaTheta;
estimatedPos_.center.y += -deltaSum *
(cos(estimatedPos_.direction)-cos(oldDir))/deltaTheta;
} else {
deltaTheta = (estimatedPos_.direction +oldDir)/2.;
estimatedPos_.center.x += deltaSum * cos(deltaTheta);
estimatedPos_.center.y += deltaSum * sin(deltaTheta);
}
/* printf("%lf %lf %d %d %lf %lf %lf\n", motorK_, D_,
(int)motorRight_, (int)speedRight_, KRight,
deltaRight, realPos_.center.x);
*/
isValid_=true;
setRealPos(realPos_);
}
#define SIMU_PWM_LIMIT 116
void SimulatorRobot::setNewPositionValid()
{
if (isDead_) return;
if (brick_) return;
if (!isValid_) {
realPos_ = realPosOld_;
pwmLeft_=(MotorPWM)(1.5*pwmLeft_);
pwmRight_=(MotorPWM)(1.5*pwmRight_);
} else {
pwmLeft_ =(MotorPWM)(100*speedLeft_ /max(0.2, (double)fabs(motorLeft_ - motorLeftOld_ )/motorK_));
pwmRight_=(MotorPWM)(100*speedRight_/max(0.2, (double)fabs(motorRight_ - motorRightOld_)/motorK_));
}
if (pwmLeft_>SIMU_PWM_LIMIT) pwmLeft_=SIMU_PWM_LIMIT;
else if (pwmLeft_<-SIMU_PWM_LIMIT) pwmLeft_=-SIMU_PWM_LIMIT;
if (pwmRight_>SIMU_PWM_LIMIT) pwmRight_=SIMU_PWM_LIMIT;
else if (pwmRight_<-SIMU_PWM_LIMIT) pwmRight_=-SIMU_PWM_LIMIT;
}
void SimulatorRobot::setRealPos(Position const& pos) {
realPos_=pos;
convertBorderToOrthogonal(realPos_);
}
void SimulatorRobot::checkPosAndWall()
{
if (isDead_) return;
Polygon gameArea(SimulatorCL::instance()->getWallPts(), SIMU_WALL_BORDER_PTS_NBR);
if (!Geometry2D::isPointInPolygon(gameArea, realPos_.center)) {
isValid_ = false;
setRealPos(realPosOld_);
return;
}
Point intersection;
Point* wallPts=SimulatorCL::instance()->getWallPts();
for(unsigned int i=0;i!=SIMU_WALL_BORDER_PTS_NBR;i++) {
Segment wallBorder(wallPts[i], wallPts[((i+1)%SIMU_WALL_BORDER_PTS_NBR)]);
if(checkSegmentIntersectionWithRobot(wallBorder, 30, intersection)){
isValid_ = false;
setRealPos(realPosOld_);
return;
}
}
}
void SimulatorRobot::checkPosAndBridge(BridgePosition const& bridge)
{
if (isDead_) return;
// si on est dans la riviere on est mort!
if (SimulatorCL::instance()->isInRiver(wheelRealPts_[0]) ||
SimulatorCL::instance()->isInRiver(wheelRealPts_[1]) ||
(SimulatorCL::instance()->isInRiver(wheelRealPts_[2]) &&
SimulatorCL::instance()->isInRiver(wheelRealPts_[3]))) {
isValid_ = false;
if (SimulatorCL::instance()->isInRiver(wheelRealPts_[0])) {
isDead_=1;
} else if (SimulatorCL::instance()->isInRiver(wheelRealPts_[1])) {
isDead_=2;
} else isDead_=3;
needSendDisplayInfo_=true;
setRealPos(realPosOld_);
return;
}
// collision avec les murs
if (!isValid_) return;
Point intersection;
Point* bridgePts=SimulatorCL::instance()->getBridgePts();
for(unsigned int i=0;i+1<SIMU_BRIDGE_BORDER_PTS_NBR;i+=2) {
Segment bridgeBorder(bridgePts[i], bridgePts[i+1]);
if(checkSegmentIntersectionWithRobot(bridgeBorder, 30, intersection)){
/* printf("Intersection:");
intersection.print();
bridgePts[i].print();
bridgePts[i+1].print();
*/
isValid_ = false;
setRealPos(realPosOld_);
return;
}
}
// pas besoin de detecter la collision avec les murs riviere car ils sont trop bas
}
void SimulatorRobot::checkPosAndOtherRobot(SimulatorRobot* other)
{
}
void SimulatorRobot::checkPosAndGRSBall(SimulatorGrsBall* ball)
{
if (!ball || !ball->ball_) return;
Circle circle(ball->ball_->center, BALLE_GRS_RAYON);
Point intersection;
if (checkCircleIntersectionWithRobot(circle, BALLE_GRS_RAYON, intersection)) {
Point newCenter = intersection+(ball->ball_->center-intersection)* BALLE_GRS_RAYON/dist(ball->ball_->center,intersection);
ball->centerAfterCollision(newCenter);
}
}
void SimulatorRobot::checkPosAndSkittle(SimulatorSkittle* skittle)
{
if (!skittle || !skittle->skittle_ || realPos_.center.x < 10) return;
// meme si la quille est tombee on la gere comme si elle etait ronde, c'est plus facile!
Circle circle(skittle->skittle_->center, QUILLE_RAYON);
if (skittle->skittle_->status == SKITTLE_DOWN) {
circle.radius=2*QUILLE_RAYON;
}
/*
Point intersection;
if (checkCircleIntersectionWithRobot(circle, 80, intersection)) {
Point newCenter = intersection+(skittle->newPos_.center-intersection)* QUILLE_RAYON/dist(skittle->newPos_.center,intersection);
skittle->centerAfterCollision(newCenter);
}
*/
if (Geometry2D:: isCircleInPolygon(borderPol_[0], circle) ||
Geometry2D:: isCircleInPolygon(borderPol_[1], circle) ||
Geometry2D:: isCircleInPolygon(borderPol_[2], circle)) {
Point newCenter = realPos_.center+(skittle->newPos_.center-realPos_.center)*400./dist(skittle->newPos_.center, realPos_.center);
skittle->centerAfterCollision(newCenter);
}
}
bool SimulatorRobot::getIntersection(Point const& captor,
Segment const& captorVision,
Millimeter zPosCaptor,
Point& intersectionPt)
{
Point inter;
Millimeter minDistance=INFINITE_DIST;
if (zPosCaptor>70) {
for(unsigned int i=0;i!=4;i++) {
Segment robotBorder(borderRealPts_[8+i], borderRealPts_[8+((i+1)%4)]);
if(Geometry2D::getSegmentsIntersection(robotBorder, captorVision, inter)) {
Millimeter distance=dist(inter, captor);
if (minDistance<0 || minDistance>distance) {
minDistance = distance;
intersectionPt = inter;
}
}
}
} else {
for(unsigned int i=0;i!=4;i++) {
Segment robotBorder(borderRealPts_[i], borderRealPts_[(i+1)%4]);
if(Geometry2D::getSegmentsIntersection(robotBorder, captorVision, inter)) {
Millimeter distance=dist(inter, captor);
if (minDistance<0 || minDistance>distance) {
minDistance = distance;
intersectionPt = inter;
}
}
}
for(unsigned int i=0;i!=4;i++) {
Segment robotBorder(borderRealPts_[4+i], borderRealPts_[4+((i+1)%4)]);
if(Geometry2D::getSegmentsIntersection(robotBorder, captorVision, inter)) {
Millimeter distance=dist(inter, captor);
if (minDistance<0 || minDistance>distance) {
minDistance = distance;
intersectionPt = inter;
}
}
}
}
return (minDistance>0);
}
bool SimulatorRobot::checkSegmentIntersectionWithRobot(Segment const& seg,
Millimeter z,
Point& intersectionPt)
{
if (z>60) {
for(unsigned int i=0;i!=4;i++) {
Segment robotBorder(borderRealPts_[8+i], borderRealPts_[8+((i+1)%4)]);
if(Geometry2D::getSegmentsIntersection(robotBorder, seg, intersectionPt)) return true;
}
} else {
for(unsigned int i=0;i!=4;i++) {
Segment robotBorder(borderRealPts_[i], borderRealPts_[(i+1)%4]);
if(Geometry2D::getSegmentsIntersection(robotBorder, seg, intersectionPt)) return true;
}
for(unsigned int i=0;i!=4;i++) {
Segment robotBorder(borderRealPts_[4+i], borderRealPts_[4+((i+1)%4)]);
if(Geometry2D::getSegmentsIntersection(robotBorder, seg, intersectionPt)) return true;
}
}
return false;
}
bool SimulatorRobot::checkCircleIntersectionWithRobot(Circle const& circle,
Millimeter z,
Point& intersectionPt)
{
Point intersectionPt1;
Point intersectionPt2;
int npts=0;
if (z>60) {
for(unsigned int i=0;i!=4;i++) {
Segment robotBorder(borderRealPts_[8+i], borderRealPts_[8+((i+1)%4)]);
npts=Geometry2D::getSegmentCircleIntersection(robotBorder, circle,
intersectionPt1, intersectionPt2);
if (npts==1) {
intersectionPt = intersectionPt1;
return true;
} else if (npts==2) {
intersectionPt = (intersectionPt1+intersectionPt2)/2.;
return true;
}
}
} else {
for(unsigned int i=0;i!=4;i++) {
Segment robotBorder(borderRealPts_[i], borderRealPts_[(i+1)%4]);
npts=Geometry2D::getSegmentCircleIntersection(robotBorder, circle,
intersectionPt1, intersectionPt2);
if (npts==1) {
intersectionPt = intersectionPt1;
return true;
} else if (npts==2) {
intersectionPt = (intersectionPt1+intersectionPt2)/2.;
return true;
}
}
for(unsigned int i=0;i!=4;i++) {
Segment robotBorder(borderRealPts_[4+i], borderRealPts_[4+((i+1)%4)]);
npts=Geometry2D::getSegmentCircleIntersection(robotBorder, circle,
intersectionPt1, intersectionPt2);
if (npts==1) {
intersectionPt = intersectionPt1;
return true;
} else if (npts==2) {
intersectionPt = (intersectionPt1+intersectionPt2)/2.;
return true;
}
}
}
return false;
}
void SimulatorRobot::convertBorderToCylindric(Point const& center)
{
for(unsigned int i=0;i<SIMU_ROBOT_PTS_NBR;i++) {
Geometry2D::convertToCylindricCoord(center, borderPts_[i]);
}
for(unsigned int i=0;i<SIMU_ROBOT_WHEEL_PTS_NBR;i++) {
Geometry2D::convertToCylindricCoord(center, wheelPts_[i]);
}
}
void SimulatorRobot::convertBorderToOrthogonal(Position const& pos)
{
for(unsigned int i=0;i<SIMU_ROBOT_PTS_NBR;i++) {
borderRealPts_[i] = borderPts_[i];
Geometry2D::convertToOrthogonalCoord(pos.center,
pos.direction,
borderRealPts_[i]);
}
for(unsigned int i=0;i<SIMU_ROBOT_WHEEL_PTS_NBR;i++) {
wheelRealPts_[i] = wheelPts_[i];
Geometry2D::convertToOrthogonalCoord(pos.center,
pos.direction,
wheelRealPts_[i]);
}
borderPol_[0] = Polygon(borderRealPts_, 4);
borderPol_[1] = Polygon(&(borderRealPts_[4]), 4);
borderPol_[2] = Polygon(&(borderRealPts_[8]), 4);
}
void SimulatorRobot::setBorderRobotAttack()
{
// points en coordonnees relatives
wheelPts_[0] = Point(0, 160);
wheelPts_[1] = Point(0, -160);
wheelPts_[2] = Point(80, 140);
wheelPts_[3] = Point(80, -140);
borderPts_[0] = Point(110, 175);
borderPts_[1] = Point(-50, 175);
borderPts_[2] = Point(-50, 120);
borderPts_[3] = Point(90, 120);
borderPts_[4] = Point(110, -175);
borderPts_[5] = Point(-50, -175);
borderPts_[6] = Point(-50, -120);
borderPts_[7] = Point(90, -120);
borderPts_[8] = Point(110, -175);
borderPts_[9] = Point(-50, -175);
borderPts_[10] = Point(-50, 175);
borderPts_[11] = Point(110, 175);
// passage des coordonnees en mode cylyndrique
convertBorderToCylindric(Point(0,0));
}
void SimulatorRobot::setBorderRobotDefence()
{
// points en coordonnees relatives
wheelPts_[0] = Point(0, 160);
wheelPts_[1] = Point(0, -160);
wheelPts_[2] = Point(90, 140);
wheelPts_[3] = Point(90, -140);
borderPts_[0] = Point(140, 170);
borderPts_[1] = Point(-60, 170);
borderPts_[2] = Point(-60, 120);
borderPts_[3] = Point(90, 120);
borderPts_[4] = Point(140, -170);
borderPts_[5] = Point(-60, -170);
borderPts_[6] = Point(-60, -120);
borderPts_[7] = Point(90, -120);
borderPts_[8] = Point(140, -170);
borderPts_[9] = Point(-60, -170);
borderPts_[10] = Point(-60, 170);
borderPts_[11] = Point(140, 170);
// passage des coordonnees en mode cylyndrique
convertBorderToCylindric(Point(0,0));
}
void SimulatorRobot::setBorderRobotBrick()
{
// points en coordonnees relatives
wheelPts_[0] = Point(0, 140);
wheelPts_[1] = Point(0, -140);
wheelPts_[2] = Point(140, 0);
wheelPts_[3] = Point(-140, 0);
borderPts_[0] = Point(-150, -150);
borderPts_[1] = Point(-150, 150);
borderPts_[2] = Point(150, 150);
borderPts_[3] = Point(150, -150);
borderPts_[4] = Point(-150, -150);
borderPts_[5] = Point(-150, 150);
borderPts_[6] = Point(150, 150);
borderPts_[7] = Point(150, -150);
borderPts_[8] = Point(-150, -150);
borderPts_[9] = Point(-150, 150);
borderPts_[10] = Point(150, 150);
borderPts_[11] = Point(150, -150);
// passage des coordonnees en mode cylyndrique
convertBorderToCylindric(Point(0,0));
}
|
543aca3d36bfeadfe99759f183c54f5314131e35 | 26f6f9a290182e1ffa8f8554b2f9f498b17004f0 | /HDOJ/1710.cpp | 3f898c3256d2902764be824e94c7d81811111870 | [] | no_license | ZhaoxiZhang/Algorithm | bb2d0f4a439def86de86de15f5cb91326e157fe0 | 6f09e662f4908f6198830ef1e11a20846ff3cacb | refs/heads/master | 2021-01-01T19:42:02.668004 | 2019-09-07T14:55:14 | 2019-09-14T08:08:39 | 98,655,367 | 13 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | 1710.cpp | #include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
typedef struct Tree{
Tree *left,*right;
int val;
}Tree;
Tree *head;
Tree *build(int a[],int b[],int N)
{
Tree *node;
for (int i = 0;i < N;i++)
{
if (b[i] == a[0])
{
node = (Tree *)malloc(sizeof(Tree));
node->val = a[0];
node->left = build(a + 1,b,i);
node->right = build(a + i + 1,b + i + 1, N - i - 1);
return node;
}
}
return NULL;
}
void Print(Tree *p)
{
if (p == NULL) return;
Print(p->left);
Print(p->right);
if (p == head) printf("%d\n",p->val);
else printf("%d ",p->val);
free(p);
}
int main()
{
int N,a[maxn],b[maxn];
while (~scanf("%d",&N))
{
for (int i = 0;i < N;i++) scanf("%d",&a[i]);
for (int i = 0;i < N;i++) scanf("%d",&b[i]);
head = build(a,b,N);
Print(head);
}
return 0;
}
|
d6a59cedd40c53000a3a5b134004e9e9db3e6ad6 | ae7a415f5c291960d08c73aca391e48c2f02359c | /ui/include/radio_group.h | 5e357cbf4f8fccf44e76c2967e9f776f0f210be5 | [] | no_license | BlenderCN-Org/commonlib | 7baca6483bcba06dfc33e5e0725a3f5a70a363e5 | ed75131a230052483a5a0c0503aebca219a6379c | refs/heads/master | 2020-05-22T18:50:02.423070 | 2018-06-11T17:56:46 | 2018-06-11T17:56:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | h | radio_group.h | #ifndef __RADIO_GROUP_H__
#define __RADIO_GROUP_H__
#include <vector>
#include "check_button.h"
namespace UI
{
class RadioGroup
{
private:
std::vector<CheckButton *> group;
public:
RadioGroup() {}
~RadioGroup() {}
void add(CheckButton *c) { group.push_back(c); }
void set_active(CheckButton *c)
{
c->set_state(true);
for (unsigned int i = 0; i < group.size(); i++)
{
if (group[i] != c)
{
group[i]->set_state(false);
}
}
}
};
};
#endif //__RADIO_GROUP_H__
|
be0fda9dbd7c780ac0836e15fac863a6c58611ef | 9be246df43e02fba30ee2595c8cec14ac2b355d1 | /utils/matsysapp/matsysapp.cpp | 9f2804854e96e108b0b975000c1464265397565e | [] | no_license | Clepoy3/LeakNet | 6bf4c5d5535b3824a350f32352f457d8be87d609 | 8866efcb9b0bf9290b80f7263e2ce2074302640a | refs/heads/master | 2020-05-30T04:53:22.193725 | 2019-04-12T16:06:26 | 2019-04-12T16:06:26 | 189,544,338 | 18 | 5 | null | 2019-05-31T06:59:39 | 2019-05-31T06:59:39 | null | UTF-8 | C++ | false | false | 21,431 | cpp | matsysapp.cpp | /*
glapp.c - Simple OpenGL shell
There are several options allowed on the command line. They are:
-height : what window/screen height do you want to use?
-width : what window/screen width do you want to use?
-bpp : what color depth do you want to use?
-window : create a rendering window rather than full-screen
-fov : use a field of view other than 90 degrees
*/
#include "stdafx.h"
#pragma warning(disable:4305)
#pragma warning(disable:4244)
#include <windows.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <mmsystem.h>
#include "matsysapp.h"
#include "cmdlib.h"
#include "imaterialproxyfactory.h"
#include "filesystem.h"
#include "imaterialproxy.h"
#include "MaterialSystem_Config.h"
#include "vstdlib/icommandline.h"
static int g_nCapture = 0;
#define OSR2_BUILD_NUMBER 1111
#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
SpewRetval_t MatSysAppSpewFunc( SpewType_t type, char const *pMsg )
{
printf( "%s", pMsg );
OutputDebugString( pMsg );
if( type == SPEW_ASSERT )
return SPEW_DEBUGGER;
else if( type == SPEW_ERROR )
return SPEW_ABORT;
else
return SPEW_CONTINUE;
}
class MatSysAppMaterialProxyFactory : public IMaterialProxyFactory
{
public:
virtual IMaterialProxy *CreateProxy( const char *proxyName )
{
CreateInterfaceFn clientFactory = Sys_GetFactoryThis();
if( !clientFactory )
{
return NULL;
}
// allocate exactly enough memory for the versioned name on the stack.
char proxyVersionedName[1024];
strcpy( proxyVersionedName, proxyName );
strcat( proxyVersionedName, IMATERIAL_PROXY_INTERFACE_VERSION );
IMaterialProxy *materialProxy;
materialProxy = ( IMaterialProxy * )clientFactory( proxyVersionedName, NULL );
if( !materialProxy )
{
return NULL;
}
return materialProxy;
}
virtual void DeleteProxy( IMaterialProxy *pProxy )
{
if( pProxy )
{
pProxy->Release();
}
}
};
MatSysAppMaterialProxyFactory g_MatSysAppMaterialProxyFactory;
MaterialSystemApp g_MaterialSystemApp;
float fAngle = 0.0f;
char *szFSDesc[] = { "Windowed", "Full Screen" };
extern "C" unsigned int g_Time;
unsigned int g_Time = 0;
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
return g_MaterialSystemApp.WinMain(hInstance, hPrevInstance, szCmdLine, iCmdShow);
}
BOOL isdigits( char *s )
{
int i;
for (i = 0; s[i]; i++)
{
if ((s[i] > '9') || (s[i] < '0'))
{
return FALSE;
}
}
return TRUE;
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
return g_MaterialSystemApp.WndProc(hwnd, iMsg, wParam, lParam);
}
// This function builds a list the screen resolutions supported by the display driver
static void BuildModeList(screen_res_t* &pResolutions, int &iResCount)
{
DEVMODE dm;
int mode;
mode = 0;
while(EnumDisplaySettings(NULL, mode, &dm))
{
mode++;
}
pResolutions = (screen_res_t *)malloc(sizeof(screen_res_t)*mode);
mode = 0;
while(EnumDisplaySettings(NULL, mode, &dm))
{
pResolutions[mode].width = dm.dmPelsWidth;
pResolutions[mode].height = dm.dmPelsHeight;
pResolutions[mode].bpp = dm.dmBitsPerPel;
pResolutions[mode].flags = dm.dmDisplayFlags;
pResolutions[mode].frequency = dm.dmDisplayFrequency;
mode++;
}
iResCount = mode;
}
bool Sys_Error(const char *pMsg, ...)
{
va_list marker;
char msg[4096];
va_start(marker, pMsg);
vsprintf(msg, pMsg, marker);
va_end(marker);
MessageBox(NULL, msg, "FATAL ERROR", MB_OK);
g_MaterialSystemApp.Term();
exit(1);
return false;
}
void con_Printf(const char *pMsg, ...)
{
char msg[2048];
va_list marker;
va_start(marker, pMsg);
vsprintf(msg, pMsg, marker);
va_end(marker);
OutputDebugString(msg);
}
bool MSA_IsKeyDown(char key)
{
return !!(GetAsyncKeyState(key) & 0x8000);
}
bool MSA_IsMouseButtonDown( int button )
{
if( button == MSA_BUTTON_LEFT )
return !!(GetAsyncKeyState(VK_LBUTTON) & 0x8000);
else
return !!(GetAsyncKeyState(VK_RBUTTON) & 0x8000);
}
void MSA_Sleep(unsigned long count)
{
if(count > 0)
Sleep(count);
}
static void MaterialSystem_Error( char *fmt, ... )
{
char str[4096];
va_list marker;
va_start(marker, fmt);
vsprintf(str, fmt, marker);
va_end(marker);
Sys_Error(str);
}
static void MaterialSystem_Warning( char *fmt, ... )
{
}
void InitMaterialSystemConfig(MaterialSystem_Config_t *pConfig, const char *matPath)
{
memset( pConfig, 0, sizeof(*pConfig) );
pConfig->screenGamma = 2.2f;
pConfig->texGamma = 2.2;
pConfig->overbright = 2;
pConfig->bAllowCheats = false;
pConfig->bLinearFrameBuffer = false;
pConfig->polyOffset = 4;
pConfig->skipMipLevels = 0;
pConfig->lightScale = 1.0f;
pConfig->bFilterLightmaps = true;
pConfig->bFilterTextures = true;
pConfig->bMipMapTextures = true;
pConfig->bShowMipLevels = false;
pConfig->bReverseDepth = false;
pConfig->bCompressedTextures = false;
pConfig->bBumpmap = false;
pConfig->bLightingOnly = false;
pConfig->errorFunc = MaterialSystem_Error;
pConfig->warningFunc = MaterialSystem_Warning;
pConfig->bUseGraphics = true;
pConfig->bEditMode = false; // No, we're not in WorldCraft.
}
/*
====================
CalcFov
====================
*/
float CalcFov (float fov_x, float width, float height)
{
float a;
float x;
if (fov_x < 1 || fov_x > 179)
fov_x = 90; // error, set to 90
x = width/tan(fov_x/360*M_PI);
a = atan (height/x);
a = a*360/M_PI;
return a;
}
MaterialSystemApp::MaterialSystemApp()
{
Clear();
}
MaterialSystemApp::~MaterialSystemApp()
{
Term();
}
void MaterialSystemApp::Term()
{
int i;
if( m_pFileSystemDLL )
{
Sys_UnloadModule( m_pFileSystemDLL );
m_pFileSystemDLL = NULL;
}
// Free the command line holder memory
if (m_argc > 0)
{
// Free in reverse order of allocation
for (i = (m_argc-1); i >= 0; i--)
{
free(m_argv[i]);
}
// Free the parameter "pockets"
free(m_argv);
}
// Free the memory that holds the video resolution list
if (m_pResolutions)
free(m_pResolutions);
if (m_hDC)
{
if (!ReleaseDC((HWND)m_hWnd, (HDC)m_hDC))
{
MessageBox(NULL, "ShutdownOpenGL - ReleaseDC failed\n", "ERROR", MB_OK);
}
m_hDC = NULL;
}
if (m_bFullScreen)
{
ChangeDisplaySettings( 0, 0 );
}
Clear();
}
void MaterialSystemApp::Clear()
{
m_pFileSystemDLL = NULL;
m_pMaterialSystem = NULL;
m_hMaterialSystemInst = 0;
m_hInstance = 0;
m_iCmdShow = 0;
m_hWnd = 0;
m_hDC = 0;
m_bActive = false;
m_bFullScreen = false;
m_width = m_height = 0;
m_centerx = m_centery = 0;
m_bpp = 0;
m_bChangeBPP = false;
m_bAllowSoft = 0;
g_nCapture = 0;
m_szCmdLine = 0;
m_argc = 0;
m_argv = 0;
m_glnWidth = 0;
m_glnHeight = 0;
m_gldAspect = 0;
m_NearClip = m_FarClip = 0;
m_fov = 90;
m_pResolutions = 0;
m_iResCount = 0;
m_iVidMode = 0;
}
int MaterialSystemApp::WinMain(void *hInstance, void *hPrevInstance, char *szCmdLine, int iCmdShow)
{
MSG msg;
HDC hdc;
CommandLine()->CreateCmdLine( szCmdLine );
// Not changable by user
m_hInstance = hInstance;
m_iCmdShow = iCmdShow;
m_pResolutions = 0;
m_NearClip = 8.0f;
m_FarClip = 28400.0f;
// User definable
m_fov = 90.0f;
m_bAllowSoft = FALSE;
m_bFullScreen = TRUE;
// Get the current display device info
hdc = GetDC( NULL );
m_DevInfo.bpp = GetDeviceCaps(hdc, BITSPIXEL);
m_DevInfo.width = GetSystemMetrics(SM_CXSCREEN);
m_DevInfo.height = GetSystemMetrics(SM_CYSCREEN);
ReleaseDC(NULL, hdc);
// Parse the command line if there is one
m_argc = 0;
if (strlen(szCmdLine) > 0)
{
m_szCmdLine = szCmdLine;
GetParameters();
}
// Default to 640 pixels wide
m_width = FindNumParameter("-width", 640);
m_height = FindNumParameter("-height", 480);
m_bpp = FindNumParameter("-bpp", 32);
m_fov = FindNumParameter("-fov", 90);
// Check for windowed rendering
m_bFullScreen = FALSE;
if (FindParameter("-fullscreen"))
{
m_bFullScreen = TRUE;
}
// Build up the video mode list
BuildModeList(m_pResolutions, m_iResCount);
// Create the main program window, start up OpenGL and create our viewport
if (CreateMainWindow( m_width, m_height, m_bpp, m_bFullScreen) != TRUE)
{
ChangeDisplaySettings(0, 0);
MessageBox(NULL, "Unable to create main window.\nProgram will now end.", "FATAL ERROR", MB_OK);
Term();
return 0;
}
// Turn the cursor off for full-screen mode
if (m_bFullScreen == TRUE)
{
// Probably want to do this all the time anyway
ShowCursor(FALSE);
}
// We're live now
m_bActive = TRUE;
// Define this funciton to init your app
AppInit();
RECT rect;
GetWindowRect( (HWND)m_hWnd, &rect );
m_centerx = ( rect.left + rect.right ) / 2;
m_centery = ( rect.top + rect.bottom ) / 2;
// Begin the main program loop
while (m_bActive == TRUE)
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
if (m_pMaterialSystem)
{
RenderScene();
}
}
if (m_bFullScreen == TRUE)
{
ShowCursor(TRUE);
}
// Release the parameter and video resolution lists
Term();
// Tell the app to cleanup.
AppExit();
return msg.wParam;
}
long MaterialSystemApp::WndProc(void *inhwnd, long iMsg, long wParam, long lParam)
{
if(inhwnd != m_hWnd)
{
return DefWindowProc((HWND)inhwnd, iMsg, wParam, lParam);
}
HWND hwnd = (HWND)inhwnd;
switch (iMsg)
{
case WM_CHAR:
switch(wParam)
{
case VK_ESCAPE:
SendMessage(hwnd, WM_CLOSE, 0, 0);
break;
}
AppChar( wParam );
break;
case WM_KEYDOWN:
AppKey( wParam, true );
break;
case WM_KEYUP:
AppKey( wParam, false );
break;
case WM_ACTIVATE:
if ((LOWORD(wParam) != WA_INACTIVE) && ((HWND)lParam == NULL))
{
ShowWindow(hwnd, SW_RESTORE);
SetForegroundWindow(hwnd);
}
else
{
if (m_bFullScreen)
{
ShowWindow(hwnd, SW_MINIMIZE);
}
}
return 0;
case WM_SETFOCUS:
if(g_bCaptureOnFocus)
{
MouseCapture();
}
break;
case WM_KILLFOCUS:
if(g_bCaptureOnFocus)
{
MouseRelease();
}
break;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
{
if(!g_bCaptureOnFocus)
{
g_nCapture++;
MouseCapture();
}
}
break;
case WM_LBUTTONUP:
case WM_RBUTTONUP:
{
if(!g_bCaptureOnFocus)
{
g_nCapture--;
MouseRelease();
}
}
break;
case WM_CLOSE:
Term();
m_bActive = FALSE;
break;
case WM_DESTROY:
PostQuitMessage (0);
return 0;
}
return DefWindowProc (hwnd, iMsg, wParam, lParam);
}
bool MaterialSystemApp::InitMaterialSystem()
{
RECT rect;
// Init libraries.
MathLib_Init( true, true, true, 2.2f, 2.2f, 0.0f, 2.0f );
SpewOutputFunc( MatSysAppSpewFunc );
if ((m_hDC = GetDC((HWND)m_hWnd)) == NULL)
{
ChangeDisplaySettings(0, 0);
MessageBox(NULL, "GetDC on main window failed", "FATAL ERROR", MB_OK);
return FALSE;
}
// Load the material system DLL and get its interface.
char *pDLLName = "MaterialSystem.dll";
m_hMaterialSystemInst = LoadLibrary( pDLLName );
if( !m_hMaterialSystemInst )
{
return Sys_Error( "Can't load MaterialSystem.dll\n" );
}
CreateInterfaceFn clientFactory = Sys_GetFactory( pDLLName );
if ( clientFactory )
{
m_pMaterialSystem = (IMaterialSystem *)clientFactory( MATERIAL_SYSTEM_INTERFACE_VERSION, NULL );
if ( !m_pMaterialSystem )
{
return Sys_Error( "Could not get the material system interface from materialsystem.dll" );
}
}
else
{
return Sys_Error( "Could not find factory interface in library MaterialSystem.dll" );
}
// Figure out the material path.
char fullPath[1024];
const char *pPath = FindParameterArg("-game");
char modDir[512];
if(!pPath)
{
// If they didn't specify -game on the command line, use VPROJECT.
SetQdirFromPath(".");
pPath = basegamedir;
strcpy( modDir, gamedir );
}
else
{
modDir[0] = 0;
}
sprintf(fullPath, "%smaterials", pPath);
char workingDir[512];
GetCurrentDirectory( sizeof(workingDir), workingDir );
const char *pShaderDLL = FindParameterArg("-shaderdll");
char defaultShaderDLL[256];
if(!pShaderDLL)
{
strcpy(defaultShaderDLL, "shaderapidx9.dll");
pShaderDLL = defaultShaderDLL;
}
m_pFileSystemDLL = Sys_LoadModule( "filesystem_stdio.dll" );
if( !m_pFileSystemDLL )
{
return Sys_Error( "Can't load file system DLL (filesystem_stdio.dll)" );
}
if ( !strlen( modDir ) )
{
sprintf( modDir, "%s\\%s", workingDir, pPath );
}
IFileSystem *pFileSystem = ( IFileSystem * )Sys_GetFactory(m_pFileSystemDLL)( FILESYSTEM_INTERFACE_VERSION, NULL );
if ( pFileSystem->Init() != INIT_OK )
return false;
pFileSystem->AddSearchPath( modDir, "PLATFORM" );
if(!m_pMaterialSystem->Init(pShaderDLL, &g_MatSysAppMaterialProxyFactory, Sys_GetFactory(m_pFileSystemDLL)))
return Sys_Error("IMaterialSystem::Init failed");
MaterialVideoMode_t mode;
memset(&mode, 0, sizeof(mode));
if(!m_pMaterialSystem->SetMode(m_hWnd, 0, mode, MATERIAL_VIDEO_MODE_WINDOWED))
return Sys_Error("IMaterialSystem::SetMode failed");
MaterialSystem_Config_t config;
InitMaterialSystemConfig(&config, fullPath);
if(!m_pMaterialSystem->ConfigInit(&config))
return Sys_Error("IMaterialSystem::ConfigInit failed. Make sure VPROJECT is set or use -game on the command line.");
GetClientRect((HWND)m_hWnd, &rect);
m_glnWidth= rect.right;
m_glnHeight = rect.bottom;
m_gldAspect = (float)m_glnWidth / m_glnHeight;
GetWindowRect( (HWND)m_hWnd, &rect );
m_centerx = (rect.left + rect.right) / 2;
m_centery = (rect.top + rect.bottom) / 2;
return true;
}
bool MaterialSystemApp::CreateMainWindow(int width, int height, int bpp, bool fullscreen)
{
HWND hwnd;
WNDCLASSEX wndclass;
DWORD dwStyle, dwExStyle;
int x, y, sx, sy, ex, ey, ty;
if ((hwnd = FindWindow(g_szAppName, g_szAppName)) != NULL)
{
SetForegroundWindow(hwnd);
return 0;
}
wndclass.cbSize = sizeof (wndclass);
wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wndclass.lpfnWndProc = ::WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = (HINSTANCE)m_hInstance;
wndclass.hIcon = 0;
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)COLOR_GRAYTEXT;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = g_szAppName;
wndclass.hIconSm = 0;
if (!RegisterClassEx (&wndclass))
{
MessageBox(NULL, "Window class registration failed.", "FATAL ERROR", MB_OK);
return FALSE;
}
if (fullscreen)
{
dwExStyle = WS_EX_TOPMOST;
dwStyle = WS_POPUP | WS_VISIBLE;
x = y = 0;
sx = m_width;
sy = m_height;
}
else
{
dwExStyle = 0;
//dwStyle = WS_CAPTION | WS_SYSMENU | WS_THICKFRAME; // Use this if you want a "normal" window
dwStyle = WS_CAPTION;
ex = GetSystemMetrics(SM_CXEDGE);
ey = GetSystemMetrics(SM_CYEDGE);
ty = GetSystemMetrics(SM_CYSIZE);
// Center the window on the screen
x = (m_DevInfo.width / 2) - ((m_width+(2*ex)) / 2);
y = (m_DevInfo.height / 2) - ((m_height+(2*ey)+ty) / 2);
sx = m_width+(2*ex);
sy = m_height+(2*ey)+ty;
/*
Check to be sure the requested window size fits on the screen and
adjust each dimension to fit if the requested size does not fit.
*/
if (sx >= m_DevInfo.width)
{
x = 0;
sx = m_DevInfo.width-(2*ex);
}
if (sy >= m_DevInfo.height)
{
y = 0;
sy = m_DevInfo.height-((2*ey)+ty);
}
}
if ((hwnd = CreateWindowEx (dwExStyle,
g_szAppName, // window class name
g_szAppName, // window caption
dwStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, // window style
x, // initial x position
y, // initial y position
sx, // initial x size
sy, // initial y size
NULL, // parent window handle
NULL, // window menu handle
(HINSTANCE)m_hInstance, // program instance handle
NULL)) // creation parameters
== NULL)
{
ChangeDisplaySettings(0, 0);
MessageBox(NULL, "Window creation failed.", "FATAL ERROR", MB_OK);
return FALSE;
}
m_hWnd = hwnd;
if (!InitMaterialSystem())
{
m_hWnd = NULL;
return FALSE;
}
ShowWindow((HWND)m_hWnd, m_iCmdShow);
UpdateWindow((HWND)m_hWnd);
SetForegroundWindow((HWND)m_hWnd);
SetFocus((HWND)m_hWnd);
return TRUE;
}
void MaterialSystemApp::RenderScene()
{
if(!m_pMaterialSystem)
return;
static DWORD lastTime = 0;
POINT cursorPoint;
float deltax = 0, deltay = 0, frametime;
DWORD newTime = GetTickCount();
DWORD deltaTime = newTime - lastTime;
if ( deltaTime > 1000 )
deltaTime = 0;
lastTime = newTime;
frametime = (float) ((double)deltaTime * 0.001);
g_Time = newTime;
if ( g_nCapture )
{
GetCursorPos( &cursorPoint );
SetCursorPos( m_centerx, m_centery );
deltax = (cursorPoint.x - m_centerx) * 0.1f;
deltay = (cursorPoint.y - m_centery) * -0.1f;
}
else
{
deltax = deltay = 0;
}
m_pMaterialSystem->ClearBuffers(true, true);
m_pMaterialSystem->MatrixMode(MATERIAL_PROJECTION);
m_pMaterialSystem->LoadIdentity();
m_pMaterialSystem->PerspectiveX(m_fov, m_gldAspect, m_NearClip, m_FarClip);
m_pMaterialSystem->MatrixMode(MATERIAL_VIEW);
m_pMaterialSystem->LoadIdentity();
AppRender( frametime, deltax, deltay );
m_pMaterialSystem->SwapBuffers();
}
void MaterialSystemApp::MouseCapture()
{
SetCapture( (HWND)m_hWnd );
ShowCursor(FALSE);
SetCursorPos( m_centerx, m_centery );
}
void MaterialSystemApp::MouseRelease()
{
ShowCursor(TRUE);
ReleaseCapture();
SetCursorPos( m_centerx, m_centery );
}
void MaterialSystemApp::GetParameters()
{
int count;
char *s, *tstring;
// Make a copy of the command line to count the parameters - strtok is destructive
tstring = (char *)malloc(sizeof(char)*(strlen(m_szCmdLine)+1));
strcpy(tstring, m_szCmdLine);
// Count the parameters
s = strtok(tstring, " ");
count = 1;
while (strtok(NULL, " ") != NULL)
{
count++;
}
free(tstring);
// Allocate "pockets" for the parameters
m_argv = (char **)malloc(sizeof(char*)*(count+1));
// Copy first parameter into the "pockets"
m_argc = 0;
s = strtok(m_szCmdLine, " ");
m_argv[m_argc] = (char *)malloc(sizeof(char)*(strlen(s)+1));
strcpy(m_argv[m_argc], s);
m_argc++;
// Copy the rest of the parameters
do
{
// get the next token
s = strtok(NULL, " ");
if (s != NULL)
{
// add it to the list
m_argv[m_argc] = (char *)malloc(sizeof(char)*(strlen(s)+1));
strcpy(m_argv[m_argc], s);
m_argc++;
}
}
while (s != NULL);
}
int MaterialSystemApp::FindNumParameter(const char *s, int defaultVal)
{
int i;
for (i = 0; i < (m_argc-1); i++)
{
if (stricmp(m_argv[i], s) == 0)
{
if (isdigits(m_argv[i+1]))
{
return(atoi(m_argv[i+1]));
}
else
{
return defaultVal;
}
}
}
return defaultVal;
}
bool MaterialSystemApp::FindParameter(const char *s)
{
int i;
for (i = 0; i < m_argc; i++)
{
if (stricmp(m_argv[i], s) == 0)
{
return true;
}
}
return false;
}
const char *MaterialSystemApp::FindParameterArg( const char *s )
{
int i;
for (i = 0; i < m_argc; i++)
{
if (stricmp(m_argv[i], s) == 0)
{
if( (i+1) < m_argc )
return m_argv[i+1];
else
return "";
}
}
return NULL;
}
void MaterialSystemApp::SetTitleText(const char *fmt, ...)
{
char str[4096];
va_list marker;
va_start(marker, fmt);
vsprintf(str, fmt, marker);
va_end(marker);
::SetWindowText((HWND)m_hWnd, str);
}
void MaterialSystemApp::MakeWindowTopmost()
{
::SetWindowPos((HWND)m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
}
void MaterialSystemApp::AppShutdown()
{
SendMessage( (HWND)m_hWnd, WM_CLOSE, 0, 0 );
}
|
09d070093ac86afe1f73206d6ddfa3cc8383ec3b | 81e4a5de81de39562e27befbad253ec8f039c9f3 | /2_LeetCode/28/ans.cpp | 6e17bb8d69d882d13a754f6750f6cbace852a752 | [] | no_license | Twelveeee/AlgorithmQuestion | 20fb5628f9e3b8bf167d41949afb23abc9f4d595 | d229f589c8b3b672e37a9adabcdad1eedea931cd | refs/heads/master | 2023-04-16T05:40:37.157432 | 2021-04-28T12:13:40 | 2021-04-28T12:13:40 | 197,725,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 502 | cpp | ans.cpp | class Solution {
public:
int strStr(string haystack, string needle) {
int n= haystack.size();
int m = needle.size();
if(n<m && m!=n)return -1;
if( m==0 )return 0;
for(int i =0;i<n;i++){
if(haystack[i] == needle[0]){
for(int j=0;j<m;j++){
if(haystack[i+j] != needle[j]){
break;
}
if(j == m-1){
return i;
}
}
}
}
return -1;
}
}; |
441922f1da089472d3890da9d33158735cda477b | ca711af27fff5442d0ee56f264e77a63caee055c | /projetoJacana/src/TipoAto.cpp | c8810d822edb3b9463666456a85b62f4d628da94 | [] | no_license | green-dev-52-matheushsilva/__projeto__jacana__587TK | 051da2432f9f3b1f76944d93ffa29879d134d364 | 315b1d6eb504012bf885b1f509a2f3018ad45ca3 | refs/heads/master | 2021-01-12T17:05:17.509350 | 2016-10-20T18:53:28 | 2016-10-20T18:53:28 | 71,493,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,473 | cpp | TipoAto.cpp | #include "TipoAto.h"
const void *TipoAto :: definirAtosAplicaveis( ) {
this->tiposDisponiveisDeAtos = new std::vector< std::string * >();
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro-2R-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro-2A-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Prenotação-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Abertura-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Notificação-Intimação-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Prenotação-Desconto-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro-2R-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro-2A-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Informação-Verbal-ou-Eletrônica-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Visualização-eletrônica-de-matrícula-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Notificação-RTD" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Registros-RTD-LB" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Registro-RPJ-LA" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro 3R-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Prenotação-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro-2R-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro-2A-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Abertura-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro-2R-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro- 2A-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Abertura-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Abertura-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RPJ" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Condomínio-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Incorporação-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Loteamento-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Exame-e-álculo-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro-3A-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Visualização-eletrônica-de-documento-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RTD" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Prenotação-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Busca-RPJ" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Busca-RTD" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Notificação-Intimação-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Notificação-Intimação-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Notificação-Intimação-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Informação-Eletrônica-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Informação-Eletrônica-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Informação-Eletrônica-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Prenotação-Desconto-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Informação-Verbal-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Informação-Verbal-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Informação-Verbal-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Exame-e-Cálculo-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Exame-e-Cálculo-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Exame-e-Cálculo-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Visualização-eletrônica-de-documento-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Visualização-eletrônica-de-matrícula-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Visualização-eletrônica-de-documento-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Visualização-eletrônica-de-matrícula-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Visualização-eletrônica-de-documento-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Visualização-eletrônica-de-matrícula-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Prenotação-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Averbação-RRI" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Averbação-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Averbação-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Averbação-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Condomínio-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Condomínio-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Condomínio-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Incorporação-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Incorporação-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Incorporação-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Loteamento-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Registro-RPJ-LB" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Registros-RTD-LC" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro 3A-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro 3A-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro 3A-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro 3R-RRI-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro 3R-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Livro 3R-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Loteamento-RRI-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Loteamento-RRI-SP" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Registro-RPJ-LA-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Registros-RTD-LB-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RPJ-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RPJ-GG" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RTD-G" ) );
tiposDisponiveisDeAtos->push_back ( new std::string( "Certidão-RTD-GG" ) );
return NULL;
}
const std::vector< std::string * > *TipoAto :: retornarTiposAtosValidos ( ) {
if ( this->tiposDisponiveisDeAtos != nullptr ) {
if ( ( (unsigned short ) this->tiposDisponiveisDeAtos->size() ) > 2 ){
return this->tiposDisponiveisDeAtos;
} else {
return nullptr;
}
} else {
return nullptr;
}
}
TipoAto::TipoAto(){
this->definirAtosAplicaveis( );
}
TipoAto::~TipoAto(){
delete this->tiposDisponiveisDeAtos;
}
|
52935b308da79b857c3e42ca27e3c6857f8a36e3 | 1c2c0fbe2a9f27ba8f0e154a044d086b1af878de | /46.cpp | 016fe6863eb68481d4d477f4b0581ec082047c33 | [] | no_license | QunNguyen/C_luyentap | b8b72bf2dfd1ae722a435baf25c3fd506c340612 | da801e21935bc2bd8e664391ea2b46c053105554 | refs/heads/main | 2023-08-13T05:45:04.139919 | 2021-10-19T05:49:40 | 2021-10-19T05:49:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | cpp | 46.cpp | #include<bits/stdc++.h>
using namespace std;
int a[100],n;
bool check=true;
void Tao(){
check=true;
for(int i=1;i<=n;i++)
a[i]=i;
}
void In(){
for(int i=1;i<=n;i++)
cout<<a[i];
cout<<" ";
}
void Sinh(){
int i=n-1;
while(i>0&&a[i]>a[i+1]) i--;
if(i>0){
int j=n;
while(a[i]>a[j]) j--;
swap(a[i],a[j]);
int k=i+1;
int h=n;
while(k<h){
swap(a[k],a[h]);
k++;h--;
}
}
else check=false;
}
int main(){
int t;
cin>>t;
while(t--){
cin>>n;
Tao();
while(check){
In();
Sinh();
}
cout<<endl;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.