text
stringlengths 8
6.88M
|
|---|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
*/
#ifndef MDE_OPFONT_H
#define MDE_OPFONT_H
#include "modules/pi/OpFont.h"
#ifdef MDEFONT_MODULE
struct MDE_FONT;
#endif // MDEFONT_MODULE
class MDE_OpFont : public OpFont
{
public:
MDE_OpFont();
virtual ~MDE_OpFont();
virtual OpFontInfo::FontType Type() { return m_type; }
#ifdef MDEFONT_MODULE
void Init(MDE_FONT* mdefont);
#endif // MDEFONT_MODULE
virtual UINT32 Ascent();
virtual UINT32 Descent();
virtual UINT32 InternalLeading();
virtual UINT32 Height();
virtual UINT32 AveCharWidth();
virtual UINT32 Overhang();
virtual UINT32 StringWidth(const uni_char* str, UINT32 len, INT32 extra_char_spacing = 0);
virtual UINT32 StringWidth(const uni_char* str, UINT32 len, OpPainter* painter, INT32 extra_char_spacing = 0);
#ifdef SVG_SUPPORT
virtual OP_STATUS GetOutline(const uni_char* in_str, UINT32 in_len, UINT32& io_str_pos, UINT32 in_last_str_pos,
BOOL in_writing_direction_horizontal, SVGNumber& out_advance, SVGPath** out_glyph);
#endif // SVG_SUPPORT
virtual OP_STATUS GetFontData(UINT8*& font_data, UINT32& data_size) { return OpStatus::ERR; }
virtual OP_STATUS ReleaseFontData(UINT8* font_data) { return OpStatus::ERR; }
#ifdef OPFONT_GLYPH_PROPS
OP_STATUS GetGlyphProps(const UnicodePoint up, GlyphProps* props);
#endif // OPFONT_GLYPH_PROPS
// private-ish:
#ifdef MDEFONT_MODULE
MDE_FONT* m_mdefont;
#endif // MDEFONT_MODULE
int m_ave_char_width;
OpFontInfo::FontType m_type;
};
#endif // MDE_OPFONT_H
|
/****************************************************************
File Name: util.C
Author: Tian Zhang, CS Dept., Univ. of Wisconsin-Madison, 1995
Copyright(c) 1995 by Tian Zhang
All Rights Reserved
Permission to use, copy and modify this software must be granted
by the author and provided that the above copyright notice appear
in all relevant copies and that both that copyright notice and this
permission notice appear in all relevant supporting documentations.
Comments and additions may be sent the author at zhang@cs.wisc.edu.
******************************************************************/
#include "global.h"
#include "util.h"
int MinOne(int x, int y)
{ if (x<y) return x;
else return y;
}
int MaxOne(int x, int y)
{ if (x>y) return x;
else return y;
}
double MinOne(double x, double y)
{ if (x<y) return x;
else return y;
}
double MaxOne(double x, double y)
{ if (x>y) return x;
else return y;
}
void indent(short ind, std::ostream &fo)
{ for (short i=0; i<ind; i++)
fo << ' ';
}
void indent(short ind, std::ofstream &fo)
{ for (short i=0; i<ind; i++)
fo << ' ';
}
void print_error(char *fnc, char *msg) {
printf("Fatal Error: in function %s: %s\n",fnc,msg);
exit(1);
}
|
#define BOOST_SP_DISABLE_THREADS
#include "PointLocatorExec.h"
///////////////////////////////////////////////////////////////////////
//
//
//
//
// Public Methods
//
//
//
//
//////////////////////////////////////////////////////////////////////
PointLocatorExec::PointLocatorExec()
{
}
PointLocatorExec::PointLocatorExec(TopologyStructConstExecution topology,
ArrayHandle<dax::Vector3>::PortalConstExecution sortPoints,
ArrayHandle<dax::Id>::PortalConstExecution pointStarts,
ArrayHandle<int>::PortalConstExecution pointCounts)
: topology(topology),
sortPoints(sortPoints),
pointStarts(pointStarts),
pointCounts(pointCounts)
{
}
void PointLocatorExec::setTopology(TopologyStructConstExecution topology)
{
this->topology = topology;
}
void PointLocatorExec::setSortPoints
(ArrayHandle<dax::Vector3>::PortalConstExecution sortPoints)
{
this->sortPoints = sortPoints;
}
void PointLocatorExec::setPointStarts
(ArrayHandle<dax::Id>::PortalConstExecution pointStarts)
{
this->pointStarts = pointStarts;
}
void PointLocatorExec::setPointCounts
(ArrayHandle<int>::PortalConstExecution pointCounts)
{
this->pointCounts = pointCounts;
}
///////////////////////////////////////////////////////////////////////
//
//
//
//
// Protected Methods
//
//
//
//
//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
//
//
//
// Private Methods
//
//
//
//
//////////////////////////////////////////////////////////////////////
|
#include "QFileSearch.h"
const char* COLTAG[] = { "文件名" ,"文件夹" ,"大小" ,"修改时间" };
const int COLWIDTH[] = { 200, 300, 80, 200 };
const char* FILESIZEUNIT[] = { " B", " KB", " MB", " G" };
const char* FORMAT = "%u年%u月%u日 %u时%u分%u秒";
QFileSearch::QFileSearch(QWidget *parent)
: QMainWindow(parent)
{
QMutexLocker locker(&lock);
initUI();
initSearchWork();
}
void QFileSearch::initUI(void)
{
// 固定窗口大小
setMinimumSize(WINDOWWIDTH, WINDOWHEIGHT);
setMaximumSize(WINDOWWIDTH, WINDOWHEIGHT);
// 初始化Item菜单
itemMenu = nullptr;
// 初始化虚拟滑轮框
fakeScrollArea = new QScrollArea(this);
fakeScrollArea->setGeometry(0, OFFSET + (GAP << 1), WINDOWWIDTH, WINDOWHEIGHT - (OFFSET * 2 + (GAP << 1)));
fakeScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
// 初始化搜索栏
searchLineEdit = new QLineEdit(this);
searchLineEdit->setGeometry(GAP, GAP, WINDOWWIDTH - (GAP << 1), OFFSET);
QRegExp rx("[a-z A-Z 0-9 .-|#*$?]{25}"); // 限制输入
QRegExpValidator *pRevalidotor = new QRegExpValidator(rx, this);
searchLineEdit->setValidator(new QRegExpValidator(rx, this));
searchLineEdit->setDisabled(true);
// 初始化item容器
fileItemModel = new QStandardItemModel(this);
fileItemModel->setColumnCount(COLNUM);
// 初始化显示文件列表框
fileListTableView = new QTableView(fakeScrollArea);
fileListTableView->setGeometry(0, 0, WINDOWWIDTH, WINDOWHEIGHT - ((OFFSET + GAP) * 2));
fileListTableView->setModel(fileItemModel);
fileListTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter); // 字体居中
fileListTableView->verticalHeader()->setDefaultSectionSize(20); // 固定行高度为6
fileListTableView->verticalHeader()->setVisible(false); // 列表头不可见
fileListTableView->setShowGrid(true); // 表中网格线可见
fileListTableView->setEditTriggers(QAbstractItemView::NoEditTriggers); // 不可更改表中内容
fileListTableView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(fileListTableView, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showMenuClickedSlots(const QPoint&)));
// 添加行头
for (int i = 0; i < COLNUM; ++i) {
fileItemModel->setHeaderData(i, Qt::Horizontal, QString::fromLocal8Bit(COLTAG[i]));
fileListTableView->setColumnWidth(i, COLWIDTH[i]);
}
// 初始化状态栏
searchInfoStatusBar = new QStatusBar(this);
searchInfoStatusBar->setGeometry(0, WINDOWHEIGHT - OFFSET, WINDOWWIDTH, OFFSET);
searchInfoStatusBar->showMessage("Initializing, please wait ^_^");
// 初始化关于按钮
aboutPushButton = new QPushButton(this);
aboutPushButton->setText(QString::fromLocal8Bit("关于"));
aboutPushButton->setGeometry(WINDOWWIDTH - BUTTONWIDTH, WINDOWHEIGHT - BUTTONHEIGHT, BUTTONWIDTH, BUTTONHEIGHT);
connect(aboutPushButton, SIGNAL(clicked(void)), this, SLOT(onAboutPushButtonClicked(void)));
// 初始化监控窗口
ULONG m_ulSHChangeNotifyRegister = NULL;
SHChangeNotifyEntry shCNF = { 0 };
shCNF.pidl = NULL;;
shCNF.fRecursive = TRUE;
m_ulSHChangeNotifyRegister = SHChangeNotifyRegister((HWND)winId(),
SHCNRF_ShellLevel,
SHCNE_ALLEVENTS,
WM_FILEMODIFY,
1,
&shCNF);
filter = new QEventFilter;
}
void QFileSearch::initSearchWork(void)
{
diskNum = 0;
// 获取磁盘的数量
for (char diskName = 'C'; diskName <= 'Z'; ++diskName)
{
Volume *v = new Volume(diskName);
if (v->isNTFS())
{
diskNum++;
}
}
num = diskNum - 1;
// 扫描每一个盘
for (char diskName = 'C'; diskName <= 'Z'; ++diskName)
{
Volume *v = new Volume(diskName);
// 如果当前盘存在并且是 NTFS 结构就增加一个线程
if (v->isNTFS()) // 可以用 QStorageInfo 来判断
{
QThread *thread = new QThread;
v->moveToThread(thread);
connect(thread, &QThread::started, v, &Volume::initUSN);
/*connect(filter, SIGNAL(sigCreate(QString)), v, SLOT(sltCreate(QString)));
connect(filter, SIGNAL(sigDelete(QString)), v, SLOT(sltDelete(QString)));
connect(filter, SIGNAL(sigCreate(QString, QString)), v, SLOT(sltRename(QString, QString)));*/
connect(this, &QFileSearch::destroy, this, [=]() {
thread->wait();
thread->quit();
lock.lock();
v->deleteLater();
thread->deleteLater();
lock.unlock();
});
connect(searchLineEdit, &QLineEdit::textChanged, v, &Volume::search); // 当搜索栏改变时就搜索
// 避免输入速度过快
connect(searchLineEdit, &QLineEdit::textChanged, this, [=]() {
searchLineEdit->blockSignals(true);
});
connect(v, &Volume::sigInitEnd, this, [=]() {
if ((diskNum - 1) == num)
{
searchLineEdit->setDisabled(false);
}
});
// 更新文件列表
connect(fakeScrollArea->verticalScrollBar(), &QScrollBar::valueChanged, this, &QFileSearch::updateItemModel);
connect(v, &Volume::sigSearchEnd, this, [=]() { // 搜索完毕发送信号
lock.lock();
num = (num + 1) % diskNum;
lock.unlock();
if ((diskNum - 1) == num)
{
searchLineEdit->blockSignals(false);
Singleton& fileArr = Singleton::get_instance();
int sum = 0;
for (int i = 0; i < ALPHABETNUM; ++i)
{
sum += fileArr.res[i].size();
}
fakeScrollArea->verticalScrollBar()->setMaximum((sum > ROWNUM) ? sum - ROWNUM : 0); // 设置滚动条的最大值
fakeScrollArea->verticalScrollBar()->setSliderPosition(0); // 让滚动条回到最上方
updateItemModel(0); // 更新文件列表
updateItemModel(0); // 更新文件列表
}
});
thread->start();
}
}
}
void QFileSearch::updateItemModel(int pos)
{
while (fileItemModel->removeRow(1)); // 清空之前的列表
Singleton& fileArr = Singleton::get_instance();
int sum = 0; // 获取文件的总数
for (int i = 0; i < ALPHABETNUM; ++i)
{
sum += fileArr.res[i].size();
}
searchInfoStatusBar->showMessage("find: " + QString::number(sum) + " files");
QStandardItem *items[COLNUM];
int dn = 0; // 表示第几个磁盘
int j = 1;
for (int count = 0; count < ROWNUM && count < sum; ++count, ++pos, ++j)
{
while (dn < ALPHABETNUM && pos >= fileArr.res[dn].size()) // 找到 pos 对应的元素位置在哪个盘
{
pos = pos - fileArr.res[dn].size();
dn++;
}
if (dn == ALPHABETNUM)
{
break;
}
std::string tmp = fileArr.res[dn].at(pos).filePath + fileArr.res[dn].at(pos).fileName;
wchar_t fullPath[MAX_PATH];
swprintf(fullPath, MAX_PATH, L"%S", tmp.c_str()); // 注意大写
GET_FILEEX_INFO_LEVELS fInfoLevelId = GetFileExInfoStandard; // 获取句柄
WIN32_FILE_ATTRIBUTE_DATA FileInformation; // 存储文件信息
BOOL bGet = GetFileAttributesEx(fullPath, fInfoLevelId, &FileInformation); // 获取文件信息
SYSTEMTIME sysTime; // 系统时间
FileTimeToSystemTime(&FileInformation.ftCreationTime, &sysTime); // 将文件时间转换为本地系统时间
QString fileSize = "";
if (0 != FileInformation.nFileSizeLow) // 处理文件大小
{
int sCount = 0;
while (FileInformation.nFileSizeLow > 1024)
{
sCount++;
FileInformation.nFileSizeLow >>= 10;
}
fileSize = QString::number(FileInformation.nFileSizeLow) + FILESIZEUNIT[sCount];
}
QString fileTime = "";
if (0xffff != sysTime.wYear) // 处理文件时间的显示
{
char ft[0x3f];
sprintf(ft, FORMAT, sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
fileTime = QString::fromLocal8Bit(ft);
}
// 文件名 文件路径 文件大小 文件日期
items[0] = new QStandardItem(QString::fromStdString(fileArr.res[dn].at(pos).fileName));
items[0]->setEditable(false);
items[1] = new QStandardItem(QString::fromStdString(fileArr.res[dn].at(pos).filePath));
items[1]->setEditable(false);
items[2] = new QStandardItem(fileSize);
items[2]->setEditable(false);
items[2]->setTextAlignment(Qt::AlignRight);
items[3] = new QStandardItem(fileTime);
items[3]->setEditable(false);
items[3]->setTextAlignment(Qt::AlignRight);
fileItemModel->setItem(j, 0, items[0]);
fileItemModel->setItem(j, 1, items[1]);
fileItemModel->setItem(j, 2, items[2]);
fileItemModel->setItem(j, 3, items[3]);
}
}
void QFileSearch::showMenuClickedSlots(const QPoint& pos)
{
int row = fileListTableView->verticalHeader()->logicalIndexAt(pos); // 获取当前点击的Item位置
if (-1 != row)
{
if (nullptr != itemMenu) // 避免占用内存
{
delete itemMenu;
}
itemMenu = new QMenu(this);
QAction *openFile = itemMenu->addAction(QString::fromLocal8Bit("打开文件"));
QAction *openPath = itemMenu->addAction(QString::fromLocal8Bit("打开路径"));
QAction *copyPath = itemMenu->addAction(QString::fromLocal8Bit("复制文件完整路径和文件名"));
connect(openFile, &QAction::triggered, this, [=]() {
QDesktopServices::openUrl(QUrl::fromLocalFile(fileItemModel->item(row, 1)->text() + fileItemModel->item(row, 0)->text()));
});
connect(openPath, &QAction::triggered, this, [=]() {
QDesktopServices::openUrl(QUrl::fromLocalFile(fileItemModel->item(row, 1)->text()));
});
connect(copyPath, &QAction::triggered, this, [=]() {
QClipboard *clip = QApplication::clipboard(); // 获取剪切板
clip->setText(fileItemModel->item(row, 1)->text() + fileItemModel->item(row, 0)->text());
});
itemMenu->exec(QCursor::pos()); //在当前鼠标位置显示
}
}
void QFileSearch::onAboutPushButtonClicked(void)
{
aboutDialog = new QDialog(this);
aboutDialog->setAttribute(Qt::WA_DeleteOnClose, true);
aboutDialog->setMinimumSize(DIALOGWIDTH, DIALOGHEIGHT);
aboutDialog->setMaximumSize(DIALOGWIDTH, DIALOGHEIGHT);
aboutDialog->setWindowTitle("About");
aboutDialog->show();
//计算显示原点
QRect rect = geometry();
int x = rect.x() + ((WINDOWWIDTH - DIALOGWIDTH) >> 1);
int y = rect.y() + ((WINDOWHEIGHT - DIALOGHEIGHT) >> 1);
aboutDialog->move(x, y);
aboutTextLabel = new QLabel(aboutDialog);
aboutTextLabel->setAttribute(Qt::WA_DeleteOnClose, true);
aboutTextLabel->setText(ABOUTTEXT);
aboutTextLabel->setGeometry(20, 20, 400, 300);
aboutTextLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
aboutTextLabel->show();
}
|
#include<iostream>
#include<string>
using namespace std;
int main()
{
int arr[256]={0};
string s;
cin>>s;
for(int i=0;i<s.size()/2;i++)
{
if( s[i] != s[s.size()-i-1] )
{
cout<<"not palindrome";
return 0;
}
}
cout<<"palindrome";
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int number, test = 1;
while(cin >> number && number > 0)
{
int hello = 1, count = 0;
while(hello < number)
{
hello+=hello;
count++;
}
cout << "Case " << test++ << ": " << count << endl;
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 2008-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef MEDIA_PLAYER_SUPPORT
#include "modules/media/src/coremediaplayer.h"
#include "modules/media/src/mediasource.h"
/* static */ OP_STATUS
MediaPlayer::Create(MediaPlayer*& player, const URL& url, const URL& referer_url, BOOL is_video, Window* window)
{
RETURN_IF_ERROR(g_media_module.EnsureOpMediaManager());
// Find a good MessageHandler for the MediaPlayer to use. There are two requirements:
// * The MessageHandler must outlive the MediaPlayer.
// * MessageHandler::GetWindow() must work for Gadget Media to load correctly.
// There is no known MessageHandler that does both of those so try the best mix possible.
MessageHandler* message_handler = g_main_message_handler;
#ifdef GADGET_SUPPORT
if (window && window->GetType() == WIN_TYPE_GADGET)
// Might crash if element is abused. See CORE-38309.
message_handler = window->GetMessageHandler();
#endif // GADGET_SUPPORT
// Don't ever play in a thumbnail
BOOL force_paused = window && window->IsThumbnailWindow();
player = OP_NEW(CoreMediaPlayer, (url, referer_url, is_video, g_op_media_manager, g_media_source_manager, message_handler, force_paused));
if (!player)
return OpStatus::ERR_NO_MEMORY;
return OpStatus::OK;
}
#ifndef SELFTEST
# define m_source_manager g_media_source_manager
# define m_pi_manager g_op_media_manager
#endif // !SELFTEST
CoreMediaPlayer::CoreMediaPlayer(const URL& url, const URL& origin_url, BOOL is_video,
OpMediaManager* pi_manager,
MediaSourceManager* source_manager,
MessageHandler* message_handler,
BOOL force_paused)
: m_pi_player(NULL),
m_listener(NULL),
m_source(NULL),
m_url(url),
m_origin_url(origin_url),
m_position(0.0),
m_rate(1.0),
m_volume(1.0),
m_preload(g_stdlib_infinity),
m_message_handler(message_handler),
m_played_ranges(NULL),
m_played_range_start(-1),
m_paused(TRUE),
m_force_paused(force_paused),
m_suspend(FALSE),
m_seeking(FALSE)
#ifdef DEBUG_ENABLE_OPASSERT
, m_network_err(FALSE)
, m_decode_err(FALSE)
, m_duration_known(FALSE)
#endif // DEBUG_ENABLE_OPASSERT
, m_is_video(is_video)
#ifdef SELFTEST
, m_pi_manager(pi_manager)
, m_source_manager(source_manager)
#endif // SELFTEST
#if VIDEO_THROTTLING_FPS_HIGH > 0
, m_throttler(this)
#endif // VIDEO_THROTTLING_FPS_HIGH
{
}
/* virtual */
CoreMediaPlayer::~CoreMediaPlayer()
{
DestroyPlatformPlayer();
if (m_source)
ReleaseSource();
OP_DELETE(m_played_ranges);
}
OP_STATUS
CoreMediaPlayer::Init()
{
if (!m_pi_player && !m_source)
{
// Ask OpMediaManager::CanPlayURL about how to handle this
// URL. Don't ask about data: URLs as that requires copying
// the (potentially huge) data just to ask.
if (m_url.Type() != URL_DATA)
{
OpString url_str;
RETURN_IF_ERROR(m_url.GetAttribute(URL::KUniName_For_Data, 0, url_str));
if (m_pi_manager->CanPlayURL(url_str.CStr()))
{
// OpMediaPlayer wants to handle this URL without help
// from core. Simply create and initialize the player.
InitPlatformPlayer(m_pi_manager->CreatePlayer(&m_pi_player, GetHandle(), url_str.CStr()));
return OpStatus::OK;
}
}
// OpMediaPlayer will need to use OpMediaSource. Create a
// MediaSource and begin buffering. OpMediaPlayer is
// created and initalized in OnProgress or OnIdle.
OP_ASSERT(m_source == NULL);
RETURN_IF_ERROR(m_source_manager->GetSource(m_source, m_url, m_origin_url, m_message_handler));
RETURN_IF_ERROR(m_source->AddProgressListener(this));
m_source->HandleClientChange();
}
if (!m_played_ranges)
{
m_played_ranges = OP_NEW(MediaTimeRanges, ());
if (!m_played_ranges)
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::Play()
{
if (m_force_paused)
return Pause();
RETURN_IF_ERROR(Init());
m_paused = FALSE;
if (m_played_range_start < 0)
GetPosition(m_played_range_start);
if (m_pi_player)
return m_pi_player->Play();
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::Pause()
{
RETURN_IF_ERROR(Init());
m_paused = TRUE;
#if VIDEO_THROTTLING_FPS_HIGH > 0
m_throttler.Break();
#endif // VIDEO_THROTTLING_FPS_HIGH > 0
if (m_pi_player)
return m_pi_player->Pause();
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::Suspend()
{
// Temporary fix for CORE-26421. Ignores callback from the backend while
// the media element is suspended. These callback will need to be handled
// somehow for suspend/resume to work properly. See CORE-27035.
m_suspend = TRUE;
DestroyPlatformPlayer();
#if VIDEO_THROTTLING_FPS_HIGH > 0
m_throttler.Break();
#endif //VIDEO_THROTTLING_FPS_HIGH > 0
if (m_source)
{
ReleaseSource();
m_source = NULL;
#ifdef DEBUG_ENABLE_OPASSERT
m_network_err = FALSE;
m_decode_err = FALSE;
#endif // DEBUG_ENABLE_OPASSERT
}
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::Resume()
{
m_suspend = FALSE;
return Init();
}
#ifdef _DEBUG
static Debug&
operator<<(Debug& d, const OpMediaTimeRanges* ranges)
{
UINT32 length = ranges->Length();
for (UINT32 i = 0; i < length; i++)
{
if (i > 0)
d << ", ";
d << "[";
d << ranges->Start(i);
d << ", ";
d << ranges->End(i);
d << ")";
}
return d;
}
#endif
/* virtual */ OP_STATUS
CoreMediaPlayer::GetBufferedTimeRanges(const OpMediaTimeRanges*& ranges)
{
RETURN_VALUE_IF_NULL(m_pi_player, OpStatus::ERR);
RETURN_IF_ERROR(m_pi_player->GetBufferedTimeRanges(&ranges));
#ifdef DEBUG_ENABLE_OPASSERT
// Verify that the ranges are normalized.
double duration;
OpStatus::Ignore(GetDuration(duration));
double prev_end = op_nan(NULL);
for (UINT32 i = 0; i < ranges->Length(); i++)
{
double start = ranges->Start(i);
double end = ranges->End(i);
OP_ASSERT(start >= 0 && op_isfinite(start));
OP_ASSERT(end > 0 && op_isfinite(end));
OP_ASSERT(op_isnan(prev_end) || prev_end < start);
OP_ASSERT(start < end);
OP_ASSERT(!op_isfinite(duration) || duration >= end);
prev_end = end;
}
OP_NEW_DBG("GetBufferedTimeRanges", "MediaPlayer");
OP_DBG(("duration: %f; buffered: ", duration) << ranges);
#endif // DEBUG_ENABLE_OPASSERT
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::GetSeekableTimeRanges(const OpMediaTimeRanges*& ranges)
{
if (m_pi_player)
return m_pi_player->GetSeekableTimeRanges(&ranges);
return OpStatus::ERR;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::GetPlayedTimeRanges(const OpMediaTimeRanges*& ranges)
{
RETURN_VALUE_IF_NULL(m_played_ranges, OpStatus::ERR);
if (m_played_range_start >= 0)
{
double end;
if (GetPosition(end) == OpStatus::OK)
OpStatus::Ignore(m_played_ranges->AddRange(m_played_range_start, end));
}
ranges = m_played_ranges;
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::GetPosition(double& position)
{
if (m_seeking)
{
position = m_position;
return OpStatus::OK;
}
if (m_pi_player)
return m_pi_player->GetPosition(&position);
position = 0.0;
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::SetPosition(double position)
{
if (position < 0 || !op_isfinite(position))
return OpStatus::ERR_OUT_OF_RANGE;
if (m_played_ranges && m_played_range_start >= 0)
{
double end;
if (GetPosition(end) == OpStatus::OK)
OpStatus::Ignore(m_played_ranges->AddRange(m_played_range_start, end));
}
m_position = position;
if (m_pi_player)
{
RETURN_IF_ERROR(m_pi_player->SetPosition(position));
m_seeking = TRUE;
}
m_played_range_start = position;
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::GetDuration(double& duration)
{
duration = op_nan(NULL);
if (m_pi_player)
return m_pi_player->GetDuration(&duration);
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::SetPlaybackRate(double rate)
{
if (m_pi_player)
return m_pi_player->SetPlaybackRate(rate);
m_rate = rate;
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::SetVolume(double volume)
{
if (m_pi_player)
return m_pi_player->SetVolume(volume);
m_volume = volume;
return OpStatus::OK;
}
/* virtual */ OP_STATUS
CoreMediaPlayer::SetPreload(BOOL preload)
{
m_preload = preload ? g_stdlib_infinity : MEDIA_PRELOAD_DURATION;
if (m_pi_player)
return m_pi_player->SetPreload(m_preload);
return OpStatus::OK;
}
/* virtual */ void
CoreMediaPlayer::GetVideoSize(UINT32& width, UINT32& height)
{
double pixel_ratio;
if (m_pi_player && OpStatus::IsSuccess(m_pi_player->GetNativeSize(&width, &height, &pixel_ratio)))
{
// Increase one dimension if needed to preserve aspect ratio.
if (pixel_ratio > 1.0)
width = (UINT32)(width*pixel_ratio + 0.5);
else if (pixel_ratio > 0.0 && pixel_ratio < 1.0)
height = (UINT32)(height/pixel_ratio + 0.5);
}
else
{
// OpMediaPlayer isn't required to not modify width/height
// when failing, so...
width = height = 0;
}
}
/* virtual */ OP_STATUS
CoreMediaPlayer::GetFrame(OpBitmap*& bitmap)
{
if (m_pi_player)
{
OP_STATUS status = m_pi_player->GetFrame(&bitmap);
if (OpStatus::IsSuccess(status) && !bitmap)
return OpStatus::ERR;
return status;
}
return OpStatus::ERR;
}
/* virtual */ void
CoreMediaPlayer::OnDurationChange(OpMediaPlayer* player)
{
#ifdef DEBUG_ENABLE_OPASSERT
m_duration_known = TRUE;
#endif // DEBUG_ENABLE_OPASSERT
if (m_listener && !m_suspend)
m_listener->OnDurationChange(this);
}
/* virtual */ void
CoreMediaPlayer::OnVideoResize(OpMediaPlayer* player)
{
if (m_listener && !m_suspend)
m_listener->OnVideoResize(this);
}
/* virtual */ void
CoreMediaPlayer::OnFrameUpdate(OpMediaPlayer* player)
{
#if VIDEO_THROTTLING_FPS_HIGH > 0
if (m_throttler.IsFrameUpdateAllowed())
#endif // VIDEO_THROTTLING_FPS_HIGH > 0
{
if (m_listener && !m_suspend)
m_listener->OnFrameUpdate(this);
}
}
/* virtual */ void
CoreMediaPlayer::OnDecodeError(OpMediaPlayer* player)
{
#ifdef DEBUG_ENABLE_OPASSERT
OP_ASSERT(!m_decode_err || !"a decode error is fatal and cannot happen twice");
m_decode_err = TRUE;
#endif // DEBUG_ENABLE_OPASSERT
if (m_listener && !m_suspend)
m_listener->OnDecodeError(this);
}
/* virtual */ void
CoreMediaPlayer::OnPlaybackEnd(OpMediaPlayer* player)
{
OP_ASSERT(m_duration_known || !"Playback ended before duration was known.");
if (m_listener && !m_suspend)
m_listener->OnPlaybackEnd(this);
#if VIDEO_THROTTLING_FPS_HIGH > 0
m_throttler.Break();
#endif // VIDEO_THROTTLING_FPS_HIGH > 0
}
/* virtual */ void
CoreMediaPlayer::OnForcePause(OpMediaPlayer* player)
{
if (m_listener)
m_listener->OnForcePause(this);
}
/* virtual */ void
CoreMediaPlayer::OnSeekComplete(OpMediaPlayer* player)
{
if (m_listener && !m_suspend && m_seeking)
m_listener->OnSeekComplete(this);
m_seeking = FALSE;
}
/* virtual */ void
CoreMediaPlayer::OnStalled(OpMediaPlayer* player)
{
if (m_listener && !m_suspend)
m_listener->OnStalled(this);
}
/* virtual */ void
CoreMediaPlayer::OnProgress(MediaSource* source)
{
OP_ASSERT(source == m_source);
if (m_listener && !m_suspend)
m_listener->OnProgress(this);
// When using a core MediaSource, initialize platform player.
if (!m_pi_player && source)
InitPlatformPlayer(m_pi_manager->CreatePlayer(&m_pi_player, GetHandle()));
}
/* virtual */ void
CoreMediaPlayer::OnError(MediaSource* source)
{
OP_ASSERT(source == m_source);
#ifdef DEBUG_ENABLE_OPASSERT
OP_ASSERT(!m_network_err);
m_network_err = TRUE;
#endif // DEBUG_ENABLE_OPASSERT
if (m_listener && !m_suspend)
m_listener->OnError(this);
}
/* virtual */ void
CoreMediaPlayer::OnIdle(MediaSource* source)
{
OP_ASSERT(source == m_source);
if (m_listener && !m_suspend)
m_listener->OnIdle(this);
// There's no guarantee that OnProgress is called at all (e.g. in
// the case of a cached resource), so create player here too.
if (!m_pi_player && source)
InitPlatformPlayer(m_pi_manager->CreatePlayer(&m_pi_player, GetHandle()));
}
/* virtual */ void
CoreMediaPlayer::OnPauseForBuffering(OpMediaPlayer* player)
{
if (m_listener)
m_listener->OnPauseForBuffering(this);
}
/* virtual */ void
CoreMediaPlayer::OnPlayAfterBuffering(OpMediaPlayer* player)
{
if (m_listener)
m_listener->OnPlayAfterBuffering(this);
}
/* virtual */ void
CoreMediaPlayer::OnClientCollision(MediaSource* source)
{
// Release source and get a new one in Init()
OP_ASSERT(source == m_source);
ReleaseSource();
m_source = NULL;
RAISE_IF_MEMORY_ERROR(Init());
}
void
CoreMediaPlayer::ReleaseSource()
{
OP_ASSERT(m_source);
m_source->RemoveProgressListener(this);
m_source_manager->PutSource(m_source);
}
void
CoreMediaPlayer::InitPlatformPlayer(OP_STATUS status)
{
if (OpStatus::IsSuccess(status))
{
m_pi_player->SetListener(this);
// Initialize state set before platform player was created.
if (m_paused)
m_pi_player->Pause();
else
m_pi_player->Play();
m_pi_player->SetPosition(m_position);
m_pi_player->SetPlaybackRate(m_rate);
m_pi_player->SetVolume(m_volume);
m_pi_player->SetPreload(m_preload);
}
else
{
OP_ASSERT(m_pi_player == NULL);
RAISE_IF_MEMORY_ERROR(status);
// Treat all errors as decode errors.
if (m_listener && !m_suspend)
m_listener->OnDecodeError(this);
}
}
void
CoreMediaPlayer::DestroyPlatformPlayer()
{
m_pi_manager->DestroyPlayer(m_pi_player);
m_pi_player = NULL;
}
#if VIDEO_THROTTLING_FPS_HIGH > 0
void
CoreMediaPlayer::OnFrameUpdateAllowed()
{
if (m_listener)
m_listener->OnFrameUpdate(this);
}
#endif // VIDEO_THROTTLING_FPS_HIGH > 0
#ifdef PI_VIDEO_LAYER
void
CoreMediaPlayer::GetVideoLayerColor(UINT8* red, UINT8* green, UINT8* blue, UINT8* alpha)
{
OpMediaManager::GetVideoLayerColor(red, green, blue, alpha);
}
void
CoreMediaPlayer::SetVideoLayerRect(const OpRect& rect, const OpRect& clipRect)
{
if (m_pi_player)
{
// Notify player only if there is a change in video window
if (!rect.Equals(m_last_screen_rect) || !clipRect.Equals(m_last_clip_rect))
{
m_last_screen_rect = rect;
m_last_clip_rect = clipRect;
m_pi_player->SetVideoLayerRect(rect, clipRect);
}
}
}
#endif //PI_VIDEO_LAYER
#endif // MEDIA_PLAYER_SUPPORT
|
#include "executive.h"
#include <stdexcept>
#include <string>
executive::executive(std::string _filename) {
ifstream input;
string name;
float distance;
int count_review;
string temp;
input.open(_filename);
if (input.is_open()) {
while (!input.eof()) {
getline(input, temp, ',');
int num = stoi(temp);
myheap.Insert(num);
}
} else {
cout << "Cannot open the files!\n";
}
input.close();
Print();
}
executive::~executive() {}
void executive::Print() {
try {
while (true) {
cout << "Please choice one of the following commands:\n";
cout << "1- BuildHeap\n2- Insert\n3- Delete\n4- MinLevelElements\n5- "
"MaxLevelElements\n6- Exit\n";
cout << "Enter your choice:\n";
int choice;
cin >> choice;
cout << "=====================================================\n";
if (choice == 1) {
cout << "Output:\n";
myheap.BuildHeap();
cout << "=====================================================\n";
} else if (choice == 2) {
cout << "Enter element to be inserted:";
int key;
cin >> key;
myheap.Insert(key);
cout << "Output: " << key << " has been inserted successfully!\n";
cout << "=====================================================\n";
} else if (choice == 3) {
int min = myheap.GetMinNode();
myheap.Delete();
cout << "Output: " << min << " has been deleted successfully!\n";
cout << "=====================================================\n";
} else if (choice == 4) {
myheap.MinLevelElements();
cout << "=====================================================\n";
} else if (choice == 5) {
myheap.MaxLevelElements();
cout << "=====================================================\n";
} else if (choice == 6) {
cout << "Output: Bye Bye!\n";
cout << "=========================================================\n";
break;
} else {
throw -1;
break;
}
}
} catch (int num) {
if (num == -1) {
cout << "Input Error!\n";
cout << "=========================================================\n";
} else if (num == -2) {
cout << "Delete the empty tree!\n";
cout << "=========================================================\n";
exit(1);
}
}
}
|
// Created on: 1993-03-10
// Created by: Philippe DAUTRY
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Geom_Line_HeaderFile
#define _Geom_Line_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <gp_Ax1.hxx>
#include <Geom_Curve.hxx>
#include <GeomAbs_Shape.hxx>
#include <Standard_Integer.hxx>
class gp_Lin;
class gp_Pnt;
class gp_Dir;
class gp_Vec;
class gp_Trsf;
class Geom_Geometry;
class Geom_Line;
DEFINE_STANDARD_HANDLE(Geom_Line, Geom_Curve)
//! Describes an infinite line.
//! A line is defined and positioned in space with an axis
//! (gp_Ax1 object) which gives it an origin and a unit vector.
//! The Geom_Line line is parameterized:
//! P (U) = O + U*Dir, where:
//! - P is the point of parameter U,
//! - O is the origin and Dir the unit vector of its positioning axis.
//! The parameter range is ] -infinite, +infinite [.
//! The orientation of the line is given by the unit vector
//! of its positioning axis.
class Geom_Line : public Geom_Curve
{
public:
//! Creates a line located in 3D space with the axis placement A1.
//! The Location of A1 is the origin of the line.
Standard_EXPORT Geom_Line(const gp_Ax1& A1);
//! Creates a line from a non transient line from package gp.
Standard_EXPORT Geom_Line(const gp_Lin& L);
//! Constructs a line passing through point P and parallel to vector V
//! (P and V are, respectively, the origin and the unit
//! vector of the positioning axis of the line).
Standard_EXPORT Geom_Line(const gp_Pnt& P, const gp_Dir& V);
//! Set <me> so that <me> has the same geometric properties as L.
Standard_EXPORT void SetLin (const gp_Lin& L);
//! changes the direction of the line.
Standard_EXPORT void SetDirection (const gp_Dir& V);
//! changes the "Location" point (origin) of the line.
Standard_EXPORT void SetLocation (const gp_Pnt& P);
//! changes the "Location" and a the "Direction" of <me>.
Standard_EXPORT void SetPosition (const gp_Ax1& A1);
//! Returns non transient line from gp with the same geometric
//! properties as <me>
Standard_EXPORT gp_Lin Lin() const;
//! Returns the positioning axis of this line; this is also its local coordinate system.
Standard_EXPORT const gp_Ax1& Position() const;
//! Changes the orientation of this line. As a result, the
//! unit vector of the positioning axis of this line is reversed.
Standard_EXPORT void Reverse() Standard_OVERRIDE;
//! Computes the parameter on the reversed line for the
//! point of parameter U on this line.
//! For a line, the returned value is -U.
Standard_EXPORT Standard_Real ReversedParameter (const Standard_Real U) const Standard_OVERRIDE;
//! Returns the value of the first parameter of this
//! line. This is Standard_Real::RealFirst().
Standard_EXPORT Standard_Real FirstParameter() const Standard_OVERRIDE;
//! Returns the value of the last parameter of this
//! line. This is Standard_Real::RealLast().
Standard_EXPORT Standard_Real LastParameter() const Standard_OVERRIDE;
//! returns False
Standard_EXPORT Standard_Boolean IsClosed() const Standard_OVERRIDE;
//! returns False
Standard_EXPORT Standard_Boolean IsPeriodic() const Standard_OVERRIDE;
//! Returns GeomAbs_CN, which is the global continuity of any line.
Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE;
//! returns True.
//! Raised if N < 0.
Standard_EXPORT Standard_Boolean IsCN (const Standard_Integer N) const Standard_OVERRIDE;
//! Returns in P the point of parameter U.
//! P (U) = O + U * Dir where O is the "Location" point of the
//! line and Dir the direction of the line.
Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt& P) const Standard_OVERRIDE;
//! Returns the point P of parameter u and the first derivative V1.
Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1) const Standard_OVERRIDE;
//! Returns the point P of parameter U, the first and second
//! derivatives V1 and V2. V2 is a vector with null magnitude
//! for a line.
Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2) const Standard_OVERRIDE;
//! V2 and V3 are vectors with null magnitude for a line.
Standard_EXPORT void D3 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2, gp_Vec& V3) const Standard_OVERRIDE;
//! The returned vector gives the value of the derivative for the
//! order of derivation N.
//! Raised if N < 1.
Standard_EXPORT gp_Vec DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE;
//! Applies the transformation T to this line.
Standard_EXPORT void Transform (const gp_Trsf& T) Standard_OVERRIDE;
//! Returns the parameter on the transformed curve for
//! the transform of the point of parameter U on <me>.
//!
//! me->Transformed(T)->Value(me->TransformedParameter(U,T))
//!
//! is the same point as
//!
//! me->Value(U).Transformed(T)
//!
//! This methods returns <U> * T.ScaleFactor()
Standard_EXPORT virtual Standard_Real TransformedParameter (const Standard_Real U, const gp_Trsf& T) const Standard_OVERRIDE;
//! Returns a coefficient to compute the parameter on
//! the transformed curve for the transform of the
//! point on <me>.
//!
//! Transformed(T)->Value(U * ParametricTransformation(T))
//!
//! is the same point as
//!
//! Value(U).Transformed(T)
//!
//! This methods returns T.ScaleFactor()
Standard_EXPORT virtual Standard_Real ParametricTransformation (const gp_Trsf& T) const Standard_OVERRIDE;
//! Creates a new object which is a copy of this line.
Standard_EXPORT Handle(Geom_Geometry) Copy() const Standard_OVERRIDE;
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(Geom_Line,Geom_Curve)
protected:
private:
gp_Ax1 pos;
};
#endif // _Geom_Line_HeaderFile
|
// Created on: 1996-09-04
// Created by: Christian CAILLET
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Transfer_DataInfo_HeaderFile
#define _Transfer_DataInfo_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Type.hxx>
class Standard_Transient;
//! Gives information on an object
//! Used as template to instantiate Mapper and SimpleBinder
//! This class is for Transient
class Transfer_DataInfo
{
public:
DEFINE_STANDARD_ALLOC
//! Returns the Type attached to an object
//! Here, the Dynamic Type of a Transient. Null Type if unknown
Standard_EXPORT static Handle(Standard_Type) Type (const Handle(Standard_Transient)& ent);
//! Returns Type Name (string)
//! Allows to name type of non-handled objects
Standard_EXPORT static Standard_CString TypeName (const Handle(Standard_Transient)& ent);
protected:
private:
};
#endif // _Transfer_DataInfo_HeaderFile
|
#include "use.h"
#include "teacher.h"
#include "student.h"
void doSomething(User &u)
{
u.output();
}
int main()
{
// User user;
// std::cout << User::get_user_count() << std::endl;
// std::cin >> user;
// // user.fname="pritam";
// // user.lname="sarkar";
// // user.set_status("gold");
// std::cout << user << std::endl;
// Teacher teacher;
// teacher.output();
// teacher.fname = "eshani";
// teacher.lname = "jas";
// std::cout << teacher.fname << " " << teacher.lname << std::endl;
Teacher t;
Student s;
User &u1 = t;
User &u2 = s;
doSomething(u1);
doSomething(u2);
return 0;
}
|
//
// Particle.cpp
// w04_h02_particle
//
// Created by Kris Li on 9/28/16.
//
//
#include "Particle.hpp"
Particle::Particle(){
setInitialCondition(ofPoint(0,0), ofPoint(0,0));
}
void Particle::setInitialCondition(ofPoint _pos, ofPoint _vel){
pos.set(_pos.x, _pos.y);
vel.set(_vel.x, _vel.y);
}
void Particle::update(){
vel = vel + force;
pos = pos + vel;
}
void Particle::resetForce(){
force.set(0, 0);
}
void Particle::addRepulsionForce(ofPoint _pos, float _radius, float _strength){
ofPoint posOfForce;
posOfForce.set(_pos.x, _pos.y);
ofPoint diff = pos - posOfForce;
if(diff.length() < _radius){
//smooth
// float pct = 1 - (diff.length() / _radius);
// diff.normalize();
// force += diff * pct * _strength;
//wiggly
diff *= ofMap(diff.length(), 0, _radius, 1.0, 0.0);
force += diff * _strength;
}
}
void Particle::addAttractionForce(ofPoint _pos, float _radius, float _strength){
ofPoint posOfForce;
posOfForce.set(_pos.x, _pos.y);
ofPoint diff = pos - posOfForce;
if(diff.length() < _radius){
//smooth:
// float pct = 1 - (diff.length() / _radius);
// diff.normalize();
// force -= diff * pct * _strength;
//wiggly:
diff *= ofMap(diff.length(), 0, _radius, 1.0, 0.0);
force -= diff * _strength;
}
}
void Particle::bound(){
if(pos.x <0 || pos.x > ofGetWidth()){
vel.x = -0.05*vel.x;
}
if(pos.y <0 || pos.y > ofGetHeight()){
vel.y = -0.05*vel.y;
}
}
void Particle::draw(){
ofCircle(pos, 5);
}
|
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
class Solution {
public:
string addStrings(string num1, string num2) {
string res;
int carry=0,i,j,cur;
for(i=int(num1.size())-1,j=int(num2.size())-1;i>=0||j>=0;i--,j--)
{
if(i<0)
cur=num2[j]-'0'+carry;
else if(j<0)
cur=num1[i]-'0'+carry;
else
cur=(num1[i]-'0')+(num2[j]-'0')+carry;
carry=cur>9?1:0;
cur=cur>9?cur-10:cur;
res.push_back(cur+'0');
}
if(carry)
res.push_back('1');
reverse(res.begin(),res.end());
return res;
}
};
int main()
{
string num1="1243",num2="328748";
Solution solute;
cout<<solute.addStrings(num1,num2)<<endl;
return 0;
}
|
//Phoneix_RK
/*
https://leetcode.com/problems/number-of-islands/
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
*/
class Solution {
public:
void dfs(vector<vector<char>>& grid,int i,int j)
{
if(i<0 || i>=grid.size() || j<0 || j>=grid[i].size() || grid[i][j]=='0')
return;
grid[i][j]='0';
dfs(grid,i-1,j);
dfs(grid,i+1,j);
dfs(grid,i,j-1);
dfs(grid,i,j+1);
}
int numIslands(vector<vector<char>>& grid) {
int count=0;
/*
traverse matrix
if 1 is found
1)incr count
2)do dfs and change all connected 1s to zero
repeat until no 1 is found
return count
*/
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[i].size();j++)
{
if(grid[i][j]=='1')
{
count++;
dfs(grid,i,j);
}
}
}
return count;
}
};
|
#include<iostream>
#include<string>
#define MAX 1000
using namespace std;
void showMenu(){
cout << "***************************" << endl;
cout << "***** 1、添加联系人 *****" << endl;
cout << "***** 2、显示联系人 *****" << endl;
cout << "***** 3、删除联系人 *****" << endl;
cout << "***** 4、查找联系人 *****" << endl;
cout << "***** 5、修改联系人 *****" << endl;
cout << "***** 6、清空联系人 *****" << endl;
cout << "***** 0、退出通讯录 *****" << endl;
cout << "***************************" << endl;
}
struct Person{
string m_name;
int m_Sex;
int m_Age;
string m_Phone;
string m_Addr;
};
struct Addressbooks{
struct Person personArray[MAX];
int m_Size;
};
void addPerson(Addressbooks *abs){
// 定义添加联系人信息的函数
if(abs->m_Size == MAX){
cout<<"通讯录已满,无法继续添加联系人!"<<endl;
}
else{
string name;
cout<<"请输入联系人姓名:\n"<<endl;
cin>>name;
abs->personArray[abs->m_Size].m_name = name;
cout<<"请输入联系人性别:\n"<<endl;
cout<<"1——男:\n"<<endl;
cout<<"2——女:\n"<<endl;
int sex = 0;
cin>>sex;
abs->personArray[abs->m_Size].m_Sex = sex;
cout<<"请输入联系人年龄:\n"<<endl;
int age = 0;
cin>>age;
abs->personArray[abs->m_Size].m_Age = age;
cout<<"请输入联系人电话:\n"<<endl;
string number;
cin>>number;
abs->personArray[abs->m_Size].m_Phone = number;
cout<<"请输入联系人地址:\n"<<endl;
string address;
cin>>address;
abs->personArray[abs->m_Size].m_Addr = address;
abs->m_Size += 1;
cout<<"联系人添加成功!\n";
system("pause");
system("cls");
}
}
int isExist(Addressbooks *abs, string name){
for(int i = 0; i < abs->m_Size; i++){
if(abs->personArray[i].m_name == name){
return i;
}
}
return -1;
}
void delPerson(Addressbooks *abs){
cout<<"请输入要删除的联系人姓名:"<<endl;
string name;
cin>>name;
int ret = isExist(abs, name);
if(ret == -1){
cout<<"不存在要删除的联系人!\n";
}
else{
for(int i = ret; i < abs->m_Size; i++){
abs->personArray[i] = abs->personArray[i+1];
}
abs->m_Size -= 1;
cout<<"删除成功!\n";
}
system("pause");
system("cls");
}
void showPerson(Addressbooks *abs){
if(abs->m_Size == 0){
cout<<"当前通讯录为空!\n";
}
else{
for(int i = 0; i < abs->m_Size; i++){
cout<<"姓名:"<<abs->personArray[i].m_name <<"\n";
cout<<"性别:"<<abs->personArray[i].m_Sex <<"\n";
cout<<"年龄:"<<abs->personArray[i].m_Age <<"\n";
cout<<"电话:"<<abs->personArray[i].m_Phone <<"\n";
cout<<"住址:"<<abs->personArray[i].m_Addr <<"\n";
}
}
system("pause");
system("cls");
}
void serchPerson(Addressbooks *abs){
cout<<"请输入要查找的联系人:\n";
string name;
cin>>name;
int ret = isExist(abs, name);
if(ret == -1){
cout<<"查无此人!\n";
}
else{
cout<<"姓名:"<<abs->personArray[ret].m_name <<"\n";
cout<<"性别:"<<abs->personArray[ret].m_Sex <<"\n";
cout<<"年龄:"<<abs->personArray[ret].m_Age <<"\n";
cout<<"电话:"<<abs->personArray[ret].m_Phone <<"\n";
cout<<"住址:"<<abs->personArray[ret].m_Addr <<"\n";
}
system("pause");
system("cls");
}
void changePerson(Addressbooks *abs){
cout<<"请输入要修改的联系人姓名:\n";
string name;
cin>>name;
int ret = isExist(abs, name);
if(ret == -1){
cout<<"不存在此联系人!\n";
}
else{
string name2;
cout<<"请输入修改后的姓名:";
cin>>name2;
abs->personArray[ret].m_name = name2;
string number;
cout<<"请输入修改后的电话:";
cin>>number;
abs->personArray[ret].m_Phone = number;
string address;
cout<<"请输入修改后的地址:";
cin>>address;
abs->personArray[ret].m_Addr = address;
cout<<"修改成功!\n"<<endl;
}
system("pause");
system("cls");
}
void clearPerson(Addressbooks *abs){
cout<<"请确认是否清空通讯录(yes)!\n";
string sure;
cin>>sure;
if(sure == "yse"){
abs->m_Size = 0;
cout<<"通讯录已清空!\n";
}
else{
showMenu();
}
}
int main() {
Addressbooks abs; // 创建通讯录
abs.m_Size = 0; // 初始化通讯录人数为0
int select = 0;
while (true)
{
showMenu();
cin >> select;
switch (select)
{
case 1: //添加联系人
addPerson(&abs);
break;
case 2: //显示联系人
showPerson(&abs);
break;
case 3: //删除联系人
delPerson(&abs);
break;
case 4: //查找联系人
serchPerson(&abs);
break;
case 5: //修改联系人
changePerson(&abs);
break;
case 6: //清空联系人
clearPerson(&abs);
break;
case 0: //退出通讯录
cout << "欢迎下次使用" << endl;
system("pause");
return 0;
break;
default:
break;
}
}
system("pause");
return 0;
}
|
/**
* @file library_export.hpp
*
* @todo Add description
*
* @author Matthew Rodusek (matthew.rodusek@gmail.com)
* @date Nov 30, 2015
*
*/
/*
* Change Log:
*
* Nov 30, 2015:
* - library_export.hpp created
*/
#ifndef VALKNUT_CORE_INTERNAL_LIBRARY_EXPORT_HPP_
#define VALKNUT_CORE_INTERNAL_LIBRARY_EXPORT_HPP_
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
//!
//! @def VALKNUT_API_EXPORT
//! @brief Expands to compiler/platform specific symbol export statement
//!
//! @def VALKNUT_API_IMPORT
//! @brief Expands to compiler/platform specific symbol import statement
//!
//! @def VALKNUT_API_LOCAL
//! @brief Decrease visibility to just the library (usable only in linux)
//!
#ifdef STATIC_BUILD
# define VALKNUT_API_EXPORT /* not used */
# define VALKNUT_API_IMPORT /* not used */
# define VALKNUT_API_LOCAL /* not used */
#else
# define VALKNUT_API_EXPORT VALKNUT_COMPILER_SYMBOL_EXPORT
# define VALKNUT_API_IMPORT VALKNUT_COMPILER_SYMBOL_IMPORT
# define VALKNUT_API_LOCAL VALKNUT_COMPILER_SYMBOL_VISIBLE
#endif
//!
//! @def VALKNUT_API
//! @brief Expands to export on DLL build, import otherwise
//!
#ifdef BUILD_DLL
# define VALKNUT_API VALKNUT_API_EXPORT // Export the symbols to the library
#else
# define VALKNUT_API VALKNUT_API_IMPORT // Import symbols from the library
#endif
//!
//! @def VALKNUT_IMPEXP
//!
//! @brief DLL-building import/export symbol.
//!
//! Expands to compiler and platform specific import or export symbol if
//! building or reading from DLL, otherwise expands to nothing if statically
//! linking.
//!
#if defined(STATIC_BUILD) || defined(NO_DLL)
# define VALKNUT_IMPEXP
#elif defined(BUILD_DLL)
# define VALKNUT_IMPEXP VALKNUT_API_EXPORT
#else
# define VALKNUT_IMPEXP VALKNUT_API_IMPORT
#endif
//!
//! @def VALKNUT_CAPI
//!
//! @brief Symbol to denote the calling conventions for a C DLL
//!
#ifndef VALKNUT_CAPI
# if defined(__GNUC__) || (defined(_MSC_VER) && (_MSC_VER >= 800))
# define VALKNUT_CAPI VALKNUT_CDECL
# else
# define VALKNUT_CAPI VALKNUT_STDCALL
# endif
#endif
//!
//! @def VALKNUT_EXPORT_TYPE( type )
//!
//! @brief Expands to the type along with the import/export symbol
//!
#ifndef VALKNUT_EXPORT_TYPE
# define VALKNUT_EXPORT_TYPE( type ) VALKNUT_IMPEXP type
#endif
//!
//! @def VALKNUT_PROTOTYPE( type, name, args, attributes )
//!
//! @brief Expands into a function prototype containing attributes,
//! return type, name, and arguments.
//!
#ifndef VALKNUT_PROTOTYPE
# define VALKNUT_PROTOTYPE( type, name, args, attributes ) attributes type name args
#endif
//!
//! @def VALKNUT_EXPORT_CA( type, name, args, attributes )
//!
//! @brief Expands into an export statement for a C function that contains
//! attributes. Note that this must be in an extern "C" statement.
//!
#ifndef VALKNUT_EXPORT_CA
# define VALKNUT_EXPORT_CA( type, name, args, attributes ) \
VALKNUT_PROTOTYPE( \
VALKNUT_IMPEXP type, \
(VALKNUT_API name), \
args, \
extern attributes \
)
#endif
//!
//! @def VALKNUT_EXPORT_C( type, name, args, attributes )
//!
//! @brief Expands into an export statement for a C function prototype.
//! Note that this must be in an extern "C" statement.
//!
#ifndef VALKNUT_EXPORT_C
# define VALKNUT_EXPORT_C( type, name, args ) VALKNUT_EXPORT_CA( type, name, args, VALKNUT_EMPTY )
#endif
//!
//! @def VALKNUT_EXPORT_A( type, name, args, attributes )
//!
//! @brief Expands into an export statement for a C++ function prototype
//! containing function attributes.
//!
//! Note that this does not belong in an extern "C" statement, and should
//! not be in a class body/method signature.
//!
#ifndef VALKNUT_EXPORT_A
# define VALKNUT_EXPORT_A( type, name, args, attributes ) \
VALKNUT_PROTOTYPE( \
VALKNUT_IMPEXP type, \
name, \
args, \
attributes \
)
#endif
//!
//! @def VALKNUT_EXPORT( type, name, args )
//!
//! @brief Expands into an export statement for a C++ function prototype.
//!
//! Note that this does not belong in an extern "C" statement, and should
//! not be in a class body/method signature.
//!
#ifndef VALKNUT_EXPORT
# define VALKNUT_EXPORT( type, name, args ) VALKNUT_EXPORT_A(type, name, args, VALKNUT_EMPTY )
#endif
#endif /* VALKNUT_CORE_INTERNAL_LIBRARY_EXPORT_HPP_ */
|
// OpenVDB_Softimage
// VDB_Node_MeshToVolume.h
// Mesh to Volume custom ICE node
#ifndef VDB_NODE_MESHTOVOLUME_H
#define VDB_NODE_MESHTOVOLUME_H
#include <xsi_pluginregistrar.h>
#include <xsi_status.h>
#include <xsi_icenodecontext.h>
#include <openvdb/openvdb.h>
class VDB_Node_MeshToVolume
{
public:
VDB_Node_MeshToVolume();
~VDB_Node_MeshToVolume();
XSI::CStatus Evaluate(XSI::ICENodeContext& ctxt);
static XSI::CStatus Register(XSI::PluginRegistrar& reg);
private:
bool m_isDirty;
openvdb::math::Transform::Ptr m_transform;
};
#endif
|
#include <PA9.h>
#include "PlayerProfile.h"
#include "DSspecs.h"
#include "InitFat.h"
#include <fat.h>
#include <unistd.h>
#include <sys/dir.h>
PlayerProfile::PlayerProfile()
:m_nameLength(0), m_level(0), m_experience(0){
SetName("");
}
PlayerProfile::PlayerProfile(const PlayerProfile &pp)
:m_level(pp.m_level), m_experience(pp.m_experience){
SetName(pp.m_name);
}
PlayerProfile::~PlayerProfile(){};
void PlayerProfile::Copy(const PlayerProfile &pp){
Set(pp.m_name, pp.m_level, pp.m_experience);
}
void PlayerProfile::Set(const char * const name, u8 level, u16 exp){
SetName(name);
SetLevel(level);
SetExperience(exp);
}
void PlayerProfile::SetName(const char * const name){
for(m_nameLength=0; m_nameLength<PLAYER_PROFILE_MAX_NAMELENGTH; m_nameLength++){
m_name[m_nameLength] = name[m_nameLength];
if(m_name[m_nameLength] == '\0') break;
}
m_name[PLAYER_PROFILE_MAX_NAMELENGTH] = '\0';
}
void PlayerProfile::SetLevel(u8 level){
m_level = level;
}
void PlayerProfile::SetExperience(u16 exp){
m_experience = exp;
}
void PlayerProfile::AddExperience(u16 exp){
m_experience += exp;
}
bool PlayerProfile::CheckLevelUp(){
if(m_experience >= PLAYER_PROFILE_EXP_FOR_LVLUP){
m_level++;
m_experience -= PLAYER_PROFILE_EXP_FOR_LVLUP;
return true;
}
return false;
}
const char * const PlayerProfile::Name()const{
return m_name;
}
u8 PlayerProfile::NameLength()const{
return m_nameLength;
}
u8 PlayerProfile::Level()const{
return m_level;
}
u8 PlayerProfile::Experience()const{
return m_experience;
}
bool PlayerProfile::IsInitialized()const{
return !(m_nameLength == 0 && m_name[0] == '\0' && m_level == 0 && m_experience == 0);
}
void PlayerProfile::Read(FILE * f){
fread(&m_nameLength, sizeof(m_nameLength), 1, f);
fread(m_name, sizeof(char), PLAYER_PROFILE_MAX_NAMELENGTH+1, f);
fread(&m_level, sizeof(m_level), 1, f);
fread(&m_experience, sizeof(m_experience), 1, f);
}
void PlayerProfile::Write(FILE * f){
fwrite(&m_nameLength, sizeof(m_nameLength), 1, f);
fwrite(m_name, sizeof(char), PLAYER_PROFILE_MAX_NAMELENGTH+1, f);
fwrite(&m_level, sizeof(m_level), 1, f);
fwrite(&m_experience, sizeof(m_experience), 1, f);
}
void LoadPlayerProfiles(PlayerProfile * pp, u8 amount){
if(FAT_INIT_SUCCESS){
FILE *f = fopen(SAVE_PATH, READ_MODE);
if(f != NULL){
for(u8 i=0; i<amount; i++) pp[i].Read(f);
fclose(f);
return;
}
}
for(u8 i=0; i<amount; i++) pp[i].Set("", 0, 0); //no success, fill the classes with emptyness
//debug account
pp[0].Set("No saving:(", 40, 8);
}
void SavePlayerProfiles(PlayerProfile * pp, u8 amount){
PA_InitText(DS_TOP, BG_TEXT);
if(FAT_INIT_SUCCESS){
PA_OutputSimpleText(DS_TOP, 0, 0, "fatinit success");
DIR_ITER* dir;
dir = diropen(SAVE_DIR);
if(dir == NULL){
PA_OutputSimpleText(DS_TOP, 0, 3, "can't open directory, creating directory");
mkdir(SAVE_DIR, 0);
dir = diropen(SAVE_DIR);
if(dir == NULL){
PA_OutputSimpleText(DS_TOP, 0, 4, "can't create directory");
return;
}
}
PA_OutputSimpleText(DS_TOP, 0, 5, "changing directory");
chdir(SAVE_DIR);
PA_OutputSimpleText(DS_TOP, 0, 6, "opening savefile");
FILE *f = fopen(SAVE_PATH, WRITE_MODE);
if(f != NULL){
PA_OutputSimpleText(DS_TOP, 0, 7, "saving");
for(u8 i=0; i<amount; i++) pp[i].Write(f);
fclose(f);
}
PA_OutputSimpleText(DS_TOP, 0, 8, "saving done");
}
else{
PA_OutputSimpleText(DS_TOP, 0, 0, "saving is not supported on emulators");
}
}
|
#include "Stonewt.h"
using std::cout;
Stonewt::Stonewt(double lbs) :stone((int)lbs / Lbs_per_stn), pds_left((int)lbs% Lbs_per_stn + lbs - (int)lbs), pounds(lbs)
{
}
Stonewt::Stonewt(int stn, double lbs) : stone(stn), pds_left(lbs), pounds(stn* Lbs_per_stn + lbs)
{
}
Stonewt::Stonewt() : stone(0), pds_left(0), pounds(0)
{
}
Stonewt::~Stonewt() {}
void Stonewt::show_lbs() const
{
cout << pounds << " pounds\n";
}
void Stonewt::show_stn() const
{
cout << stone << " stone, " << pds_left << " pounds\n";
}
bool Stonewt::operator>(const Stonewt& s)
{
return pounds > s.pounds;
}
bool Stonewt::operator>=(const Stonewt& s)
{
return pounds >= s.pounds;
}
bool Stonewt::operator<(const Stonewt& s)
{
return pounds < s.pounds;
}
bool Stonewt::operator<=(const Stonewt& s)
{
return pounds <= s.pounds;
}
bool Stonewt::operator==(const Stonewt& s)
{
return pounds == s.pounds;
}
bool Stonewt::operator!=(const Stonewt& s)
{
return pounds != s.pounds;
}
|
//
// CompositeByteCompressor.cpp
// Garmin-Encode
//
// Created by Quinn Ramsay on 2018-11-28.
// Copyright © 2018 Quinnter. All rights reserved.
//
#include "CompositeByteCompressor.h"
CompositeByteCompressor::CompositeByteCompressor()
{
}
CompositeByteCompressor::~CompositeByteCompressor()
{
for(auto compressor : m_compressors)
{
delete compressor;
}
m_compressors.clear();
}
int CompositeByteCompressor::compress(unsigned char* data_ptr, int data_size)
{
auto currSize = data_size;
for(auto compressor : m_compressors)
{
currSize = compressor->compress(data_ptr, currSize);
}
return currSize;
}
int CompositeByteCompressor::decompress(unsigned char* data_ptr, int data_size)
{
//reverse iterate A(B(x)) !== B(A(x))
auto currSize = data_size;
for(auto i = m_compressors.rbegin(); i != m_compressors.rend(); ++i)
{
currSize = (*i)->decompress(data_ptr, currSize);
}
return currSize;
}
void CompositeByteCompressor::AddCompressor(IByteCompressor* compressor) {
if(compressor == nullptr)
return;
m_compressors.push_back(compressor);
}
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@tiliae.eu *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#ifndef BAJKAAPP_H_
#define BAJKAAPP_H_
#ifdef USE_CHIPMUNK
#include <chipmunk.h>
#endif
#include "Geometry.h"
#include "Model.h"
#include "IDispatcher.h"
#include "ReflectionMacros.h"
#include "../events/types/IEvent.h"
#include "ModelManager.h"
#include "Config.h"
#ifdef ANDROID
#include <android/input.h>
namespace Util {
struct AndroidEngine;
}
#endif
namespace Util {
class Impl;
/**
* Bajka application. It is bound to OpenGL and is not meant to
* be used with any other technologies (i.e. DirectX). Implements
* the main loop.
*/
class App : public Core::Object {
public:
C__ (void)
App ();
virtual ~App ();
void init ();
m_ (loop) void loop ();
m_ (destroy) void destroy ();
/*--------------------------------------------------------------------------*/
Config *getConfig () const;
m_ (setConfig) void setConfig (Config *b);
/// Głowny model.
Model::IModel *getModel () const;
/**
* 1. Odłącza poprzedni rootControloer od dispatcherów.
* 2. Ustawia główny kontroler.
* 3. Podłącza ten nowy do wszystkich dispatcherów.
*/
S_ (setModel) void setModel (Model::IModel *model);
/**
* Resetuje stan, dropuje iterację, resetuje dispatchery,
* resetuje tweeny etc.
*/
void reset ();
Event::DispatcherList *getDispatchers () const;
m_ (setDispatchers) void setDispatchers (Event::DispatcherList *d);
ModelManager *getManager ();
S_ (setManager) void setManager (ModelManager *m);
static App *instance ();
static void setInstance (App *i) { instance_ = i; }
/**
* Powoduje zawieszenie wykonywania aktualnej iteracji i rozpoczęcie następnej.
* Wszystkie czekające eventy zostają odrzucone etc.
*/
void dropIteration ();
bool getDropIteration () const;
/*-----platform dependent---------------------------------------------------*/
#ifdef ANDROID
AndroidEngine const *getAndroidEngine () const;
AndroidEngine *getAndroidEngine ();
// Standardowy handler CMD z android AppGlue
void engineHandleCmd (int32_t cmd);
int32_t engineHandleInput (AInputEvent* androidEvent);
#endif
private:
Impl *impl;
static App *instance_;
E_ (App)
};
} // nam
extern Util::App *app ();
extern Util::Config *config ();
extern Util::ModelManager *manager ();
#endif /* BAJKAAPP_H_ */
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2002 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#ifdef ECMASCRIPT_DEBUGGER
#include "modules/ecmascript_utils/esdebugger.h"
#include "modules/ecmascript_utils/esenginedebugger.h"
#include "modules/ecmascript_utils/esremotedebugger.h"
#include "modules/ecmascript/ecmascript.h"
#include "modules/util/simset.h"
class ES_DebugThread;
class ES_DebugRuntime;
class ES_DebugSession;
/* ===== ES_DebugBackend ====================================== */
ES_DebugBackend::ES_DebugBackend()
: frontend(NULL)
{
}
/* virtual */
ES_DebugBackend::~ES_DebugBackend()
{
}
/* ===== ES_DebugPosition ========================================== */
ES_DebugPosition::ES_DebugPosition()
: scriptid(0), linenr(0)
{
}
ES_DebugPosition::ES_DebugPosition(unsigned scriptid, unsigned linenr)
: scriptid(scriptid), linenr(linenr)
{
}
BOOL ES_DebugPosition::operator==(const ES_DebugPosition &other) const
{
return scriptid == other.scriptid && linenr == other.linenr;
}
BOOL ES_DebugPosition::operator!=(const ES_DebugPosition &other) const
{
return !operator==(other);
}
BOOL ES_DebugPosition::Valid() const
{
return scriptid != 0 && linenr != 0;
}
/* ===== ES_DebugObjectInfo ============================================= */
ES_DebugObjectInfo::ES_DebugObjectInfo()
{
prototype.info = 0;
flags.init = 0;
class_name = NULL;
function_name = NULL;
}
ES_DebugObjectInfo::~ES_DebugObjectInfo()
{
if (flags.packed.delete_function_name)
op_free(function_name);
if (flags.packed.delete_class_name)
op_free(class_name);
OP_DELETE(prototype.info);
}
/* ===== ES_DebugObjectProperties ======================================= */
ES_DebugObjectProperties::ES_DebugObjectProperties()
: properties_count(0),
properties (NULL)
{
object.info = 0;
}
ES_DebugObjectProperties::~ES_DebugObjectProperties()
{
OP_DELETEA(properties);
OP_DELETE(object.info);
}
/* ===== ES_DebugObjectProperties::Property ============================= */
ES_DebugObjectProperties::Property::Property()
{
name = 0;
}
ES_DebugObjectProperties::Property::~Property()
{
op_free(name);
}
/* ===== ES_DebugObjectChain ================================================== */
ES_DebugObjectChain::ES_DebugObjectChain()
: prototype(NULL)
{
}
ES_DebugObjectChain::~ES_DebugObjectChain()
{
OP_DELETE(prototype);
}
/* ===== ES_DebugValue ================================================== */
ES_DebugValue::ES_DebugValue()
: type(VALUE_UNDEFINED),
is_8bit(FALSE),
owns_value(FALSE)
{
}
ES_DebugValue::~ES_DebugValue()
{
if (owns_value)
if (type == VALUE_STRING)
if (is_8bit)
OP_DELETEA(value.string8.value);
else
OP_DELETEA(value.string16.value);
else if (type == VALUE_OBJECT)
OP_DELETE(value.object.info);
}
OP_STATUS
ES_DebugValue::GetString(OpString& str) const
{
if (type != VALUE_STRING && type != VALUE_STRING_WITH_LENGTH)
return OpStatus::ERR;
int len = KAll;
if (type == VALUE_STRING_WITH_LENGTH)
len = (is_8bit ? value.string8.length : value.string16.length);
if (is_8bit)
return str.Set(value.string8.value, len);
else
return str.Set(value.string16.value, len);
}
/* ===== ES_DebugReturnValue ============================================ */
ES_DebugReturnValue::ES_DebugReturnValue()
{
function.id = 0;
function.info = 0;
}
ES_DebugReturnValue::~ES_DebugReturnValue()
{
if (function.id && function.info)
OP_DELETE(function.info);
OP_DELETE(next);
}
/* ===== ES_DebugStackFrame ============================================ */
ES_DebugStackFrame::ES_DebugStackFrame()
: scope_chain(NULL)
, scope_chain_length(0)
{
function.info = 0;
arguments.info = 0;
this_obj.info = 0;
}
ES_DebugStackFrame::~ES_DebugStackFrame()
{
OP_DELETE(function.info);
OP_DELETE(arguments.info);
OP_DELETE(this_obj.info);
OP_DELETEA(scope_chain);
}
/* ===== ES_DebugFrontend =============================================== */
ES_DebugFrontend::ES_DebugFrontend()
: dbg_backend(NULL)
{
}
ES_DebugFrontend::~ES_DebugFrontend()
{
}
OP_STATUS
ES_DebugFrontend::ConstructEngineBackend(ES_DebugWindowAccepter* accepter)
{
#ifdef ECMASCRIPT_ENGINE_DEBUGGER
dbg_backend = OP_NEW(ES_EngineDebugBackend, ());
if (!dbg_backend)
return OpStatus::ERR_NO_MEMORY;
return static_cast<ES_EngineDebugBackend *>(dbg_backend)->Construct(this, accepter);
#else // ECMASCRIPT_ENGINE_DEBUGGER
return OpStatus::ERR;
#endif // ECMASCRIPT_ENGINE_DEBUGGER
}
OP_STATUS
ES_DebugFrontend::ConstructRemoteBackend(BOOL active, const OpStringC &address, int port)
{
#ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND
dbg_backend = OP_NEW(ES_RemoteDebugBackend, ());
if (!dbg_backend)
return OpStatus::ERR_NO_MEMORY;
return ((ES_RemoteDebugBackend *) dbg_backend)->Construct(this, active, address, port);
#else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND
return OpStatus::ERR;
#endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND
}
void
ES_DebugFrontend::ExportObject(ES_Runtime *rt, ES_Object *internal, ES_DebugObject &external, BOOL chain_info)
{
dbg_backend->ExportObject(rt, internal, external, chain_info);
}
void
ES_DebugFrontend::ExportValue(ES_Runtime *rt, const ES_Value &internal, ES_DebugValue &external, BOOL chain_info)
{
dbg_backend->ExportValue(rt, internal, external, chain_info);
}
OP_STATUS
ES_DebugFrontend::Detach()
{
OP_STATUS status;
if (dbg_backend)
{
status = dbg_backend->Detach();
OP_DELETE(dbg_backend);
dbg_backend = NULL;
}
else
status = OpStatus::OK;
return status;
}
OP_STATUS
ES_DebugFrontend::Runtimes(unsigned tag, OpUINTPTRVector &runtime_ids, BOOL force_create_all)
{
return dbg_backend->Runtimes(tag, runtime_ids, force_create_all);
}
OP_STATUS
ES_DebugFrontend::Continue(unsigned dbg_runtime_id, ES_DebugFrontend::Mode mode)
{
return dbg_backend->Continue(dbg_runtime_id, mode);
}
OP_STATUS
ES_DebugFrontend::Backtrace(ES_Runtime *runtime, ES_Context *context, unsigned max_frames, unsigned &length, ES_DebugStackFrame *&frames)
{
return dbg_backend->Backtrace(runtime, context, max_frames, length, frames);
}
OP_STATUS
ES_DebugFrontend::Backtrace(unsigned dbg_runtime_id, unsigned dbg_thread_id, unsigned max_frames, unsigned &length, ES_DebugStackFrame *&frames)
{
return dbg_backend->Backtrace(dbg_runtime_id, dbg_thread_id, max_frames, length, frames);
}
OP_STATUS
ES_DebugFrontend::Eval(unsigned tag, unsigned dbg_runtime_id, unsigned dbg_thread_id, unsigned frame_index, const uni_char *string, unsigned string_length, ES_DebugVariable *variables, unsigned variables_count, BOOL want_debugging)
{
return dbg_backend->Eval(tag, dbg_runtime_id, dbg_thread_id, frame_index, string, string_length, variables, variables_count, want_debugging);
}
OP_STATUS
ES_DebugFrontend::Examine(unsigned dbg_runtime_id, unsigned objects_count, unsigned *object_ids, BOOL examine_prototypes, BOOL skip_non_enum, ES_DebugPropertyFilters *filters, /* out */ ES_DebugObjectChain *&chains, unsigned int async_tag)
{
return dbg_backend->Examine(dbg_runtime_id, objects_count, object_ids, examine_prototypes, skip_non_enum, filters, chains, async_tag);
}
BOOL
ES_DebugFrontend::HasBreakpoint(unsigned id)
{
return dbg_backend->HasBreakpoint(id);
}
OP_STATUS
ES_DebugFrontend::AddBreakpoint(unsigned id, const ES_DebugBreakpointData &data)
{
return dbg_backend->AddBreakpoint(id, data);
}
OP_STATUS
ES_DebugFrontend::RemoveBreakpoint(unsigned id)
{
return dbg_backend->RemoveBreakpoint(id);
}
OP_STATUS
ES_DebugFrontend::SetStopAt(const StopType stop_type, const BOOL value)
{
return dbg_backend->SetStopAt(stop_type, value);
}
OP_STATUS
ES_DebugFrontend::GetStopAt(StopType stop_type, BOOL &return_value)
{
return dbg_backend->GetStopAt(stop_type, return_value);
}
OP_STATUS
ES_DebugFrontend::Break(unsigned dbg_runtime_id, unsigned dbg_thread_id)
{
return dbg_backend->Break(dbg_runtime_id, dbg_thread_id);
}
void
ES_DebugFrontend::Prune()
{
if (dbg_backend)
dbg_backend->Prune();
}
void
ES_DebugFrontend::FreeObject(unsigned object_id)
{
if (dbg_backend)
dbg_backend->FreeObject(object_id);
}
void
ES_DebugFrontend::FreeObjects()
{
if (dbg_backend)
dbg_backend->FreeObjects();
}
ES_Object *
ES_DebugFrontend::GetObjectById(ES_Runtime *runtime, unsigned object_id)
{
return dbg_backend->GetObjectById(runtime, object_id);
}
ES_Object *
ES_DebugFrontend::GetObjectById(unsigned object_id)
{
return dbg_backend->GetObjectById(object_id);
}
ES_Runtime *
ES_DebugFrontend::GetRuntimeById(unsigned runtime_id)
{
return dbg_backend->GetRuntimeById(runtime_id);
}
unsigned
ES_DebugFrontend::GetObjectId(ES_Runtime *rt, ES_Object *object)
{
return dbg_backend->GetObjectId(rt, object);
}
unsigned
ES_DebugFrontend::GetRuntimeId(ES_Runtime *runtime)
{
return dbg_backend->GetRuntimeId(runtime);
}
unsigned
ES_DebugFrontend::GetThreadId(ES_Thread *thread)
{
return dbg_backend->GetThreadId(thread);
}
ES_DebugReturnValue *
ES_DebugFrontend::GetReturnValue(unsigned dbg_runtime_id, unsigned dbg_thread_id)
{
return dbg_backend->GetReturnValue(dbg_runtime_id, dbg_thread_id);
}
OP_STATUS
ES_DebugFrontend::GetFunctionPosition(unsigned dbg_runtime_id, unsigned function_id, unsigned &script_guid, unsigned &line_no)
{
return dbg_backend->GetFunctionPosition(dbg_runtime_id, function_id, script_guid, line_no);
}
void
ES_DebugFrontend::ResetFunctionFilter()
{
dbg_backend->ResetFunctionFilter();
}
OP_STATUS
ES_DebugFrontend::AddFunctionClassToFilter(const char* classname)
{
return dbg_backend->AddFunctionClassToFilter(classname);
}
void
ES_DebugFrontend::SetReformatFlag(BOOL enable)
{
dbg_backend->SetReformatFlag(enable);
}
OP_STATUS
ES_DebugFrontend::SetReformatConditionFunction(const uni_char *source)
{
return dbg_backend->SetReformatConditionFunction(source);
}
#endif // ECMASCRIPT_DEBUGGER
|
#ifndef EVENTPULL_H
#define EVENTPULL_H
#include <thread>
#include <string>
#include <queue>
class APIPULL
{
std::thread apiThread;
std::string URI;
bool isRunning;
std::queue<std::string> *statusQueue;
void doWork();
public:
APIPULL(std::string URI);
~APIPULL();
void Run();
void addToStatusQueue(const std::string &URI);
void Stop();
};
#endif
|
//
// Created by cis505 on 12/1/17.
//
#include <grpc++/grpc++.h>
#include "../common/WriteServiceClient.h"
#include <thread>
int main(int argc, char *argv[]) {
string address1 = "0.0.0.0:50051";
WriteServiceClient client1(grpc::CreateChannel(address1, grpc::InsecureChannelCredentials()));
vector<string> replicas;
string address2 = "0.0.0.0:50052";
replicas.push_back(address2);
//
// client1.WriteCommand("rowkey1", "colkey1", "value1", WriteType::PUT, FileType::EMAIL, replicas, 1);
//
//
// client1.WriteCommand("rowkey2", "colkey2", "value2", WriteType::PUT, FileType::EMAIL, replicas, 2);
client1.WriteCommand("rowkey2", "colkey2", "value4", WriteType::PUT, FileType::EMAIL, replicas, 4);
client1.WriteCommand("rowkey5", "colkey5", "value5", WriteType::PUT, FileType::EMAIL, replicas, 5);
// WriteServiceClient client2(grpc::CreateChannel(address2, grpc::InsecureChannelCredentials()));
//
// client2.WriteCommand("rowkey3", "colkey3", "value3", WriteType::PUT, FileType::EMAIL, replicas, 3);
}
|
//
// GFireAttack.h
// Core
//
// Created by Max Yoon on 11. 8. 29..
// Copyright 2011년 __MyCompanyName__. All rights reserved.
//
#ifndef Core_GFireAttack_h
#define Core_GFireAttack_h
class GFireAttack : public GFarAttack
{
GnDeclareCreateAttack;
public:
static GFarAttack* CreateAttack(guint32 uIndex);
public:
void Update(float fTime);
void SetPosition(GnVector2 cPos);
};
#endif
|
#include <stdio.h>
#include <math.h>
#include "Maze.h"
int** _maze;
bool inSquare = false;
int c_x, c_z;
Maze::Maze(void)
{
_sizeWidth = 50; // Default size
_sizeHeight = 50;
c_x = -1;
c_z = -1;
}
Maze::~Maze(void)
{
}
void Maze::newMaze(int width, int height)
{
_mazeGen.generateNewMaze(width, height);
_maze = _mazeGen.getMaze();
_sizeWidth = width;
_sizeHeight = height;
// Set starting and end points
start.setPoint(0, 0);
end.setPoint(_sizeWidth, _sizeHeight);
// Set visited
_visited = new int*[width];
for (int i = 0; i < width; ++i)
_visited[i] = new int[height];
for (int i = 0; i < width; i++)
for(int j = 0; j < height; j++)
_visited[i][j] = 0;
}
bool Maze::isValidMove(float x, float y, Direction face)
{
// Check boundries
if (x < -0.25 || x > _sizeWidth - 0.75)
return false;
if (y < -0.25 || y > _sizeHeight - 0.75)
return false;
// Check maze array
int check_x = int(x + 0.5);
int check_y = int(y + 0.5);
if (_maze[check_x][check_y] > 0)
return false;
// Valid move
return true;
}
void Maze::markMovement(float x, float z)
{
int m_x = int(x + 0.5);
int m_z = int(z + 0.5);
_visited[m_x][m_z] = 1;
}
bool Maze::isStartPoint(float x, float z)
{
int m_x = int(x + 0.5);
int m_z = int(z + 0.5);
return (start.getX() == m_x && start.getY() == m_z);
}
bool Maze::isEndPoint(float x, float z)
{
int m_x = int(x + 0.5);
int m_z = int(z + 0.5);
return (end.getX() == m_x && end.getY() == m_z);
}
int Maze::getWidth() { return _sizeWidth; }
int Maze::getHeight() { return _sizeHeight; }
int **Maze::getMaze() { return _maze; }
void Maze::setVisitedAt(int x, int z, int increment) { _visited[x][z] += increment; }
int Maze::getVisitedAt(int x, int z) { return _visited[x][z]; };
|
#include "ofApp.h"
//-----------------------------------------------------------------------------------------
//
void ofApp::setup()
{
//ofSetLogLevel( OF_LOG_VERBOSE );
ofSetFrameRate( 60 );
fontSmall.loadFont("Fonts/DIN.otf", 8 );
ofxGuiSetDefaultWidth( 300 );
int texSize = 128;
particles.init( texSize ); // number of particles is (texSize * texSize)
// Give us a starting point for the camera
camera.setNearClip(0.01f);
camera.setPosition( 0, 0.5, 0.9 );
camera.setMovementMaxSpeed( 0.01f );
time = 0.0f;
timeStep = 1.0f / 60.0f;
videoPlayer.loadMovie("Movies/SilhouetteTest.mov");
videoPlayer.setLoopState( OF_LOOP_NORMAL );
videoPlayer.play();
drawGui = false;
}
//-----------------------------------------------------------------------------------------
//
void ofApp::update()
{
// Update time, this let's us hit space and slow down time, even reverse it.
if( ofGetKeyPressed(' ') ) { timeStep = ofLerp( timeStep, ofMap( ofGetMouseX(), 0, ofGetWidth(), -(1.0f/60.0f), (1.0f/60.0f) ), 0.1f );}
else { timeStep = ofLerp( timeStep, 1.0f / 120.0f, 0.1f ); } // *********************** TEMP, slowing down time a bit, set back to normal time once we change the sim
time += timeStep;
bool haveNewData = false;
videoPlayer.update();
if( videoPlayer.isFrameNew() )
{
spawnPositions.clear();
ofPixels& maskPixels = videoPlayer.getPixelsRef();
int channels = maskPixels.getNumChannels();
int w = maskPixels.getWidth();
int h = maskPixels.getHeight();
float relwh = w/h;
float relhw = h/w;
int tmpIndex = 0;
for( int y = 0; y < h; y++ )
{
for( int x = 0; x < w; x++ )
{
ofVec3f maskValue;
maskValue.x = maskPixels[ (tmpIndex * channels) + 0 ];
maskValue.y = maskPixels[ (tmpIndex * channels) + 1 ];
maskValue.z = maskPixels[ (tmpIndex * channels) + 2 ];
// Decide on whether to include the data at pixel or not
if( (maskValue.x + maskValue.y + maskValue.z) > 0 )
{
// Turn our valid pixel into a 3D position, pretty arbitrary in this case
// but let's fudge some numbers that work ok
ofVec3f spawnPos;
spawnPos.x = ofMap( x, 0, w, -0.5, 0.5 );
spawnPos.y = ofMap( y, 0, h, 0.0, 0.75 );
spawnPos.z = ofMap( maskValue.x, 0, 255.0, -0.2, 0.2 );
spawnPositions.push_back( spawnPos );
}
tmpIndex++;
}
}
haveNewData = true;
}
/*
spawnPositions.clear();
float time = ofGetElapsedTimef();
ofVec3f spawnMiddle = ofVec3f(0,0.2,0) + ofVec3f(0,0.2,0).getRotated( time * 30.0, ofVec3f(0,0,1) ).getRotated( time * 25.0, ofVec3f(0,1,0) );
ofMesh sphereMesh = ofMesh::sphere( 0.08, 40 );
//emissionMesh.clear();
for( int y = 0; y < particles.textureSize; y++ )
{
for( int x = 0; x < particles.textureSize; x++ )
{
ofVec3f spawnPos = spawnMiddle + sphereMesh.getVertex( ofRandom( sphereMesh.getNumVertices() - 1) );
spawnPositions.push_back( spawnPos );
}
}
haveNewData = true;
*/
if( haveNewData )
{
int tmpIndex = 0;
for( int y = 0; y < particles.textureSize; y++ )
{
for( int x = 0; x < particles.textureSize; x++ )
{
ofVec3f spawnPos;
spawnPos = spawnPositions.at( (int)ofRandom(spawnPositions.size()-1) );
particles.spawnPosBuffer.getPixels()[ (tmpIndex * 3) + 0 ] = spawnPos.x;
particles.spawnPosBuffer.getPixels()[ (tmpIndex * 3) + 1 ] = spawnPos.y;
particles.spawnPosBuffer.getPixels()[ (tmpIndex * 3) + 2 ] = spawnPos.z;
tmpIndex++;
}
}
particles.spawnPosTexture.loadData( particles.spawnPosBuffer );
}
}
//-----------------------------------------------------------------------------------------
//
void ofApp::draw()
{
ofBackgroundGradient( ofColor(40,40,40), ofColor(0,0,0), OF_GRADIENT_CIRCULAR);
particles.update( time, timeStep );
ofEnableDepthTest();
camera.begin();
// draw a grid on the floor
ofSetColor( ofColor(60) );
ofPushMatrix();
ofRotate(90, 0, 0, -1);
ofDrawGridPlane( 0.5, 12, false ); // of 0.9.0
ofPopMatrix();
ofSetColor( ofColor::white );
particles.draw( &camera );
camera.end();
ofDisableDepthTest();
ofEnableBlendMode( OF_BLENDMODE_ALPHA );
ofSetColor( ofColor::white );
int size = 196;
//particles.particleDataFbo.source()->getTextureReference(0).draw( 0, 0, size, size );
videoPlayer.draw( 0,0, videoPlayer.getWidth() * 0.3, videoPlayer.getHeight() * 0.3 );
if( drawGui )
{
particles.drawGui();
}
fontSmall.drawStringShadowed(ofToString(ofGetFrameRate(),2), ofGetWidth()-35, ofGetHeight() - 6, ofColor::whiteSmoke, ofColor::black );
}
//-----------------------------------------------------------------------------------------
//
void ofApp::keyPressed(int key)
{
if( key == OF_KEY_TAB )
{
drawGui = !drawGui;
}
else if( key == 'f' )
{
ofToggleFullscreen();
}
else if( key == OF_KEY_LEFT )
{
}
else if( key == OF_KEY_RIGHT )
{
}
}
|
//
// Created by 송지원 on 2020-01-24.
//
#include <iostream>
using namespace std;
int main()
{
int N, K;
long long mod = 1000000000;
long long d[201][201] = {0, };
cin >> N >> K;
for (int n=0; n <= N; n++) {
d[1][n] = 1;
}
for (int k=2; k<=K; k++) {
for (int n=0; n<=N; n++) {
for (int l=0; l<=n; l++) {
d[k][n] += d[k-1][l];
}
d[k][n] %= mod;
}
}
cout << d[K][N] % mod;
return 0;
}
|
#include "player.hpp"
#include <algorithm>
namespace Game
{
void Player::setName(const std::string& name)
{
this->name = name;
for(PlayerActionListener* l : listeners)
l->setName(name);
changed();
}
void Player::setActiveVehicle(Vehicle* vehicle)
{
if(vehicles.getIndexOf(vehicle) != -1)
activeVehicle = vehicle;
}
void Player::buyPart(const Part* part)
{
if(money >= part->getPrice())
{
money -= part->getPrice();
changed();
parts.add(Object::clone(part));
}
}
void Player::buyVehicle(const Vehicle* vehicle)
{
if(money >= vehicle->getPrice())
{
money -= vehicle->getPrice();
changed();
vehicles.add(Object::clone(vehicle));
}
}
void Player::attachPart(Part* part)
{
if(!getActiveVehicle())
return;
auto it = std::find(parts.begin(), parts.end(), part);
if(it == parts.end())
return;
}
void Player::detachPart(Part* part)
{
(void)part;
if(!getActiveVehicle())
return;
}
void Player::upgradePart(Part* part, const Upgrade* upgrade)
{
(void)part;
(void)upgrade;
}
const std::string& Player::getName() const
{
return name;
}
int Player::getMoney() const
{
return money;
}
const Container<Vehicle>& Player::getVehicles() const
{
return vehicles;
}
const Container<Part>& Player::getParts() const
{
return parts;
}
Vehicle* Player::getActiveVehicle() const
{
return activeVehicle;
}
Player::Player(const std::string& name, int money):
name(name),
money(money),
activeVehicle(nullptr)
{
}
Player::Player(const Json::Value& value):
Object(value),
parts(value["parts"]),
vehicles(value["vehicles"])
{
name = value["name"].asString();
money = value["money"].asUInt();
activeVehicle = vehicles.getByIndex(value["activeVehicle"].asInt());
}
void Player::save(Json::Value& value)
{
Object::save(value);
value["type"] = "player";
value["name"] = name;
value["money"] = money;
value["activeVehicle"] = vehicles.getIndexOf(activeVehicle);
vehicles.save(value["vehicles"]);
parts.save(value["parts"]);
}
};
|
//
// Created by ischelle on 05/05/2021.
//
#pragma once
#include "Player.hpp"
namespace pandemic {
class Scientist : public Player {
public:
int n;
Scientist(Board board, City city, int n);
// Player discover_cure(); // Can discover a cure with `n` cards instead of 5
};
}
|
#include <Wire.h>
#include <stdlib.h>
#include <Servo.h>
#include <IRremote.h>
#define ACTIVATED HIGH
unsigned long elapsed_time;
unsigned long last_time_print;
/*--- Propeller Servos -------------------------------------------------------*/
Servo right_prop;
Servo left_prop;
double throttle = 1100;
int button_state = 0;
int previous_time_pressed;
bool start_motors = false;
//--- Simple Moving Average Globals ------------------------------------------*/
const int samples = 10;
int a_x_readings[samples];
int a_y_readings[samples];
int a_z_readings[samples];
long int a_read_index = 0;
long int a_read_total[3] = {0, 0, 0};
long int a_read_ave[3] = {0, 0, 0};
/*--- Time Control -----------------------------------------------------------*/
int refresh_rate = 250;
float dt = 1 / refresh_rate;
const float loop_micros = (dt) * 1000000;
/*--- IMU Globals ------------------------------------------------------------*/
float rad_to_degrees = 57.29577951;
float degrees_to_rad = 0.017453293;
float a_magnitude, a_roll, a_pitch;
float g_roll, g_pitch;
float g_modifier = (1/65.5)*(dt);
float g_modifier_rads = g_modifier * 0.017453293;
float i_roll = 0, i_pitch = 0;
long g_cal[3];
/*--- PID Globals ------------------------------------------------------------*/
float pid, pwm_right, pwm_left, error, previous_error;
float pid_p = 0, pid_i = 0, pid_d = 0;
float k_p = 1.4;
float k_i = 1.82;
float k_d = 1.04;
float desired_angle = 0.0;
/*--- Remote Control ---------------------------------------------------------*/
IRrecv irrecv(12); // IR reciver digital input to pin 12.
decode_results results;
/*--- setup mpu --------------------------------------------------------------*/
void setup_mpu(){
// Activate the MPU-6050
// 0x68 = Registry address of mpu6050
// 0x6B = Send starting register
// 0x00 = Tell the MPU not to be asleep
Wire.beginTransmission(0x68);
Wire.write(0x6B);
Wire.write(0x00);
Wire.endTransmission();
// Configure the accelerometer (+/-8g)
// 0x68 = Registry address of mpu6050
// 0x1C = Registry address of accelerometer
// 0x10 = Full scale range of accelerometer (data sheet)
Wire.beginTransmission(0x68);
Wire.write(0x1C);
Wire.write(0x10);
Wire.endTransmission();
// Configure the gyro (500dps full scale
// 0x68 = Registry address of mpu6050
// 0x1B = Registry address of gyroscope
// 0x08 = 500 degree / sec Range of the gyro in degree/sec (data sheet)
// 0x10 = 1000 degree / sec range
// 0x12 = 2000 degree / sec range
Wire.beginTransmission(0x68);
Wire.write(0x1B);
Wire.write(0x10);
Wire.endTransmission();
}
/*--- read mpu --------------------------------------------------------------*/
void read_mpu(int ** sensor_output_array){
int array_size = 10;
*sensor_output_array = (int*) malloc(sizeof(int) * array_size);
/* Access the accellerometer register and requst
14 bits. Assign each high and low bit to a variable. */
Wire.beginTransmission(0x68);
Wire.write(0x3B);
Wire.endTransmission();
Wire.requestFrom(0x68, 14);
while(Wire.available() < 14){}; // Wait for all of the bits to be recieved:
// Assign values to each element of the array:
(*sensor_output_array)[0] = Wire.read()<<8|Wire.read(); // a_x
(*sensor_output_array)[1] = Wire.read()<<8|Wire.read(); // a_y
(*sensor_output_array)[2] = Wire.read()<<8|Wire.read(); // a_z
(*sensor_output_array)[3] = Wire.read()<<8|Wire.read(); // temp
(*sensor_output_array)[4] = Wire.read()<<8|Wire.read(); // g_x
(*sensor_output_array)[5] = Wire.read()<<8|Wire.read(); // g_y
(*sensor_output_array)[6] = Wire.read()<<8|Wire.read(); // g_z
}
/*--- DATA PROCESSING --------------------------------------------------------*/
void accel_data_processing(int * sensor_data[]){ //Simple moving average filter
a_read_total[0] -= a_x_readings[a_read_index];
a_read_total[1] -= a_y_readings[a_read_index];
a_read_total[2] -= a_z_readings[a_read_index];
a_x_readings[a_read_index] = (*sensor_data)[0];
a_y_readings[a_read_index] = (*sensor_data)[1];
a_z_readings[a_read_index] = (*sensor_data)[2];
a_read_total[0] += a_x_readings[a_read_index];
a_read_total[1] += a_y_readings[a_read_index];
a_read_total[2] += a_z_readings[a_read_index];
a_read_index += 1;
if (a_read_index >= samples){
a_read_index = 0;
}
a_read_ave[0] = a_read_total[0] / samples;
a_read_ave[1] = a_read_total[1] / samples;
a_read_ave[2] = a_read_total[2] / samples;
}
void gyro_data_processing(int * sensor_data[]){
(*sensor_data)[4] -= g_cal[0];
(*sensor_data)[5] -= g_cal[1];
(*sensor_data)[6] -= g_cal[2];
}
/*--- Calculate Roll Pitch & Yaw ---------------------------------------------*/
void calculate_attitude(int sensor_data[]){
/*--- Attitude from accelerometer -------------*/
a_magnitude = sqrt(pow(a_read_ave[0], 2) + pow(a_read_ave[1], 2) + pow(a_read_ave[2], 2));
a_roll = asin((float)a_read_ave[1] / a_magnitude) * rad_to_degrees; // X
a_pitch = asin((float)a_read_ave[0] / a_magnitude) * rad_to_degrees * (-1); // Y
// Attitude correction offset
a_roll -= 1.2;
a_pitch += 3.2;
/*6--- Attitude from Gyroscope ----------------------------------------------*/
//0.000061069
float t = (micros() - elapsed_time);
elapsed_time = micros();
double lsb_coefficient = (1 / 32.8) * ((t) / 1000000);
g_roll += sensor_data[4] * lsb_coefficient * 1.09;
g_pitch += sensor_data[5] * lsb_coefficient * 1.09;
//1.09 = coefficient that makes gyro attitue match accel attitude.
/* Approximation for transfer of roll to pitch & vice versa using yaw. Thanks
Joop: */
g_roll += g_pitch * sin(sensor_data[6] * lsb_coefficient * 0.0174533 * 0.5);
g_pitch -= g_roll * sin(sensor_data[6] * lsb_coefficient * 0.0174533 * 0.5);
/*--- Complimentary FIlter --------------------*/
// Apply complimentary filter if force magnitude is within reasonable range.
int f_magnitude_approx = abs(a_read_ave[0]) + abs(a_read_ave[1]) + abs(a_read_ave[2]);
if (f_magnitude_approx > 3072 && f_magnitude_approx < 32768){ // 4096 = 1g for +- 8G range
float hpf = 0.9996; // High Pass Filter
float lpf = 1.0 - hpf; // Low Pass Fbilter
g_roll = hpf * g_roll + lpf * a_roll;
g_pitch = hpf * g_pitch + lpf * a_pitch;
}
}
/*--- Calibrate IMU ----------------------------------------------------------*/
void calibrate_imu(){
/* THE IMU MUST NOT BE MOVED DURING SETUP */
/*--- Simple Moving ave Setup ---*/
for (int i = 0; i < samples; i++){
a_x_readings[i] = 0;
a_y_readings[i] = 0;
a_z_readings[i] = 0;
}
/*--- Calibrate gyroscope data and initial attitude: ---*/
int cal_count = 750;
Serial.print("\nCalibrating \n");
for (int i = 0; i < cal_count; i ++){
// Print the loading bar blips n times
if(i % 125 == 0) { Serial.print("- "); }
// Collect data from MPU
int * data_xyzt; read_mpu(&data_xyzt);
g_cal[0] += data_xyzt[4];
g_cal[1] += data_xyzt[5];
g_cal[2] += data_xyzt[6];
accel_data_processing(&data_xyzt);
calculate_attitude(data_xyzt);
i_roll += a_roll;
i_pitch += a_pitch;
free(data_xyzt); // Clear dynamic memory allocation
delay(3);
}
// Find the average value of the data that was recorded above:
g_cal[0] /= cal_count;
g_cal[1] /= cal_count;
g_cal[2] /= cal_count;
i_roll /= cal_count;
i_pitch /= cal_count;
// Set initial angle based off accelerometer
g_roll = i_roll;
g_pitch = i_pitch;
}
/*--- Flight Controller ------------------------------------------------------*/
void flight_controller(){
error = desired_angle - g_roll;
// PROPORTIONAL COMPONENET
pid_p = k_p * error;
// INTEGRAL COMPONENT
int k_i_thresh = 8;
if (error < k_i_thresh && error > -k_i_thresh) {
pid_i = pid_i * (k_i * error);
}
if (error > k_i_thresh && error < -k_i_thresh){
pid_i = 0;
}
/* DERIVATIVE COMPONENT*/
pid_d = k_d * ((error - previous_error) / 0.004);
/* Sum the the components to find the total pid value. */
pid = pid_p + pid_i + pid_d;
/* Clamp the maximum & minimum pid values*/
if (pid < -1000){
pid = -1000;
}
if (pid > 1000){
pid = 1000;
}
/* Calculate PWM width. */
pwm_right = throttle + pid;
pwm_left = throttle - pid;
/* clamp the PWM values. */
//----------Right---------//
if (pwm_right < 1000){
pwm_right = 1000;
}
if (pwm_right > 2000){
pwm_right = 2000;
}
//----------Left---------//
if (pwm_left < 1000){
pwm_left = 1000;
}
if (pwm_left > 2000){
pwm_left = 2000;
}
if (start_motors == true){
right_prop.writeMicroseconds(pwm_right);
left_prop.writeMicroseconds(pwm_left);
} else{
right_prop.writeMicroseconds(1000);
left_prop.writeMicroseconds(1000);
}
previous_error = error;
}
/*--- Debugging --------------------------------------------------------------*/
void debugging(){
// Serial.println(0);
// Serial.print("\n");
// Serial.println(5000);
// Serial.print(" ");
// Serial.print(loop_time);
// Serial.print(" ");
// Serial.print(loop_micros);
// Serial.print(" ");
// Serial.print("\n");
/*--- Print ---*/
// Serial.print("\n");
// Serial.print(90);
// Serial.print(" ");
// Serial.print(-90);
// Serial.print(" ");
int mode = 2;
if (elapsed_time - last_time_print > 35000){
if(mode == 1){
Serial.print("Roll: ");
Serial.print(g_roll);
Serial.print(" - Pitch: ");
Serial.print(g_pitch);
Serial.print(" - pwm left: ");
Serial.print(pwm_left);
Serial.print(" - pwm right: ");
Serial.print(pwm_right);
Serial.print(" - PID: ");
Serial.print(pid);
Serial.print(" - Run Motors?: ");
Serial.print(start_motors);
Serial.print(" - k_p: ");
Serial.print(k_p);
Serial.print(" - k_i: ");
Serial.print(k_i);
Serial.print(" - k_d: ");
Serial.print(k_d);
Serial.print("\n");
}
if(mode == 2){
// Serial.print("");
// Serial.print();
Serial.print(" aPitch: ");
Serial.print(a_pitch);
Serial.print(" - gPitch: ");
Serial.print(g_pitch);
Serial.print(" - aRoll: ");
Serial.print(a_roll);
Serial.print(" - gRoll: ");
Serial.print(g_roll);
Serial.print(" ");
Serial.print(90);
Serial.print(" ");
Serial.print(-90);
Serial.print("\n");
}
if(mode == 3){
// Serial.print(" gRoll: ");
// Serial.print(g_roll);
// Serial.print(" - gPitch: ");
Serial.print(g_pitch);
// Serial.print(" ");
// Serial.print(90);
// Serial.print(" ");
// Serial.print(-90);
// Serial.print(" - k_p: ");
// Serial.print(k_p);
// Serial.print(" - k_i: ");
// Serial.print(k_i);
// Serial.print(" - k_d: ");
// Serial.print(k_d);
Serial.print("\n");
}
last_time_print = micros();
}
}
void motors_on_off(){
button_state = digitalRead(13);
long int elapsed_time = millis();
if (button_state == ACTIVATED && start_motors == false && ((elapsed_time - previous_time_pressed) > 700)){
start_motors = true;
previous_time_pressed = millis();
}
else if(button_state == ACTIVATED && start_motors == true && ((elapsed_time - previous_time_pressed) > 700)){
start_motors = false;
previous_time_pressed = millis();
}
}
void IR_remoteControl(){
/*--- Store IR reciever remote value ---*/
if(irrecv.decode(&results)){
if(results.value != 4294967295){
//Serial.println(results.value, HEX);
/*--- Change PID gain values ---*/
switch(results.value){
case 1320906895: // Power Button:
if (start_motors){
start_motors = false;
} else{
start_motors = true;
}
break;
case 1320929335: // Button 1
k_p += 0.02;
break;
case 1320880375: // Button 2
k_d += 0.02;
break;
case 1320913015: // Button 3
k_i += 0.02;
break;
case 1320939535: // Button 4
k_p -= 0.02;
break;
case 1320890575: // Button 5
k_d -= 0.02;
break;
case 1320923215: // Button 6
k_i -= 0.02;
break;
case 1320887005: // Up Button
throttle += 50;
break;
case 1320925255:
throttle -= 50; // Down Button
break;
default:
break;
}
}
irrecv.resume();
}
}
void potentiometer_control(){
float value = analogRead(A0);
value = map(value, 1, 1024, 30, -30);
desired_angle = value;
}
/*--- Setup ------------------------------------------------------------------*/
void setup() {
Serial.begin(2000000);
Wire.begin();
irrecv.enableIRIn();
// Motors
right_prop.attach(5);
left_prop.attach(3);
right_prop.writeMicroseconds(1000);
left_prop.writeMicroseconds(1000);
// Calibrate imu
setup_mpu();
calibrate_imu();
}
/*--- Main -------------------------------------------------------------------*/
void loop(){
//IMU
int * data_xyzt;
read_mpu(&data_xyzt);
accel_data_processing(&data_xyzt);
gyro_data_processing(&data_xyzt);
calculate_attitude(data_xyzt);
free(data_xyzt);
// FLIGHT CONTROLLER
flight_controller();
// DEBUGGING
debugging();
//CALIBRATION CONTROLS
IR_remoteControl();
potentiometer_control();
//TIME CONTROL
while (micros() - elapsed_time < 4000);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright 2002 Opera Software ASA. All rights reserved.
*
* ECMAScript regular expression matcher -- test code
* Lars T Hansen
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//testing
#include "scaffold.h"
//testing
#include "regexp_advanced_api.h"
// Pass -2 for 'a' to indicate that failure is the expected result.
void test( uni_char *re, uni_char *input, unsigned int last_index, unsigned int a, unsigned int b, BOOL3 ignore_case=MAYBE, BOOL3 multi_line=MAYBE )
{
RegExpMatch *tmp;
RegExp e;
int r;
OP_STATUS status = e.Init(re,ignore_case,multi_line);
if (OpStatus::IsError(status))
printf( "Failed to compile/init: %s\n", re);
else if ((r = e.Exec(input,uni_strlen(input),last_index,&tmp)) != 0 && (tmp[0].first_char != a || tmp[0].last_char != b) ||
(r == 0 && a != -2))
printf( "Failed: %s on %s, expected (%d,%d), got (%d,%d)\n",
re, input,
a, b,
(r > 0 ? tmp[0].first_char : -2), (r > 0 ? tmp[0].last_char : -2) );
}
static void copydown( char *dest, const uni_char *src, int k )
{
int j;
for ( j=0 ; j < k && src[j] != 0 ; j++ )
dest[j] = (char)(src[j]);
if (j < k)
dest[j] = 0;
}
void testshow( uni_char *re, uni_char *input, int last_index, BOOL3 ignore_case=MAYBE, BOOL3 multi_line=MAYBE )
{
RegExpMatch *tmp;
RegExp e;
int r, i;
OP_STATUS status = e.Init(re,ignore_case,multi_line);
if (OpStatus::IsError(status))
printf( "Failed to compile/init: %s\n", re);
r = e.Exec(input,uni_strlen(input),last_index,&tmp);
printf( "Matches: %d\n", r );
for ( i=0 ; i < r ; i++ )
{
if (tmp[i].first_char != -1)
{
char buf[1000]; /* ARRAY OK 2007-02-22 chrispi */
int k=tmp[i].last_char-tmp[i].first_char+1;
if (k >= 1000)
k = 999;
copydown( buf, input+tmp[i].first_char, k );
buf[k] = 0;
printf( " %d,%d \"%s\"\n", (int)(tmp[i].first_char), (int)(tmp[i].last_char), buf );
}
else
printf( " UNDEFINED\n" );
}
}
void testc( uni_char *re, uni_char *input, int last_index, const uni_char *res[], int nres, BOOL3 ignore_case=MAYBE, BOOL3 multi_line=MAYBE )
{
RegExpMatch *tmp;
RegExp e;
int r, i;
OP_STATUS status = e.Init(re,ignore_case,multi_line);
if (OpStatus::IsError(status))
printf( "Failed to compile/init: %s\n", re);
r = e.Exec(input,uni_strlen(input),last_index,&tmp);
if (nres != r)
printf( "Failed: %s on %s, expected %d results, got %d\n",
re, input,
nres, r );
else
for ( i=0 ; i<r ; i++ )
{
unsigned int len=tmp[i].last_char-tmp[i].first_char+1;
if ((tmp[i].first_char == -1) != (res[i] == 0))
printf( "Failed: %s on %s, on item %d: def/undef mismatch\n",
re, input, i );
else if (res[i] != 0 && uni_strlen(res[i]) != len)
printf( "Failed: %s on %s, on item %d: length mismatch\n",
re, input, i );
else if (res[i] != 0 && uni_strncmp( res[i], input + tmp[i].first_char, len ) != 0)
{
char buf[1000]; /* ARRAY OK 2007-02-22 chrispi */
if (len >= 1000)
len = 999;
copydown( buf, input+tmp[i].first_char, len );
buf[len] = 0;
printf( "Failed: %s on %s, on item %d: mismatch -- got %s wanted %s\n",
re, input, i,
buf, res[i] );
}
}
}
int main( int argc, char **argv )
{
test(UNI_L("a"),UNI_L(""),0,-2,-2);
test(UNI_L("a"),UNI_L("a"),0,0,0);
test(UNI_L("a"),UNI_L("bbbbbbb"),0,-2,-2);
test(UNI_L("a"),UNI_L("bbbbabb"),0,4,4);
test(UNI_L("(?:a)"),UNI_L("a"),0,0,0);
test(UNI_L("(?:a)"),UNI_L("bbbbabb"),0,4,4);
test(UNI_L("(?:a)"),UNI_L("bbbbbbb"),0,-2,-2);
test(UNI_L("(?:ab(?:c|d|f))"),UNI_L("123abcabdabf456"),4,6,8);
test(UNI_L("(?:ab(?:c|d|f))+"),UNI_L("123abcabdabf456"),4,6,11);
test(UNI_L("a*bc"),UNI_L("aaaaaaabcjunk"),0,0,8);
test(UNI_L("a*bc"),UNI_L("xyzaaaaaaabcjunk"),0,3,11);
test(UNI_L("a?bc"),UNI_L("xyzaaaaaaabcjunk"),0,9,11);
test(UNI_L("a{3}bc"),UNI_L("xabcyzaaaaaaabcjunk"),0,10,14);
test(UNI_L("a{3,}bc"),UNI_L("xabcyzaaaaaaabcjunk"),0,6,14);
test(UNI_L("a{3,5}aa"),UNI_L("xabcyzaaaaaaabcjunk"),0,6,12);
test(UNI_L("a{3,5}?aa"),UNI_L("xabcyzaaaaaaabcjunk"),0,6,10);
test(UNI_L("^abc"),UNI_L("abcabc"),0,0,2);
test(UNI_L("^abc"),UNI_L("abcabc"),1,-2,-2);
test(UNI_L("^abc"),UNI_L("abd\nabc"),0,4,6,FALSE,TRUE);
test(UNI_L("abc$"),UNI_L("abcabc"),0,3,5);
test(UNI_L("abc$"),UNI_L("abcabd"),0,-2,-2);
test(UNI_L("abc$"),UNI_L("abc\nabd"),0,0,2,FALSE,TRUE);
test(UNI_L("[a-zA-Z][a-zA-Z0-9]+\\B.f"),UNI_L("123abcabdabg456 foo"),4,-2,-2);
test(UNI_L("[a-zA-Z][a-zA-Z0-9]+\\B.f"),UNI_L("123abcabdabf456 foo"),4,4,11);
test(UNI_L("[a-zA-Z][a-zA-Z0-9]+\\B.f"),UNI_L("123abcabdabg456afoo"),4,4,16);
test(UNI_L("[a-zA-Z][a-zA-Z0-9]+\\b.f"),UNI_L("123abcabdabg456 foo"),4,4,16);
test(UNI_L("[a-zA-Z][a-zA-Z0-9]+\\b.f"),UNI_L("123abcabdabg456afoo"),4,-2,-2);
test(UNI_L("[a-zA-Z][a-zA-Z0-9]+\\B.f|[a-zA-Z][a-zA-Z0-9]+\\B.f|[a-zA-Z][a-zA-Z0-9]+\\B.f|[a-zA-Z][a-zA-Z0-9]+\\B.f|[a-zA-Z][a-zA-Z0-9]+\\B.f"),UNI_L("123abcabdabg456 foo"),4,-2,-2); // Tests when RE_Store overflows one segment
test(UNI_L("[a-k]+"),UNI_L("ABC"),0,0,2,TRUE,FALSE);
test(UNI_L("ø"),UNI_L("ø"),0,0,0,TRUE,FALSE); // o-slash
test(UNI_L("ø"),UNI_L("Ø"),0,0,0,TRUE,FALSE); // o-slash
test(UNI_L("ñ"),UNI_L("Ñ"),0,0,0,TRUE,FALSE); // tilde-n
test(UNI_L("(?:\\d+)?do\\d+(?=.*,)\\w+"),UNI_L("do100xyzzy=10,20"),0,0,9); // Fortran "do" loop
test(UNI_L("(?:\\d+)?do\\d+(?=.*,)\\w+"),UNI_L("do100xyzzy=10.20"),0,-2,-2); // fails on assignment stmt
test(UNI_L("(?:\\d+)?do\\d+\\w+=\\d+,\\d+"),UNI_L("do100xyzzy=10,20"),0,0,15);
test(UNI_L("(?:\\d+)?do\\d+(?!.*,)\\w+"),UNI_L("do100xyzzy=10.20"),0,0,9); // Fortran assignment stmt
test(UNI_L("(?:\\d+)?do\\d+(?!.*,)\\w+"),UNI_L("do100xyzzy=10,20"),0,-2,-2); // fails on do loop
test(UNI_L("(?:\\d+)?do\\d+(?=.*\\.)\\w+"),UNI_L("do100xyzzy=10.20"),0,0,9); // Thinking positive!
const uni_char *a1[] = { UNI_L("aaaaaaa"), UNI_L("aaaaaaa") };
testc(UNI_L("(a*)"), UNI_L("aaaaaaa"),0,a1,2);
const uni_char *a2[] = { UNI_L("abc"), UNI_L("a"), UNI_L("a"), 0, UNI_L("bc"), 0, UNI_L("bc") };
testc(UNI_L("((a)|(ab))((c)|(bc))"), UNI_L("abc"),0,a2,7);
const uni_char *a3[] = { UNI_L("aaaaaa"), UNI_L("aaa") };
testc(UNI_L("(a{3})\\1"), UNI_L("aaaaaaaa"), 0,a3,2);
const uni_char *a4[] = { UNI_L("baaabaac"), UNI_L("ba"), 0, UNI_L("abaac") };
testc(UNI_L("(.*?)a(?!(a+)b\\2c)\\2(.*)"),UNI_L("baaabaac"),0,a4,4);
// Tests the capture store management, esp in debug mode (with small store segments)
testc(UNI_L("(((a)(a)(a)(a)(a)(a)(a)(a)(a))|((a)(a)(a)(a)(a)(a)(a)(a)(a)(a))|((a)(a)(a)(a)(a)(a)(a)(a)(a)(a)(a)))|c"), UNI_L("aaaaabaaabaaaaabaabaaaabaaabbaaaaabaaaaab"),0,NULL,0);
testshow(UNI_L("(?:\\d+)?"),UNI_L("do100xyzzy=10,20"),0); // empty match at 0
testshow(UNI_L("\\w?"),UNI_L("@@@x"),0); // empty match at 0
testshow(UNI_L("ba+c"), UNI_L("baaac"), 0 );
return 0;
}
#if defined RE_SCAFFOLDING
void *operator new( unsigned int n, TLeave )
{
void *p = ::operator new(n);
if (p == NULL)
LEAVE( OpStatus::ERR_NO_MEMORY );
return p;
}
#endif
|
/** This file holds the core program logic behind the user interface.
* Implemented functions are work (for calculating bmi and updating
* the UI), and reset (for restoring the UI into its default state).
* + minor helper functions female_checked, male_checked and close.
* @author Daniel "3ICE" Berezvai
* @student_id 262849
* @email daniel.berezvai@student.tut.fi
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
/** This method sets up the user interface and registers (some) signals
* between the components. Other signals are only declared in mainwindow.ui,
* which is a little confusing and really annoying to work with.
* @param parent: not applicable, this is the top window as the class name
* hints. Default value is zero (no parent), which is good enough for my
* purposes.
*/
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent), ui(new Ui::MainWindow){
ui->setupUi(this);
//3ICE: Recalculate if any of these three fields change:
connect(ui->weight,SIGNAL(valueChanged(int)),this,SLOT(work()));
connect(ui->height,SIGNAL(valueChanged(int)),this,SLOT(work()));
//Female changes together with male, so I only need it once
connect(ui->actionFemale,SIGNAL(changed()),this,SLOT(work()));
//Interestingly, male only doesn't work, but female only does... WONTFIX
//3ICE: You don't know my pain...
//connect(ui->actionFemale,SIGNAL(changed()),this,SLOT(avoidInfiniteLoop()));
//3ICE: Yeah, so GUI-created signals are terrible. Must use code.
//Creative function names: f... m... l?
connect(ui->actionFemale,SIGNAL(triggered(bool)),this,SLOT(female_checked(bool)));
connect(ui->actionMale,SIGNAL(triggered(bool)),this,SLOT(male_checked(bool)));
connect(ui->actionReset,SIGNAL(triggered(bool)),this,SLOT(reset()));
}
/**
* @brief MainWindow::~MainWindow
* destructor's gonna destruct.
*/
MainWindow::~MainWindow(){
delete ui;
}
/** Restores the UI to default state. This method went through some
* revisions. Debugging other functions for hours broke this one :)
*/
void MainWindow::reset(){
ui->height->setValue(0);
ui->weight2->setValue(0);
if(ui->actionMale->isChecked()){
//3ICE: For some reason signals don't listen when unchecking:
ui->actionMale->setChecked(false);
//3ICE: so I have to toggle both. Strange...
ui->actionFemale->setChecked(true);
//I deleted most of the code that was responsible for the
//above complained-about bug. (Not even commented out, just
//straight up deleted...)
//3ICE: This line used to be unnecessary:
ui->gender->setText("Female");
//3ICE: But I stopped listening for changed() signals.
}
}
/** This method calculates the bmi (unless there's a zero), updates the UI
* and chronicles my struggles with Qt, C++11 compilers with 5 year old
* bug reports, and finally my beautiful BMI calculator at the end.
* @note Who wants a docstring? I usually do it. But it's 5 am now...
* @footnote Well I did it. 8 am now. Proper all-nighter. Do I get a cookie?
* Grade 5 will be enough.
*/
void MainWindow::work(){
if(ui->height->value()==0.0 || ui->weight->value()==0.0){
ui->interpreted_bmi->setText("-");
ui->bmi->setText("-");
return;
}
float height_in_meters = (float)ui->height->value() / 100;
float bmi = ui->weight->value() / (height_in_meters*height_in_meters);
//ui->bmi->setText(to_string(bmi));
//3ICE: Obviously to_string has been bugged for years now.
//And even if _I_ fix it locally, _YOU_ still won't be able
//to test & grade my code with your unpatched compiler.
//Stringstream workaround (remember to include it):
//std::ostringstream ss;ss<<bmi;std::string bmi_s(ss.str());
//3ICE: Oh you expletive Qt... Won't even accept string, wants QString.
//Well, here you go then, eat your QString:
QString bmi_string = QString::number(bmi);
ui->bmi->setText(bmi_string);
//3ICE: Oops, could have used ui->bmi->setNum(bmi); //oh well...
QString result;
if(ui->actionFemale->isChecked()){
if (bmi<=19.1) result="Underweight";
else if(bmi<=25.8) result="Normal";
else if(bmi<=27.3) result="Slight overweight";
else if(bmi<=32.2) result="Overweight";
else result="Much overweight";
}else{
if (bmi<=20.7) result="Underweight";
else if(bmi<=26.4) result="Normal";
else if(bmi<=27.8) result="Slight overweight";
else if(bmi<=31.1) result="Overweight";
else result="Much overweight";
}
ui->interpreted_bmi->setText(result);
}
/** I'm keeping this name because that's what the function did initially.
* Now it does nothing. Disregard or read all the comments for their
* slight entertainment value. Documenting my suffering continued...
*/
void MainWindow::avoidInfiniteLoop(){
//3ICE: Let's start with a funny debug message I left in:
//ui->bmi->setText(infiniteLoop?"1 dis fe, en ma":"0 dis ma en fe");
//3ICE: Qt's signal editor sucks.
//I tried my best to use the GUI, but it's sorely lacking.
//Can't open menus while Signal editor is on.
//Menus close as soon as you enter signal editing
//And if you use the tiny green + icon, the editor doesn't open.
//Only four basic dropdowns. No inherited signals, no adding new signals.
//Writing it in code is far easier than struggling with that limited system.
//I did force the signal editor to work for menu actions.
//End result looks funny, the arrows are coming out of nowhere :)
//But all that hacking did for me is waste my time, in the end...
//female.triggered->male.toggle via GUI
//male.triggered->female.toggle via GUI
//3ICE: The above logic works for spinners (changed->setValue),
//but crashes the app (!?) for radio checkboxes (triggered->toggle)
//3ICE: I spent an hour playing with setEnabled, setDisabled here.
//Almost perfect.
//3ICE: Another hour with blockSignals(false), blockSignals(true)...
//Everything good, except it breaks on Reset.
//3ICE: Another hour on forcing the GUI editor to add a QActionGroup component
//Then I could have used setExclusive(true) on it. But no matter what I did...
//The sample app behaves differently from everything I tried. In minor ways.
//Here's my worst workaround:
//if(!ui->actionFemale->isChecked()){
// ui->actionMale->blockSignals(true);
// ui->actionFemale->blockSignals(false);
////or
// ui->actionFemale->setEnabled(true);
// ui->actionMale->setEnabled(false);
////or
// ui->actionFemale->setChecked(true);
// ui->actionMale->setChecked(false);
//}else{
// ui->actionFemale->setChecked(false);
// ui->actionMale->setChecked(true);
////or
// ui->actionFemale->blockSignals(true);
// ui->actionMale->blockSignals(false);
////or
// ui->actionFemale->setDisabled(false);
// ui->actionMale->setDisabled(true);
//}
//3ICE: The only line of code that's still useful after my all-nighter:
//3ICE: I love conditional operators (?:)
//ui->gender->setText(ui->actionFemale->isChecked()?"Female":"Male");
//Update: And now even that's broken. See f and m below for fix:
}
//3ICE: Oh, the crazy things I do for grade 5...
/**
* @brief MainWindow::female_checked Unfortunately necessary
* for keeping the order of things / the user in line...
* @param on:bool whether the checkbox was toggled on or off.
* This is important because if it was toggled off, I need to
* toggle it back on (because that's how the sample program works.
*
* Helper function.
*/
void MainWindow::female_checked(bool on){
if(on) ui->actionMale->setChecked(false);
else ui->actionFemale->setChecked(true); //3ICE: Stop them from toggling it off
ui->gender->setText("Female");
}
/** @see MainWindow::female_checked(bool)
*
* Helper function.
*/
void MainWindow::male_checked(bool on){
if(on) ui->actionFemale->setChecked(false);
else ui->actionMale->setChecked(true);
ui->gender->setText("Male");
}
|
// 이 MFC 샘플 소스 코드는 MFC Microsoft Office Fluent 사용자 인터페이스("Fluent UI")를
// 사용하는 방법을 보여 주며, MFC C++ 라이브러리 소프트웨어에 포함된
// Microsoft Foundation Classes Reference 및 관련 전자 문서에 대해
// 추가적으로 제공되는 내용입니다.
// Fluent UI를 복사, 사용 또는 배포하는 데 대한 사용 약관은 별도로 제공됩니다.
// Fluent UI 라이선싱 프로그램에 대한 자세한 내용은
// http://msdn.microsoft.com/officeui를 참조하십시오.
//
// Copyright (C) Microsoft Corporation
// 모든 권리 보유.
// MainFrm.h : CMainFrame 클래스의 인터페이스
//
#pragma once
#include "CalendarBar.h"
#include "Resource.h"
#include "GcTemplateTasks.h"
#include "GcSequenceDockable.h"
#include "Gc2DObjectDockable.h"
#include "GcSequenceModifyDockable.h"
class COutlookBar : public CMFCOutlookBar
{
virtual BOOL AllowShowOnPaneMenu() const { return TRUE; }
virtual void GetPaneName(CString& strName) const { BOOL bNameValid = strName.LoadString(IDS_OUTLOOKBAR); ASSERT(bNameValid); if (!bNameValid) strName.Empty(); }
};
class CMainFrame : public CFrameWndEx, public GcMediateObject
{
protected: // serialization에서만 만들어집니다.
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// 특성입니다.
public:
// 작업입니다.
public:
// 재정의입니다.
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
// 구현입니다.
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // 컨트롤 모음이 포함된 멤버입니다.
CMFCRibbonBar m_wndRibbonBar;
CMFCRibbonApplicationButton m_MainButton;
CMFCToolBarImages m_PanelImages;
CMFCRibbonStatusBar m_wndStatusBar;
COutlookBar m_wndNavigationBar;
CMFCCaptionBar m_wndCaptionBar;
GcTemplateTasks m_wndTemplateTasksPane;
GcSequenceDockable mSequenceDockable;
Gc2DObjectDockable m2DObjectDockable;
GcSequenceModifyDockable mSequenceModifyDockable;
GtObject* mpObject;
// 생성된 메시지 맵 함수
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnViewCaptionBar();
afx_msg void OnUpdateViewCaptionBar(CCmdUI* pCmdUI);
afx_msg void OnOptions();
DECLARE_MESSAGE_MAP()
BOOL CreateOutlookBar(CMFCOutlookBar& bar, UINT uiID, int nInitialWidth);
BOOL CreateDockableBar();
BOOL CreateCaptionBar();
virtual void ReceiveMediateMessage(gtuint messageIndex, GcMediateObjectMessage* pSanderInfo);
int FindFocusedOutlookWnd(CMFCOutlookBarTabCtrl** ppOutlookWnd);
CMFCOutlookBarTabCtrl* FindOutlookParent(CWnd* pWnd);
CMFCOutlookBarTabCtrl* m_pCurrOutlookWnd;
CMFCOutlookBarPane* m_pCurrOutlookPage;
public:
virtual BOOL DestroyWindow();
afx_msg void OnSaveObjectState();
afx_msg void OnViewSequencedockable();
afx_msg void OnUpdateViewSequencedockable(CCmdUI *pCmdUI);
afx_msg void OnViewOutlookvisible();
afx_msg void OnUpdateViewOutlookvisible(CCmdUI *pCmdUI);
afx_msg void OnView2DObjectvisible();
afx_msg void OnUpdateView2DObjectvisible(CCmdUI *pCmdUI);
};
|
#pragma once
#include <Dot++/lexer/TokenizerStateInterface.hpp>
namespace dot_pp { namespace lexer { namespace states {
class SlashLineCommentState : public TokenizerStateInterface
{
public:
TokenizerState consume(const char c, FileInfo& info, Token& token, std::deque<TokenInfo>& tokens) const override;
};
}}}
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/data/smart_buffer.h>
#include <vespa/vespalib/net/tls/tls_context.h>
#include <vespa/vespalib/net/tls/transport_security_options.h>
#include <vespa/vespalib/net/tls/crypto_codec.h>
#include <vespa/vespalib/net/tls/impl/openssl_crypto_codec_impl.h>
#include <vespa/vespalib/net/tls/impl/openssl_tls_context_impl.h>
#include <vespa/vespalib/test/make_tls_options_for_testing.h>
#include <iostream>
#include <stdlib.h>
using namespace vespalib;
using namespace vespalib::net::tls;
const char* decode_state_to_str(DecodeResult::State state) noexcept {
switch (state) {
case DecodeResult::State::Failed: return "Broken";
case DecodeResult::State::OK: return "OK";
case DecodeResult::State::NeedsMorePeerData: return "NeedsMorePeerData";
default:
abort();
}
}
const char* hs_state_to_str(HandshakeResult::State state) noexcept {
switch (state) {
case HandshakeResult::State::Failed: return "Broken";
case HandshakeResult::State::Done: return "Done";
case HandshakeResult::State::NeedsMorePeerData: return "NeedsMorePeerData";
default:
abort();
}
}
void print_handshake_result(const char* mode, const HandshakeResult& res) {
fprintf(stderr, "(handshake) %s consumed %zu peer bytes, wrote %zu peer bytes. State: %s\n",
mode, res.bytes_consumed, res.bytes_produced,
hs_state_to_str(res.state));
}
void print_encode_result(const char* mode, const EncodeResult& res) {
fprintf(stderr, "(encode) %s read %zu plaintext, wrote %zu cipher. State: %s\n",
mode, res.bytes_consumed, res.bytes_produced,
res.failed ? "Broken! D:" : "OK");
}
void print_decode_result(const char* mode, const DecodeResult& res) {
fprintf(stderr, "(decode) %s read %zu cipher, wrote %zu plaintext. State: %s\n",
mode, res.bytes_consumed, res.bytes_produced,
decode_state_to_str(res.state));
}
struct Fixture {
TransportSecurityOptions tls_opts;
std::unique_ptr<TlsContext> tls_ctx;
std::unique_ptr<CryptoCodec> client;
std::unique_ptr<CryptoCodec> server;
SmartBuffer client_to_server;
SmartBuffer server_to_client;
Fixture()
: tls_opts(vespalib::test::make_tls_options_for_testing()),
tls_ctx(TlsContext::create_default_context(tls_opts)),
client(create_openssl_codec(*tls_ctx, CryptoCodec::Mode::Client)),
server(create_openssl_codec(*tls_ctx, CryptoCodec::Mode::Server)),
client_to_server(64 * 1024),
server_to_client(64 * 1024)
{}
static TransportSecurityOptions create_options_without_own_peer_cert() {
auto source_opts = vespalib::test::make_tls_options_for_testing();
return TransportSecurityOptions(source_opts.ca_certs_pem(), "", "");
}
static std::unique_ptr<CryptoCodec> create_openssl_codec(
const TransportSecurityOptions& opts, CryptoCodec::Mode mode) {
auto ctx = TlsContext::create_default_context(opts);
return create_openssl_codec(*ctx, mode);
}
static std::unique_ptr<CryptoCodec> create_openssl_codec(
const TlsContext& ctx, CryptoCodec::Mode mode) {
return std::make_unique<impl::OpenSslCryptoCodecImpl>(
*dynamic_cast<const impl::OpenSslTlsContextImpl&>(ctx).native_context(), mode);
}
EncodeResult do_encode(CryptoCodec& codec, Output& buffer, vespalib::stringref plaintext) {
auto out = buffer.reserve(codec.min_encode_buffer_size());
auto enc_res = codec.encode(plaintext.data(), plaintext.size(), out.data, out.size);
buffer.commit(enc_res.bytes_produced);
return enc_res;
}
DecodeResult do_decode(CryptoCodec& codec, Input& buffer, vespalib::string& out,
size_t max_bytes_produced, size_t max_bytes_consumed) {
auto in = buffer.obtain();
out.resize(max_bytes_produced);
auto to_consume = std::min(in.size, max_bytes_consumed);
auto enc_res = codec.decode(in.data, to_consume, &out[0], out.size());
buffer.evict(enc_res.bytes_consumed);
out.resize(enc_res.bytes_produced);
return enc_res;
}
EncodeResult client_encode(vespalib::stringref plaintext) {
auto res = do_encode(*client, client_to_server, plaintext);
print_encode_result("client", res);
return res;
}
EncodeResult server_encode(vespalib::stringref plaintext) {
auto res = do_encode(*server, server_to_client, plaintext);
print_encode_result("server", res);
return res;
}
DecodeResult client_decode(vespalib::string& out, size_t max_bytes_produced,
size_t max_bytes_consumed = UINT64_MAX) {
auto res = do_decode(*client, server_to_client, out, max_bytes_produced, max_bytes_consumed);
print_decode_result("client", res);
return res;
}
DecodeResult server_decode(vespalib::string& out, size_t max_bytes_produced,
size_t max_bytes_consumed = UINT64_MAX) {
auto res = do_decode(*server, client_to_server, out, max_bytes_produced, max_bytes_consumed);
print_decode_result("server", res);
return res;
}
HandshakeResult do_handshake(CryptoCodec& codec, Input& input, Output& output) {
auto in = input.obtain();
auto out = output.reserve(codec.min_encode_buffer_size());
auto hs_result = codec.handshake(in.data, in.size, out.data, out.size);
input.evict(hs_result.bytes_consumed);
output.commit(hs_result.bytes_produced);
return hs_result;
}
bool handshake() {
HandshakeResult cli_res;
HandshakeResult serv_res;
while (!(cli_res.done() && serv_res.done())) {
cli_res = do_handshake(*client, server_to_client, client_to_server);
serv_res = do_handshake(*server, client_to_server, server_to_client);
print_handshake_result("client", cli_res);
print_handshake_result("server", serv_res);
if (cli_res.failed() || serv_res.failed()) {
return false;
}
}
return true;
}
};
TEST_F("client and server can complete handshake", Fixture) {
EXPECT_TRUE(f.handshake());
}
TEST_F("clients and servers can send single data frame after handshake (not full duplex)", Fixture) {
ASSERT_TRUE(f.handshake());
vespalib::string client_plaintext = "Hellooo world! :D";
vespalib::string server_plaintext = "Goodbye moon~ :3";
ASSERT_FALSE(f.client_encode(client_plaintext).failed);
vespalib::string server_plaintext_out;
ASSERT_TRUE(f.server_decode(server_plaintext_out, 256).frame_decoded_ok());
EXPECT_EQUAL(client_plaintext, server_plaintext_out);
ASSERT_FALSE(f.server_encode(server_plaintext).failed);
vespalib::string client_plaintext_out;
ASSERT_TRUE(f.client_decode(client_plaintext_out, 256).frame_decoded_ok());
EXPECT_EQUAL(server_plaintext, client_plaintext_out);
}
TEST_F("clients and servers can send single data frame after handshake (full duplex)", Fixture) {
ASSERT_TRUE(f.handshake());
vespalib::string client_plaintext = "Greetings globe! :D";
vespalib::string server_plaintext = "Sayonara luna~ :3";
ASSERT_FALSE(f.client_encode(client_plaintext).failed);
ASSERT_FALSE(f.server_encode(server_plaintext).failed);
vespalib::string client_plaintext_out;
vespalib::string server_plaintext_out;
ASSERT_TRUE(f.server_decode(server_plaintext_out, 256).frame_decoded_ok());
EXPECT_EQUAL(client_plaintext, server_plaintext_out);
ASSERT_TRUE(f.client_decode(client_plaintext_out, 256).frame_decoded_ok());
EXPECT_EQUAL(server_plaintext, client_plaintext_out);
}
TEST_F("short ciphertext read on decode() returns NeedsMorePeerData", Fixture) {
ASSERT_TRUE(f.handshake());
vespalib::string client_plaintext = "very secret foo";
ASSERT_FALSE(f.client_encode(client_plaintext).failed);
vespalib::string server_plaintext_out;
auto dec_res = f.server_decode(server_plaintext_out, 256, 10);
EXPECT_FALSE(dec_res.failed()); // Short read is not a failure mode
EXPECT_TRUE(dec_res.state == DecodeResult::State::NeedsMorePeerData);
}
TEST_F("Encodes larger than max frame size are split up", Fixture) {
ASSERT_TRUE(f.handshake());
constexpr auto frame_size = impl::OpenSslCryptoCodecImpl::MaximumFramePlaintextSize;
vespalib::string client_plaintext(frame_size + 50, 'X');
auto enc_res = f.client_encode(client_plaintext);
ASSERT_FALSE(enc_res.failed);
ASSERT_EQUAL(frame_size, enc_res.bytes_consumed);
auto remainder = client_plaintext.substr(frame_size);
enc_res = f.client_encode(remainder);
ASSERT_FALSE(enc_res.failed);
ASSERT_EQUAL(50u, enc_res.bytes_consumed);
// Over on the server side, we expect to decode 2 matching frames
vespalib::string server_plaintext_out;
auto dec_res = f.server_decode(server_plaintext_out, frame_size);
ASSERT_TRUE(dec_res.frame_decoded_ok());
EXPECT_EQUAL(frame_size, dec_res.bytes_produced);
vespalib::string remainder_out;
dec_res = f.server_decode(remainder_out, frame_size);
ASSERT_TRUE(dec_res.frame_decoded_ok());
EXPECT_EQUAL(50u, dec_res.bytes_produced);
EXPECT_EQUAL(client_plaintext, server_plaintext_out + remainder);
}
TEST_F("client without a certificate is rejected by server", Fixture) {
f.client = f.create_openssl_codec(f.create_options_without_own_peer_cert(), CryptoCodec::Mode::Client);
EXPECT_FALSE(f.handshake());
}
// Certificate note: public keys must be of the same type as those
// used by vespalib::test::make_tls_options_for_testing(). In this case,
// it's P-256 EC keys.
// Also note: the Subject of this CA is different from the baseline
// test CA to avoid validation errors. This also means the Issuer is
// different for the below host certificate.
constexpr const char* unknown_ca_pem = R"(-----BEGIN CERTIFICATE-----
MIIBvzCCAWYCCQDEtg8a8Y5bBzAKBggqhkjOPQQDAjBoMQswCQYDVQQGEwJVUzEU
MBIGA1UEBwwLTG9vbmV5VmlsbGUxDjAMBgNVBAoMBUFDTUUyMRcwFQYDVQQLDA5B
Q01FIHRlc3QgQ0EgMjEaMBgGA1UEAwwRYWNtZTIuZXhhbXBsZS5jb20wHhcNMTgw
OTI3MTM0NjA3WhcNNDYwMjEyMTM0NjA3WjBoMQswCQYDVQQGEwJVUzEUMBIGA1UE
BwwLTG9vbmV5VmlsbGUxDjAMBgNVBAoMBUFDTUUyMRcwFQYDVQQLDA5BQ01FIHRl
c3QgQ0EgMjEaMBgGA1UEAwwRYWNtZTIuZXhhbXBsZS5jb20wWTATBgcqhkjOPQIB
BggqhkjOPQMBBwNCAAT88ScwGmpJ4NycxZBaqgSpw+IXfeIFR1oCGpxlLaKyrdpw
Sl9SeuAyJfW4yNinzUeiuX+5hSrzly4yFrOIW/n6MAoGCCqGSM49BAMCA0cAMEQC
IGNCYvQyZm/7GgTCi55y3RWK0tEE73ivEut9V0qvlqarAiBj8IDxv+Dm0ZFlB/8E
EYn91JZORccsNSJkfIWqrGEjBA==
-----END CERTIFICATE-----)";
// Signed by unknown CA above
constexpr const char* untrusted_host_cert_pem = R"(-----BEGIN CERTIFICATE-----
MIIBrzCCAVYCCQDAZrFWZPw7djAKBggqhkjOPQQDAjBoMQswCQYDVQQGEwJVUzEU
MBIGA1UEBwwLTG9vbmV5VmlsbGUxDjAMBgNVBAoMBUFDTUUyMRcwFQYDVQQLDA5B
Q01FIHRlc3QgQ0EgMjEaMBgGA1UEAwwRYWNtZTIuZXhhbXBsZS5jb20wHhcNMTgw
OTI3MTM0NjA3WhcNNDYwMjEyMTM0NjA3WjBYMQswCQYDVQQGEwJVUzEUMBIGA1UE
BwwLTG9vbmV5VmlsbGUxGjAYBgNVBAoMEVJvYWQgUnVubmVyLCBJbmMuMRcwFQYD
VQQDDA5yci5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABMrp
YgaA3CbDCaHa5CC6Vr7TLHEPNMkLNGnr2692a57ExWk1FMzNlZfaS79b67o6zxAu
/HMiEHtseecH96UaGg4wCgYIKoZIzj0EAwIDRwAwRAIgOjiCql8VIe0/Ihyymr0a
IforjEAMmPffLdHnMJzbya8CIBKWeTzSnG7/0PE0K73vqr+OrE5V31FjvzvYpvdT
tSe+
-----END CERTIFICATE-----)";
constexpr const char* untrusted_host_key_pem = R"(-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIHwh0Is5sf4emYv0UBsHSCCMI0XCV2RzhafIQ3j1BTK0oAoGCCqGSM49
AwEHoUQDQgAEyuliBoDcJsMJodrkILpWvtMscQ80yQs0aevbr3ZrnsTFaTUUzM2V
l9pLv1vrujrPEC78cyIQe2x55wf3pRoaDg==
-----END EC PRIVATE KEY-----)";
TEST_F("client with certificate signed by untrusted CA is rejected by server", Fixture) {
TransportSecurityOptions client_opts(unknown_ca_pem, untrusted_host_cert_pem, untrusted_host_key_pem);
f.client = f.create_openssl_codec(client_opts, CryptoCodec::Mode::Client);
EXPECT_FALSE(f.handshake());
}
TEST_F("server with certificate signed by untrusted CA is rejected by client", Fixture) {
TransportSecurityOptions server_opts(unknown_ca_pem, untrusted_host_cert_pem, untrusted_host_key_pem);
f.server = f.create_openssl_codec(server_opts, CryptoCodec::Mode::Server);
EXPECT_FALSE(f.handshake());
}
TEST_F("Can specify multiple trusted CA certs in transport options", Fixture) {
auto& base_opts = f.tls_opts;
auto multi_ca_pem = base_opts.ca_certs_pem() + "\n" + unknown_ca_pem;
TransportSecurityOptions multi_ca_using_ca_1(multi_ca_pem, untrusted_host_cert_pem, untrusted_host_key_pem);
TransportSecurityOptions multi_ca_using_ca_2(multi_ca_pem, base_opts.cert_chain_pem(), base_opts.private_key_pem());
// Let client be signed by CA 1, server by CA 2. Both have the two CAs in their trust store
// so this should allow for a successful handshake.
f.client = f.create_openssl_codec(multi_ca_using_ca_1, CryptoCodec::Mode::Client);
f.server = f.create_openssl_codec(multi_ca_using_ca_2, CryptoCodec::Mode::Server);
EXPECT_TRUE(f.handshake());
}
/*
* TODO tests:
* - handshakes with multi frame writes
* - completed handshake with pipelined data frame
* - short plaintext writes on decode (.. if we even want to support this..)
* - short ciphertext write on encode (.. if we even want to support this..)
* - detection of peer shutdown session
*/
TEST_MAIN() { TEST_RUN_ALL(); }
|
#include<bits/stdc++.h>
using namespace std;
void dec_to_bin(int n)
{
int binarr[100],i=0;
while(n>0)
{
binarr[i]=n%2;
n=n/2;
i++;
}
for(int j=i-1;j>=0;j--)
{
cout<<binarr[j]<<" ";
}
}
int main(){
int n;
cin>>n;
dec_to_bin(n);
}
|
//: C10:NamespaceOverriding1.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
#include "NamespaceMath.h"
int main() {
using namespace Math;
Integer a; // Zaslania Math::a;
a.setSign(negative);
// Teraz uzycie operatora zasiegu do
// wybrania Math::a jest niezbedne:
Math::a.setSign(positive);
} ///:~
|
#ifndef CUSTOMGRAPHICSVIEW_H
#define CUSTOMGRAPHICSVIEW_H
#include <QGraphicsView>
class MainWindow;
class CustomGraphicsView : public QGraphicsView
{
Q_OBJECT
public:
static QSize getNormalSize();
public:
CustomGraphicsView(QWidget *parent = Q_NULLPTR);
CustomGraphicsView(QGraphicsScene *scene, QWidget *parent = Q_NULLPTR);
//
void setMainWidget(QWidget *pWidget);
protected:
bool event(QEvent *event);
bool eventFilter(QObject *obj, QEvent *event);
signals:
public slots:
void slotGeometryChanged();
private:
QWidget *m_pMainWindow = nullptr;
};
#endif // CUSTOMGRAPHICSVIEW_H
|
#include "./platform/UnitTestSupport.hpp"
#include <Dot++/Exceptions.hpp>
#include <Dot++/NullConstructionPolicy.hpp>
#include <Dot++/lexer/TokenInfo.hpp>
#include <Dot++/parser/states/ReadLeftBracketVertexAttributeState.hpp>
namespace {
using namespace dot_pp::lexer;
using namespace dot_pp::parser;
struct InitialStateFixture
{
TokenStack attributes;
TokenStack stack;
dot_pp::NullConstructionPolicy constructor;
states::ReadLeftBracketVertexAttributeState<dot_pp::NullConstructionPolicy> state;
};
TEST_FIXTURE(InitialStateFixture, verifyInstatiation)
{
}
TEST_FIXTURE(InitialStateFixture, verifyTransitionsToReadVertexAttributeName)
{
std::deque<TokenInfo> tokens;
tokens.emplace_back(Token("attribute1", TokenType::string), FileInfo("test.dot"));
auto handle = tokens.cbegin();
CHECK_EQUAL(ParserState::ReadVertexAttributeName, state.consume(handle++, stack, attributes, constructor));
CHECK_EQUAL(1U, attributes.size());
CHECK_EQUAL(0U, stack.size());
}
TEST_FIXTURE(InitialStateFixture, verifyTransitionsToGraphAttributeValue)
{
std::deque<TokenInfo> tokens;
tokens.emplace_back(Token("]", TokenType::r_bracket), FileInfo("test.dot"));
auto handle = tokens.cbegin();
// we share this state with graph attributes
CHECK_EQUAL(ParserState::ReadGraphAttributeValue, state.consume(handle++, stack, attributes, constructor));
CHECK_EQUAL(0U, stack.size());
}
TEST_FIXTURE(InitialStateFixture, verifyThrowsOnWrongTokenType)
{
std::deque<TokenInfo> tokens;
tokens.emplace_back(Token("keyword", TokenType::keyword), FileInfo("test.dot"));
tokens.emplace_back(Token("string_lit", TokenType::string_literal), FileInfo("test.dot"));
tokens.emplace_back(Token("l_paren", TokenType::l_paren), FileInfo("test.dot"));
tokens.emplace_back(Token("r_paren", TokenType::r_paren), FileInfo("test.dot"));
tokens.emplace_back(Token("edge", TokenType::edge), FileInfo("test.dot"));
tokens.emplace_back(Token("edge", TokenType::directed_edge), FileInfo("test.dot"));
tokens.emplace_back(Token("l_bracket", TokenType::l_bracket), FileInfo("test.dot"));
tokens.emplace_back(Token("equal", TokenType::equal), FileInfo("test.dot"));
tokens.emplace_back(Token("end_statement", TokenType::end_statement), FileInfo("test.dot"));
tokens.emplace_back(Token("blah blah", TokenType::comment), FileInfo("test.dot"));
tokens.emplace_back(Token("blah \n blah", TokenType::multiline_comment), FileInfo("test.dot"));
for(auto handle = tokens.cbegin(), end = tokens.cend(); handle != end; ++handle)
{
CHECK_THROW(state.consume(handle, stack, attributes, constructor), dot_pp::SyntaxError);
}
}
}
|
int ledPin = 12;
int durations[] = {200, 200, 200, 500, 500, 500, 200, 200, 200};
void setup() // run once, when the sketch starts
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop() // run over and over again
{
for (int i = 0; i < 9; i++)
{
flash(durations[i]);
if (i == 2)
{
delay(300);
}
}
delay(1000); // wait 1 second before we start again
}
void flash(int duration)
{
digitalWrite(ledPin, HIGH);
delay(duration);
digitalWrite(ledPin, LOW);
delay(duration);
}
|
#include "treeface/graphics/guts/SubPath.h"
#include "treeface/graphics/guts/LineStroker.h"
using namespace treecore;
namespace treeface
{
void SubPath::stroke_complex( Geometry::HostVertexCache& result_vertices,
treecore::Array<IndexType>& result_indices,
Vec2f& result_skeleton_min,
Vec2f& result_skeleton_max,
const StrokeStyle& style ) const
{
treecore_assert( glyphs[0].type == GLYPH_TYPE_LINE );
LineStroker stroker( style );
//
// generate stroke outline
//
Vec2f v_begin;
Vec2f v_prev;
// glyph 0 is start vertex, so glyph 1 is the actual first glyph
for (int i_glyph = 1; i_glyph < glyphs.size(); i_glyph++)
{
const PathGlyph& glyph_prev = glyphs[i_glyph - 1];
const PathGlyph& glyph = glyphs[i_glyph];
Geometry::HostVertexCache curr_glyph_skeleton( sizeof(Vec2f) );
glyph.segment( glyph_prev.end, curr_glyph_skeleton );
treecore_assert( curr_glyph_skeleton.size() > 0 );
// first glyph, render cap
if (i_glyph == 1)
{
v_begin = curr_glyph_skeleton.get_first<Vec2f>() - glyphs[0].end;
v_begin.normalize();
v_prev = v_begin;
if (closed)
stroker.close_stroke_begin( glyph_prev.end, v_begin );
else
stroker.cap_begin( glyph_prev.end, v_begin );
// update skeleton bound
update_bound( glyph_prev.end, result_skeleton_min, result_skeleton_max );
}
// render line segments of this glyph
for (int i = 0; i < curr_glyph_skeleton.size(); i++)
{
bool use_line_join;
Vec2f p1;
Vec2f p2;
if (i == 0)
{
p1 = glyph_prev.end;
p2 = curr_glyph_skeleton.get<Vec2f>( i );
use_line_join = true;
}
else
{
p1 = curr_glyph_skeleton.get<Vec2f>( i - 1 );
p2 = curr_glyph_skeleton.get<Vec2f>( i );
use_line_join = false;
}
if (p1 != p2)
{
v_prev = stroker.extend_stroke( v_prev, p1, p2, use_line_join );
update_bound( p2, result_skeleton_min, result_skeleton_max );
}
}
}
if (closed)
{
const Vec2f& p_last = glyphs.getLast().end;
const Vec2f& p_first = glyphs.getFirst().end;
if (p_last != p_first)
{
stroker.extend_stroke( v_prev, p_last, p_first, true );
SUCK_GEOM_BLK( OutlineSucker sucker( stroker.part_left, "going to close stroke using actual end" );
sucker.draw_outline( stroker.part_right );
sucker.draw_vtx( p_last );
sucker.draw_vtx( p_first );
sucker.draw_unit_vector( p_first, v_begin );
)
stroker.close_stroke_end( p_last, p_first, v_begin );
}
else
{
Vec2f p_prev_calc = p_first - v_prev * (style.width * 2);
SUCK_GEOM_BLK( OutlineSucker sucker( stroker.part_left, "end overlap start, going to close stroke using calculated end" );
sucker.draw_outline( stroker.part_right );
sucker.draw_vtx( p_prev_calc );
sucker.draw_vtx( p_first );
sucker.draw_unit_vector( p_first, v_begin );
)
stroker.close_stroke_end( p_prev_calc, p_first, v_begin );
}
}
else
{
stroker.cap_end( glyphs.getLast().end, v_prev );
}
//
// triangulate stroke outline, which provides final result
//
stroker.triangulate( result_vertices, result_indices, closed );
}
} // namespace treeface
|
#pragma once
#ifndef _LR_CONSTRUCTOR_PRODUC_ITEM_
#define _LR_CONSTRUCTOR_PRODUC_ITEM_
#include <iostream>
#include <vector>
#include <set>
#include "LrContext.h"
#include "Produc.h"
using namespace std;
class ProducItem
{
private:
//该项目对应的产生式编号
size_t produc_no;
public:
//该项目对应的产生式
Produc produc;
//该项目当前进度位置
size_t cursor;
//该项目的展望符
set<string> prospects;
ProducItem(size_t produc_no, Produc p);
size_t get_no();
//返回该项目是否为规约项目
bool statute();
//获取当前进度后第二位符号,若无则为$
Symbol next_prospects();
//判断相等,精确到展望符
bool identical(const ProducItem& item)const;
//判断相等,不精确到展望符
bool operator==(const ProducItem& item)const;
ProducItem& operator=(const ProducItem& item);
//克隆当前项目,并进度+1
ProducItem* clone_puls();
//在vector中查找当前对象
vector<ProducItem*>::iterator find_from_vector(vector<ProducItem*>& v);
};
#endif
|
#include "lib_guide_screen.h"
/* note
提示屏如果两条语音间隔小于0.5秒,后一条语音会覆盖前一条语音
如果一条语音开始播放,要等播放完才会放下一条语音
*/
guide_screen::guide_screen(const char * ip, short port)
{
modbus = NULL;
is_connected = false;
monitor_quit = false;
timeout = 0;
dev_ip = ip;
dev_port = port;
last_gs_index = 0;
gs_update_time = time(0);
gs_repeat = 0;
modbus_init();
pthread_create(&thrd_monitor, NULL, connect_monitor, this);
}
guide_screen::~guide_screen()
{
monitor_quit = true;
pthread_join(thrd_monitor, NULL);
modbus_uninit();
}
int guide_screen::modbus_init()
{
int res;
modbus = modbus_new_tcp(dev_ip.c_str(), dev_port);
if (!modbus) {
printf("create modbus failed\n");
modbus = NULL;
return -1;
}
//设置从机地址
modbus_set_slave(modbus, 1);
res = modbus_connect(modbus);
if (res < 0) {
printf("[guide screen] connect failed:%s\n", modbus_strerror(errno));
modbus_close(modbus);
modbus_free(modbus);
modbus = NULL;
return -1;
}
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
//modbus_set_response_timeout(modbus, &tv);
//modbus_set_response_timeout(modbus, tv.tv_sec, tv.tv_usec);
is_connected = true;
timeout = 0;
return 0;
}
void guide_screen::modbus_uninit()
{
if (modbus) {
modbus_close(modbus);
modbus_free(modbus);
is_connected = false;
}
}
void guide_screen::set_index(uint16_t index, bool audio_en)
{
int ret;
uint16_t vals[2];
time_t now = time(NULL);
if (last_gs_index != index) {
last_gs_index = index;
gs_repeat = 0;
} else {
if ((now - gs_update_time) < 2)
return;
gs_repeat++;
if (gs_repeat > 3)
return;
}
gs_update_time = now;
if (!is_connected) {
return;
}
mtx_gs.lock();
vals[0] = audio_en?index:0;
vals[1] = index;
//多写一次保证有一次成功
int retry = 0;
do {
ret = modbus_write_registers(modbus, 0, 2, vals);
if (ret < 0) {
printf("[car gs]: index:%d res:%d, errno:%s\n", index, ret, modbus_strerror(errno));
retry++;
} else
break;
} while(retry < 2);
mtx_gs.unlock();
}
int guide_screen::heart_beat()
{
int res;
uint16_t vals[2];
mtx_gs.lock();
res = modbus_read_registers(modbus, 0, 2, vals);
mtx_gs.unlock();
return res;
}
void * guide_screen::connect_monitor(void * arg)
{
int res;
guide_screen * gs = (guide_screen *)arg;
while (!gs->monitor_quit) {
if (gs->is_connected) {
res = gs->heart_beat();
if (res < 0)
gs->timeout++;
else
gs->timeout = 0;
if (gs->timeout > GS_TIMEOUT) {
printf("[car gs]:no heart beat for 10 seconds,reconnect\n");
gs->modbus_uninit();
}
} else {
gs->modbus_init();
}
sleep(1);
}
return NULL;
}
|
#include "Folder.h"
#include <io.h>
#include <direct.h>
#include <algorithm>
#include <iostream>
using namespace std;
Folder::Folder()
{
}
Folder::~Folder()
{
}
bool Folder::operator<(const Folder& a)
{
return this->getPath() < a.getPath();
}
bool Folder::init(const char* path)
{
FileList.clear();
SubList.clear();
if (!IsExitPath(path))// _access(path, 0) == -1)
{
CreateFolderAsFullPath(path);
init(path);
return true;
}
m_Path.assign(path);
fileCount = 0;
SubCount = 0;
#ifdef _WIN64
init64(path);
#else
init32(path);
#endif
sort(FileList.begin(), FileList.end());
sort(SubList.begin(), SubList.end());
currentFile = -1;
currentFolder = -1;
return true;
}
void Folder::init64(const char* path)
{
//文件句柄
__int64 hFile = 0;
//文件信息
struct __finddata64_t fileinfo;
string p;
if ((hFile = _findfirst64(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
//如果是目录,迭代之
//如果不是,加入列表
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
Folder temp;
temp.init(p.assign(path).append("\\").append(fileinfo.name).c_str());
SubList.push_back(temp);
SubCount++;
}
}
else
{
FileOpe temp(p.assign(path).append("\\").append(fileinfo.name).c_str());
FileList.push_back(temp);
fileCount++;
}
} while (_findnext64(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
void Folder::init32(const char* path)
{
//文件句柄
long hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
//如果是目录,迭代之
//如果不是,加入列表
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
Folder temp;
temp.init(p.assign(path).append("\\").append(fileinfo.name).c_str());
SubList.push_back(temp);
SubCount++;
}
}
else
{
FileOpe temp(p.assign(path).append("\\").append(fileinfo.name).c_str());
FileList.push_back(temp);
fileCount++;
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
bool Folder::IsExitPath(const char* path)
{
return _access(path, 0) == -1 ? false : true;
}
int Folder::getFileCount()
{
return fileCount;
}
int Folder::getFolderCount()
{
return SubCount;
}
FileOpe& Folder::getFirstFile()
{
currentFile = 1;
return FileList[currentFile-1];
}
bool Folder::getNextFile(FileOpe& res)
{
currentFile++;
if (currentFile <= 0 ||currentFile == fileCount+1)return false;
//currentFile %= fileCount - 1;
res = FileList[currentFile-1];
return true;
}
bool Folder::isEndFile()
{
return currentFile == fileCount+1;
}
Folder& Folder::getFirstFolder()
{
currentFolder = 1;
return SubList[currentFolder - 1];
}
bool Folder::getNextFolder(Folder& res)// :getNextFile(FileOpe& res)
{
currentFolder++;
if (currentFolder <= 0 || currentFolder == SubCount + 1)return false;
//currentFile %= fileCount - 1;
res = SubList[currentFolder - 1];
return true;
}
bool Folder::isEndFolder()
{
return currentFolder == SubCount + 1;
}
string Folder::getPath()const
{
return m_Path;
}
string Folder::getPathName()const
{
string res;
res = m_Path.substr(m_Path.find_last_of('\\')+1);
return res;
}
int Folder::CreateFileAsFullPath(const char* name)
{
if (IsExitPath(name))//_access(name, 0) != -1)
{
return SearchFile(name);
}
ofstream tem(name);
if (tem.fail())return -1;
fileCount++;
FileOpe tt(name);
FileList.push_back(tt);
sort(FileList.begin(), FileList.end());
tem.close();
return SearchFile((tt.getPath() + tt.getName()).c_str());
//return fileCount - 1;
}
int Folder::_CreateFile(const char* name)
{
string str;
str.assign(m_Path).append("\\").append(name);
if (IsExitPath(str.c_str()))//_access(str.c_str(), 0) != -1)
{
return SearchFile(str.c_str());
}
ofstream tem(str);
if (tem.fail())return -1;
fileCount++;
FileOpe *tt = new FileOpe(str.c_str());
FileList.push_back(*tt);
sort(FileList.begin(), FileList.end());
tem.close();
return SearchFile((tt->getPath() + tt->getName()).c_str());
}
int Folder::CreateFolder(const char* name)
{
string str;
str.assign(m_Path).append("\\").append(name);
if (IsExitPath(str.c_str()))//_access(str.c_str(), 0) != -1)
{
return SearchFolder(str.c_str());
}
_mkdir(str.c_str());
SubCount++;
Folder tt;
tt.init(str.c_str());
SubList.push_back(tt);
sort(SubList.begin(), SubList.end());
return SearchFolder(tt.getPath().c_str());
//return SubCount - 1;
}
bool Folder::CreateFolderAsFullPath(const char* name)
{
if (IsExitPath(name))//_access(name, 0) != -1)
{
return true;//SearchFolder(name);
}
return _mkdir(name) == 0?true:false;
/*SubCount++;
Folder tt;
tt.init(name);
SubList.push_back(tt);
sort(SubList.begin(), SubList.end());
return SearchFolder(tt.getPath().c_str());*/
//return SubCount - 1;
}
int Folder::SearchFile(const char* name)const
{
/*for (int i = 0; i < FileList.size(); i++)
{
if (FileList[i].getPath() + FileList[i].getName() == name)
{
return i;
}
}*/
if (fileCount == 0)return -1;
else if (fileCount == 1)
{
if ((FileList[0].getPath() + FileList[0].getName()) != name)
return -1;
else return 0;
}
for (int a = 0, b = FileList.size() - 1; a <= b;)
{
if (a + 1 >= b)
if ((FileList[a].getPath() + FileList[a].getName()) == name) return a;
else if((FileList[b].getPath() + FileList[b].getName()) == name)return b;
else return -1;
int c = (a + b) / 2;
string com = FileList[c].getPath() + FileList[c].getName();
if (com < name) {
a = c;
}
else if (com > name)
{
b = c;
}
else
return c;
}
}
FileOpe& Folder::FindFile(int ind)
{
return FileList[ind];
}
int Folder::SearchFolder(const char* path)const
{
/*for (int i = 0; i < FileList.size(); i++)
{
if (SubList[i].getPath() == path)
{
return i;
}
}*/
if (SubCount == 0)return -1;
else if (SubCount == 1)
{
if ((SubList[0].getPath() == path))return 0;
else return -1;
}
for (int a = 0, b = SubList.size() - 1; a < b;)
{
if (a == b)
if (SubList[a].getPath() == path) return a;
else return -1;
if (a + 1 >= b)
if (SubList[a].getPath() == path)return a;
else if (SubList[b].getPath() == path)return b;
else return -1;
int c = (a + b) / 2;
string com = SubList[c].getPath();// +SubList[c].getName();
if (com < path) {
a = c;
}
else if (com > path)
{
b = c;
}
else
return c;
}
}
Folder& Folder::FindFolder(int ind)
{
return SubList[ind];
}
int Folder::AddFile(const char* name)
{
string str;
str.assign(m_Path).append("\\").append(name);
if (fileCount == 1)
{
if ((FileList[0].getPath() + FileList[0].getName()) > name)
{
FileOpe tt(str.c_str());
FileList.insert(FileList.begin(), tt);
fileCount++;
return 0;
}
else if ((FileList[0].getPath() + FileList[0].getName()) < name)
{
FileOpe tt(str.c_str());
FileList.insert(FileList.begin()+1, tt);
fileCount++;
return 1;
}
else return 0;
}
for (int a = 0, b = FileList.size() - 1; a < b;)
{
if (a + 1 >= b)
if ((FileList[a].getPath() + FileList[a].getName()) == name) return a;
else if ((FileList[b].getPath() + FileList[b].getName()) == name)return b;
else {
FileOpe tt(str.c_str());
FileList.insert(FileList.begin() + b, tt);
fileCount++;
return b;
}
int c = (a + b) / 2;
string com = FileList[c].getPath() + FileList[c].getName();
if (com < str) {
a = c;
}
else if (com > str)
{
b = c;
}
else
return c;
}
}
int Folder::AddFolder(const char* path)
{
string str;
str.assign(m_Path).append("\\").append(path);
for (int a = 0, b = SubList.size() - 1; a < b;)
{
if (a == b)
if (SubList[a].getPath() == path) return a;
else {
Folder tt;
tt.init(str.c_str());
SubList.insert(SubList.begin() + b, tt);
SubCount++;
return b;
}
if (a + 1 >= b)
if (SubList[a].getPath() == path)return a;
else if (SubList[b].getPath() == path)return b;
else {
Folder tt;
tt.init(str.c_str());
SubList.insert(SubList.begin() + b, tt);
SubCount++;
return b;
}
int c = (a + b) / 2;
string com = SubList[c].getPath();// +SubList[c].getName();
if (com < path) {
a = c;
}
else if (com > path)
{
b = c;
}
else
return c;
}
}
|
/*
* 题目:131. 分割回文串
* 地址:https://leetcode-cn.com/problems/palindrome-partitioning/
* 知识点:dfs + dp
*/
class Solution {
public:
void dfs(string &s, int i) {
if (i == n) {
ans.push_back(temp);
return;
}
for (int j = i; j < n; j++) {
if (dp[i][j]) {
temp.push_back(s.substr(i, j - i + 1));
dfs(s, j + 1);
temp.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
n = s.length();
dp.assign(n, vector<bool>(n, true));
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
dp[i][j] = (s[i] == s[j]) && dp[i + 1][j - 1];
}
}
dfs(s, 0);
return ans;
}
private:
vector<string> temp;
vector<vector<string>> ans;
vector<vector<bool>> dp;
int n;
};
|
#include "clientinfo.h"
// This makes sure the cpp and header refer to the same vector
std::vector<ClientInfo> ClientInfo::clients;
ClientInfo::ClientInfo(char *hostName, char *ipAddress ) {
this->hostName = hostName;
this->ipAddress = ipAddress;
// this->fileNames = new std::vector<std::string>;
}
ClientInfo::~ClientInfo() {}
void ClientInfo::formatFilesList (const char *message){
std::vector<std::string> files = split(message, '\n');
// Erase what was in the fileNames vector
std::fill(this->fileNames.begin(), this->fileNames.end(), "");
// Extract file names without '|' delimeter
for (auto fileName = files.begin(); fileName != files.end(); fileName++) {
std::vector<std::string> temp = split(fileName->c_str(), '|');
this->fileNames.push_back(temp[0]);
}
}
char* ClientInfo::getHostName() {
return this->hostName;
}
char* ClientInfo::getIpAddress() {
return this->ipAddress;
}
std::vector<ClientInfo> ClientInfo::getClients() {
return clients;
}
void ClientInfo::addClient(ClientInfo *info) {
clients.push_back(*info);
}
bool ClientInfo::fileFoundInClient(std::string FileBeingSearched){
bool Found = false;
/* data */
if(std::find(this->fileNames.begin(), this->fileNames.end(), FileBeingSearched) != this->fileNames.end()) {
Found = true;
}
return Found;
}
std::string ClientInfo::getClientsByFileName(std::string fileName){
std::string message = fileName + "|";
for(auto iter = clients.begin(); iter != clients.end(); iter++) {
// This flag is used to add the ipaddress if the filename being added is the
// first file for the client being searched.
bool firstFileAdded = true;
bool wasUpdated = false;
for(auto clientFile = iter->fileNames.begin(); clientFile != iter->fileNames.end(); clientFile++) {
if (fileName.compare(*clientFile) == 0) {
message += iter->getIpAddress();
message += " ";
}
}
}
if (message.back() == ' ') {
message.pop_back();
}
message += "\n";
return message;
}
bool ClientInfo::removeClient(char* HostName, char *IpAddress)
{ int i = 0;
bool deleted = false;
for(std::vector<ClientInfo>::iterator iter = ClientInfo::getClients().begin(); iter != ClientInfo::getClients().end(); iter++) {
if (strcmp(HostName, iter->getHostName()) == 0 && strcmp(IpAddress, iter->getIpAddress()) == 0) {
std::cout << iter->getHostName();
clients.erase (clients.begin()+i);
deleted = true;
break;
}
i++;
}
return deleted;
//Clients.erase(std::remove(Clients.begin(),Clients.end(),)Clients.end());
}
|
//=====================================================
// File : STL_algo_interface.hh
// Author : L. Plagne <laurent.plagne@edf.fr)>
// Copyright (C) EDF R&D, lun sep 30 14:23:24 CEST 2002
//=====================================================
//
// 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.
//
#ifndef STL_ALGO_INTERFACE_HH
#define STL_ALGO_INTERFACE_HH
#include <string>
#include <vector>
#include <numeric>
#include <algorithm>
#include "utilities.h"
template<class real>
class STL_algo_interface{
public :
typedef real real_type ;
typedef std::vector<real> stl_vector;
typedef std::vector<stl_vector > stl_matrix;
typedef stl_matrix gene_matrix;
typedef stl_vector gene_vector;
static inline std::string name( void )
{
return "STL_algo";
}
static void free_matrix(gene_matrix & A, int N){}
static void free_vector(gene_vector & B){}
static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){
A=A_stl ;
}
static inline void vector_from_stl(gene_vector & B, stl_vector & B_stl){
B=B_stl ;
}
static inline void vector_to_stl(gene_vector & B, stl_vector & B_stl){
B_stl=B ;
}
static inline void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){
A_stl=A ;
}
static inline void copy_vector(const gene_vector & source, gene_vector & cible, int N){
for (int i=0;i<N;i++)
cible[i]=source[i];
}
static inline void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N)
{
for (int i=0;i<N;i++){
for (int j=0;j<N;j++){
cible[i][j]=source[i][j];
}
}
}
class somme {
public:
somme(real coef):_coef(coef){};
real operator()(const real & val1, const real & val2)
{
return _coef * val1 + val2;
}
private:
real _coef;
};
class vector_generator {
public:
vector_generator(const gene_matrix & a_matrix, const gene_vector & a_vector):
_matrice(a_matrix),
_vecteur(a_vector),
_index(0)
{};
real operator()( void )
{
const gene_vector & ai=_matrice[_index];
int N=ai.size();
_index++;
return std::inner_product(&ai[0],&ai[N],&_vecteur[0],0.0);
}
private:
int _index;
const gene_matrix & _matrice;
const gene_vector & _vecteur;
};
static inline void atv_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)
{
std::generate(&X[0],&X[N],vector_generator(A,B));
}
static inline void axpy(real coef, const gene_vector & X, gene_vector & Y, int N)
{
std::transform(&X[0],&X[N],&Y[0],&Y[0],somme(coef));
}
};
#endif
|
/*!
\author Ken Jinks
\date Aug 2018
\file jinks_math.cpp
\brief This file contains math functions not in math.h
*/
#include "jinks_math.h"
namespace JinksMath
{
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2004 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef OP_TIME_WIDGET_H
#define OP_TIME_WIDGET_H
#include "modules/widgets/OpWidget.h"
#define PATTERN_EDIT
#ifdef PATTERN_EDIT
#include "modules/widgets/OpEdit.h"
#endif // PATTERN_EDIT
#include "modules/forms/datetime.h"
class OpEdit;
class OpNumberEdit;
class OpSpinner;
/** OpTime - Widget for inputting a time. Has a textfield and spinbutton */
class OpTime : public OpWidget
#ifndef QUICK
, public OpWidgetListener
#endif // QUICK
{
protected:
OpTime();
public:
static OP_STATUS Construct(OpTime** obj);
// Override base class
OP_STATUS GetText(OpString &str);
OP_STATUS SetText(const uni_char* text);
virtual void SetReadOnly(BOOL readonly);
virtual void SetEnabled(BOOL enabled);
virtual void GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows);
OP_STATUS SetValue(TimeSpec date_time);
/**
* Returns true if a value was returned.
*/
BOOL GetTime(TimeSpec& out_value) const;
/**
* Returns TRUE if there is an input value.
*/
BOOL HasValue() const;
void SetMinValue(TimeSpec new_min) { SetMinValueInternal(TRUE, new_min); }
void SetMaxValue(TimeSpec new_max) { SetMaxValueInternal(TRUE, new_max); }
/**
* @param step_value Step in seconds.
*/
void SetStep(TimeSpec step_base, double step_value) { SetStepInternal(TRUE, step_base, step_value*1000.0); }
/**
* @param step_value Step in milliseconds.
*/
void SetStepMS(TimeSpec step_base, double step_value) { SetStepInternal(TRUE, step_base, step_value); }
/** Clear the limitation of minimal time. */
void ClearMinValue() { SetMinValueInternal(FALSE, TimeSpec()); }
/** Clear the limitation of maximal time. */
void ClearMaxValue() { SetMaxValueInternal(FALSE, TimeSpec()); }
/** Clear the step value. */
void ClearStep() { SetStepInternal(FALSE, TimeSpec(), 0.0); }
// == Hooks ======================
void OnResize(INT32* new_w, INT32* new_h);
void OnFocus(BOOL focus,FOCUS_REASON reason);
BOOL OnMouseWheel(INT32 delta,BOOL vertical);
void EndChangeProperties();
// Implementing the OpTreeModelItem interface
//virtual Type GetType() {return WIDGET_TYPE_TIME;}
//virtual BOOL IsOfType(Type type) { return type == WIDGET_TYPE_TIME || OpWidget::IsOfType(type); }
// OpWidgetListener
virtual void OnChangeWhenLostFocus(OpWidget *widget);
virtual void OnClick(OpWidget *object, UINT32 id);
#ifndef QUICK
/* These seemingly meaningless overrides are implemented to avoid warnings
caused, by the overrides of same-named functions from OpWidget. */
virtual void SetValue(INT32 value) {}
#endif // QUICK
BOOL OnInputAction(OpInputAction* action);
enum TimeFieldPrecision
{
TIME_PRECISION_MINUTES, ///< Minute precision
TIME_PRECISION_SECONDS, ///< Second precision
TIME_PRECISION_SUBSECOND, ///< 3 fraction digits
TIME_PRECISION_HUNDRETHS = TIME_PRECISION_SUBSECOND,///< deprecated
TIME_PRECISION_SUBSECOND2, ///< 6 fraction digits
TIME_PRECISION_SUBSECOND3 ///< 9 fraction digits
};
void SetTimePrecision(TimeFieldPrecision precision);
private:
#ifdef PATTERN_EDIT
const uni_char* GetEditPattern() const;
OP_STATUS SetEmptyValue();
OpEdit* m_hour_field;
#else
OpNumberEdit* m_hour_field;
OpNumberEdit* m_minute_field;
OpEdit* m_colon1_field;
signed char m_seconds;
signed char m_hundreths;
#endif // PATTERN_EDIT
void GetPreferredSpinnerSize(int widget_height, INT32* spinner_width, INT32* spinner_height);
/**
* Adjusts the unadjusted_value to be within min/max if those are set.
*/
void MinMaxAdjust(int delta, TimeSpec& unadjusted_value) const;
/**
* Enables/disables spinner buttons depending on current value and min/max.
*/
void UpdateButtonState();
void SetMinValueInternal(BOOL enable, TimeSpec new_min);
void SetMaxValueInternal(BOOL enable, TimeSpec new_max);
void SetStepInternal(BOOL enable, TimeSpec step_base, double step_value_milliseconds);
OpSpinner* m_spinner;
TimeSpec m_min_value;
TimeSpec m_max_value;
TimeSpec m_step_base;
double m_step_value_milliseconds;
BOOL m_has_min_value;
BOOL m_has_max_value;
BOOL m_has_step;
TimeFieldPrecision m_precision;
TimeSpec m_last_set_full_time;
BOOL m_readonly;
#if 0 // Doesn't work inside OpDateTime. :-(
// We don't want to do magical things with the time field when the user just
// temporarily switches to another program/document so we keep track of why
// focus was lost.
public:
virtual void OnKeyboardInputLost(OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason);
private:
BOOL m_last_focus_lost_was_release;
BOOL m_pending_changed_focus_lost;
#endif
};
#endif // OP_TIME_WIDGET_H
|
#ifndef DESIGNPATTERN_OBSERVER_SUBJECT_H_
#define DESIGNPATTERN_OBSERVER_SUBJECT_H_
#include <vector>
#include "isubject.h"
namespace DesignPatter
{
class Subject : public ISubject
{
public:
virtual bool Register(IObserver*);
virtual bool Notify() const;
private:
typedef std::vector<IObserver*> ObserverVec;
ObserverVec observers_;
};
}
#endif
|
/*
Copyright (c) 2005-2022 Xavier Leclercq
Released under the MIT License
See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt
*/
#include "TestSequence.hpp"
namespace Ishiko
{
TestSequence::TestSequence(const TestNumber& number, const std::string& name)
: Test(number, name), m_itemsObserver(std::make_shared<ItemsObserver>(*this))
{
}
TestSequence::TestSequence(const TestNumber& number, const std::string& name, const TestContext& context)
: Test(number, name, context), m_itemsObserver(std::make_shared<ItemsObserver>(*this))
{
}
const Test& TestSequence::operator[](size_t pos) const
{
return *(m_tests[pos]);
}
size_t TestSequence::size() const noexcept
{
return m_tests.size();
}
void TestSequence::append(std::shared_ptr<Test> test)
{
// We need to update the number of the test
if (m_tests.size() == 0)
{
test->setNumber(number().getDeeperNumber());
}
else
{
TestNumber newNumber = m_tests.back()->number();
test->setNumber(++newNumber);
}
m_tests.push_back(test);
test->observers().add(m_itemsObserver);
}
void TestSequence::setNumber(const TestNumber& number)
{
Test::setNumber(number);
TestNumber deeperNumber = number.getDeeperNumber();
for (std::shared_ptr<Test>& test : m_tests)
{
test->setNumber(deeperNumber++);
}
}
void TestSequence::getPassRate(size_t& unknown, size_t& passed, size_t& passedButMemoryLeaks, size_t& exception,
size_t& failed, size_t& skipped, size_t& total) const
{
if (m_tests.size() == 0)
{
// Special case. If the sequence is empty we consider it to be a single unknown test case. If we didn't do
// that this case would go unnoticed in the returned values.
unknown = 1;
passed = 0;
passedButMemoryLeaks = 0;
exception = 0;
failed = 0;
total = 1;
}
else
{
for (size_t i = 0; i < m_tests.size(); ++i)
{
size_t u = 0;
size_t p = 0;
size_t pbml = 0;
size_t e = 0;
size_t f = 0;
size_t s = 0;
size_t t = 0;
m_tests[i]->getPassRate(u, p, pbml, e, f, s, t);
unknown += u;
passed += p;
passedButMemoryLeaks += pbml;
exception += e;
failed += f;
skipped += s;
total += t;
}
}
}
void TestSequence::traverse(std::function<void(const Test& test)> function) const
{
function(*this);
for (size_t i = 0; i < m_tests.size(); ++i)
{
m_tests[i]->traverse(function);
}
}
void TestSequence::addToJUnitXMLTestReport(JUnitXMLWriter& writer) const
{
// We don't usually print sequence test results as the report is supposed to be a flat list of all tests but if the
// sequence is empty we print it else it would go unnoticed. By design empty test sequences do not really make
// sense and should not be present in test suites.
if (m_tests.empty())
{
writer.writeTestCaseStart("unknown", name());
if (!passed())
{
writer.writeFailureStart();
writer.writeFailureEnd();
}
writer.writeTestCaseEnd();
}
}
void TestSequence::doRun()
{
// By default the outcome is unknown
TestResult result = TestResult::unknown;
for (size_t i = 0; i < m_tests.size(); ++i)
{
Test& test = *m_tests[i];
test.run();
// Update the result
TestResult newResult = test.result();
if (i == 0)
{
// The first test determines the initial value of the result
result = newResult;
}
else if (result == TestResult::unknown)
{
// If the current sequence outcome is unknown it can only get worse and be set
// to exception or failed (if the outcome we are adding is exception or
// failed)
if ((newResult == TestResult::failed) || (newResult == TestResult::exception))
{
result = newResult;
}
}
else if (result == TestResult::passed)
{
// If the current sequence outcome is passed it stays at this state only if the
// result we are adding is passed or skipped, else it will be 'unknown',
// 'passedButMemoryLeaks', 'exception' or 'failed'.
// depending on the outcome of the result we are adding.
if (newResult != TestResult::skipped)
{
result = newResult;
}
}
else if (result == TestResult::passedButMemoryLeaks)
{
// It can only stay at this state if the test is passed or ePassedButMemoryLeaks.
if ((newResult == TestResult::failed) ||
(newResult == TestResult::exception) ||
(newResult == TestResult::unknown))
{
result = newResult;
}
}
else if (result == TestResult::exception)
{
// It can only get worse. This happens only if the outcome is 'failed'
if (newResult == TestResult::failed)
{
result = newResult;
}
}
else if (result == TestResult::skipped)
{
result = newResult;
}
}
setResult(result);
}
TestSequence::ItemsObserver::ItemsObserver(TestSequence& sequence)
: m_sequence(sequence)
{
}
void TestSequence::ItemsObserver::onLifecycleEvent(const Test& source, EEventType type)
{
m_sequence.observers().notifyLifecycleEvent(source, type);
}
void TestSequence::ItemsObserver::onCheckFailed(const Test& source, const std::string& message, const char* file,
int line)
{
m_sequence.observers().notifyCheckFailed(source, message, file, line);
}
void TestSequence::ItemsObserver::onExceptionThrown(const Test& source, std::exception_ptr exception)
{
m_sequence.observers().notifyExceptionThrown(source, exception);
}
}
|
#include <fstream>
int main(){
std::fstream i("input.txt"), o("output.txt", 2);
int a, b = 0;
i >> a;
while (a > 0) {
b += a % 2;
a /= 2;
}
o << b;
}
|
#pragma once
#include "checksum_crc.h"
#include "interface.h"
#include "bitbuf.h"
#include "dt_common.h"
#include "dt_recv.h"
#include "../../../Utils/Utils.h"
struct model_t;
class CSentence;
struct vrect_t;
struct cmodel_t;
class IMaterial;
class CAudioSource;
class CMeasureSection;
class SurfInfo;
class ISpatialQuery;
struct cache_user_t;
class IMaterialSystem;
struct ScreenFade_t;
struct ScreenShake_t;
class CEngineSprite;
class CGlobalVarsBase;
class CPhysCollide;
class CSaveRestoreData;
class INetChannelInfo;
struct datamap_t;
struct typedescription_t;
class CStandardRecvProxies;
struct client_textmessage_t;
class IAchievementMgr;
class CGamestatsData;
class KeyValues;
class IFileList;
class CRenamedRecvTableInfo;
class CMouthInfo;
class IConVar;
class ButtonCode_t;
class vmode_s;
enum StereoEye_t
{
STEREO_EYE_MONO = 0,
STEREO_EYE_LEFT = 1,
STEREO_EYE_RIGHT = 2,
STEREO_EYE_MAX = 3,
};
class CViewSetup
{
public:
int x;
int m_nUnscaledX;
int y;
int m_nUnscaledY;
int width;
int m_nUnscaledWidth;
int height;
StereoEye_t m_eStereoEye;
int m_nUnscaledHeight;
bool m_bOrtho;
float m_OrthoLeft;
float m_OrthoTop;
float m_OrthoRight;
float m_OrthoBottom;
float fov;
float fovViewmodel;
Vector origin;
QAngle angles;
float zNear;
float zFar;
float zNearViewmodel;
float zFarViewmodel;
bool m_bRenderToSubrectOfLargerScreen;
float m_flAspectRatio;
bool m_bOffCenter;
float m_flOffCenterTop;
float m_flOffCenterBottom;
float m_flOffCenterLeft;
float m_flOffCenterRight;
bool m_bDoBloomAndToneMapping;
bool m_bCacheFullSceneState;
bool m_bViewToProjectionOverride;
VMatrix m_ViewToProjection;
};
#define MAX_PLAYER_NAME_LENGTH 32
#define SIGNED_GUID_LEN 32
#define MAX_CUSTOM_FILES 4
typedef void *(*CreateClientClassFn)(int entnum, int serialNum);
typedef void *(*CreateEventFn)();
class ClientClass
{
public:
CreateClientClassFn m_pCreateFn;
CreateEventFn m_pCreateEventFn;
const char *m_pNetworkName;
RecvTable *m_pRecvTable;
ClientClass *m_pNext;
int m_ClassID;
};
typedef struct player_info_s
{
char m_sName[MAX_PLAYER_NAME_LENGTH];
int userID;
char guid[SIGNED_GUID_LEN + 1];
uint32_t friendsID;
char friendsName[MAX_PLAYER_NAME_LENGTH];
bool fakeplayer;
bool ishltv;
bool isreplay;
CRC32_t customFiles[MAX_CUSTOM_FILES];
unsigned char filesDownloaded;
} player_info_t;
struct AudioState_t
{
Vector m_Origin;
QAngle m_Angles;
bool m_bIsUnderwater;
};
enum SkyboxVisibility_t
{
SKYBOX_NOT_VISIBLE = 0,
SKYBOX_3DSKYBOX_VISIBLE,
SKYBOX_2DSKYBOX_VISIBLE,
};
struct SkyBoxMaterials_t
{
IMaterial *material[6];
};
enum class ClientFrameStage_t
{
FRAME_UNDEFINED = -1, // (haven't run any frames yet)
FRAME_START,
// A network packet is being recieved
FRAME_NET_UPDATE_START,
// Data has been received and we're going to start calling PostDataUpdate
FRAME_NET_UPDATE_POSTDATAUPDATE_START,
// Data has been received and we've called PostDataUpdate on all data recipients
FRAME_NET_UPDATE_POSTDATAUPDATE_END,
// We've received all packets, we can now do interpolation, prediction, etc..
FRAME_NET_UPDATE_END,
// We're about to start rendering the scene
FRAME_RENDER_START,
// We've finished rendering the scene.
FRAME_RENDER_END
};
enum RenderViewInfo_t
{
RENDERVIEW_UNSPECIFIED = 0,
RENDERVIEW_DRAWVIEWMODEL = (1 << 0),
RENDERVIEW_DRAWHUD = (1 << 1),
RENDERVIEW_SUPPRESSMONITORRENDERING = (1 << 2),
};
using LightCacheHandle_t = void *;
typedef struct _XUSER_DATA
{
BYTE m_sType;
union
{
int nData; // XUSER_DATA_TYPE_INT32
int64_t i64Data; // XUSER_DATA_TYPE_INT64
double dblData; // XUSER_DATA_TYPE_DOUBLE
struct // XUSER_DATA_TYPE_UNICODE
{
uint32_t cbData; // Includes null-terminator
char *pwszData;
} string;
float fData; // XUSER_DATA_TYPE_FLOAT
struct // XUSER_DATA_TYPE_BINARY
{
uint32_t cbData;
char *pbData;
} binary;
};
} XUSER_DATA, *PXUSER_DATA;
typedef struct _XUSER_CONTEXT
{
DWORD dwContextId;
DWORD dwValue;
} XUSER_CONTEXT, *PXUSER_CONTEXT;
typedef struct _XUSER_PROPERTY
{
DWORD dwPropertyId;
XUSER_DATA value;
} XUSER_PROPERTY, *PXUSER_PROPERTY;
struct OcclusionParams_t
{
float m_flMaxOccludeeArea;
float m_flMinOccluderArea;
};
class IVEngineClient013
{
public:
virtual int GetIntersectingSurfaces(const model_t *model, const Vector &vCenter, const float radius, const bool bOnlyVisibleSurfaces, SurfInfo *pInfos, const int nMaxInfos) = 0;
virtual Vector GetLightForPoint(const Vector &pos, bool bClamp) = 0;
virtual IMaterial *TraceLineMaterialAndLighting(const Vector &start, const Vector &end, Vector &diffuseLightColor, Vector &baseColor) = 0;
virtual const char *ParseFile(const char *data, char *token, int maxlen) = 0;
virtual bool CopyLocalFile(const char *source, const char *destination) = 0;
virtual void GetScreenSize(int &width, int &height) = 0;
virtual void ServerCmd(const char *szCmdString, bool bReliable = true) = 0;
virtual void ClientCmd(const char *szCmdString) = 0;
virtual bool GetPlayerInfo(int ent_num, player_info_t *pinfo) = 0;
virtual int GetPlayerForUserID(int userID) = 0;
virtual client_textmessage_t *TextMessageGet(const char *pName) = 0;
virtual bool Con_IsVisible(void) = 0;
virtual int GetLocalPlayer(void) = 0;
virtual const model_t *LoadModel(const char *pName, bool bProp = false) = 0;
virtual float Time(void) = 0;
virtual float GetLastTimeStamp(void) = 0;
virtual CSentence *GetSentence(CAudioSource *pAudioSource) = 0;
virtual float GetSentenceLength(CAudioSource *pAudioSource) = 0;
virtual bool IsStreaming(CAudioSource *pAudioSource) const = 0;
virtual void GetViewAngles(QAngle &va) = 0;
virtual void SetViewAngles(QAngle &va) = 0;
virtual int GetMaxClients(void) = 0;
virtual const char *Key_LookupBinding(const char *pBinding) = 0;
virtual const char *Key_BindingForKey(ButtonCode_t code) = 0;
virtual void StartKeyTrapMode(void) = 0;
virtual bool CheckDoneKeyTrapping(ButtonCode_t &code) = 0;
virtual bool IsInGame(void) = 0;
virtual bool IsConnected(void) = 0;
virtual bool IsDrawingLoadingImage(void) = 0;
virtual void Con_NPrintf(int pos, const char *fmt, ...) = 0;
virtual void Con_NXPrintf(const struct con_nprint_s *info, const char *fmt, ...) = 0;
virtual int IsBoxVisible(const Vector &mins, const Vector &maxs) = 0;
virtual int IsBoxInViewCluster(const Vector &mins, const Vector &maxs) = 0;
virtual bool CullBox(const Vector &mins, const Vector &maxs) = 0;
virtual void Sound_ExtraUpdate(void) = 0;
virtual const char *GetGameDirectory(void) = 0;
virtual const VMatrix &WorldToScreenMatrix() = 0;
virtual const VMatrix &WorldToViewMatrix() = 0;
virtual int GameLumpVersion(int lumpId) const = 0;
virtual int GameLumpSize(int lumpId) const = 0;
virtual bool LoadGameLump(int lumpId, void *pBuffer, int size) = 0;
virtual int LevelLeafCount() const = 0;
virtual ISpatialQuery *GetBSPTreeQuery() = 0;
virtual void LinearToGamma(float *linear, float *gamma) = 0;
virtual float LightStyleValue(int style) = 0;
virtual void ComputeDynamicLighting(const Vector &pt, const Vector *pNormal, Vector &color) = 0;
virtual void GetAmbientLightColor(Vector &color) = 0;
virtual int GetDXSupportLevel() = 0;
virtual bool SupportsHDR() = 0;
virtual void Mat_Stub(IMaterialSystem *pMatSys) = 0;
virtual void GetChapterName(char *pchBuff, int iMaxLength) = 0;
virtual char const *GetLevelName(void) = 0;
virtual int GetLevelVersion(void) = 0;
//#if !defined( NO_VOICE )
virtual struct IVoiceTweak_s *GetVoiceTweakAPI(void) = 0;
//#endif
virtual void EngineStats_BeginFrame(void) = 0;
virtual void EngineStats_EndFrame(void) = 0;
virtual void FireEvents() = 0;
virtual int GetLeavesArea(int *pLeaves, int nLeaves) = 0;
virtual bool DoesBoxTouchAreaFrustum(const Vector &mins, const Vector &maxs, int iArea) = 0;
virtual void SetAudioState(const AudioState_t &state) = 0;
virtual int SentenceGroupPick(int groupIndex, char *m_sName, int nameBufLen) = 0;
virtual int SentenceGroupPickSequential(int groupIndex, char *m_sName, int nameBufLen, int sentenceIndex, int reset) = 0;
virtual int SentenceIndexFromName(const char *pSentenceName) = 0;
virtual const char *SentenceNameFromIndex(int sentenceIndex) = 0;
virtual int SentenceGroupIndexFromName(const char *pGroupName) = 0;
virtual const char *SentenceGroupNameFromIndex(int groupIndex) = 0;
virtual float SentenceLength(int sentenceIndex) = 0;
virtual void ComputeLighting(const Vector &pt, const Vector *pNormal, bool bClamp, Vector &color, Vector *pBoxColors = NULL) = 0;
virtual void ActivateOccluder(int nOccluderIndex, bool bActive) = 0;
virtual bool IsOccluded(const Vector &vecAbsMins, const Vector &vecAbsMaxs) = 0;
virtual void *SaveAllocMemory(size_t num, size_t size) = 0;
virtual void SaveFreeMemory(void *pSaveMem) = 0;
virtual INetChannelInfo *GetNetChannelInfo(void) = 0;
virtual void DebugDrawPhysCollide(const CPhysCollide *pCollide, IMaterial *pMaterial, matrix3x4_t &transform, const Color_t &color) = 0;
virtual void CheckPoint(const char *pName) = 0;
virtual void DrawPortals() = 0;
virtual bool IsPlayingDemo(void) = 0;
virtual bool IsRecordingDemo(void) = 0;
virtual bool IsPlayingTimeDemo(void) = 0;
virtual int GetDemoRecordingTick(void) = 0;
virtual int GetDemoPlaybackTick(void) = 0;
virtual int GetDemoPlaybackStartTick(void) = 0;
virtual float GetDemoPlaybackTimeScale(void) = 0;
virtual int GetDemoPlaybackTotalTicks(void) = 0;
virtual bool IsPaused(void) = 0;
virtual bool IsTakingScreenshot(void) = 0;
virtual bool IsHLTV(void) = 0;
virtual bool IsLevelMainMenuBackground(void) = 0;
virtual void GetMainMenuBackgroundName(char *dest, int destlen) = 0;
virtual void GetVideoModes(int &nCount, vmode_s *&pModes) = 0;
virtual void SetOcclusionParameters(const OcclusionParams_t ¶ms) = 0;
virtual void GetUILanguage(char *dest, int destlen) = 0;
virtual SkyboxVisibility_t IsSkyboxVisibleFromPoint(const Vector &vecPoint) = 0;
virtual const char *GetMapEntitiesString() = 0;
virtual bool IsInEditMode(void) = 0;
virtual float GetScreenAspectRatio() = 0;
virtual bool REMOVED_SteamRefreshLogin(const char *password, bool isSecure) = 0;
virtual bool REMOVED_SteamProcessCall(bool &finished) = 0;
virtual unsigned int GetEngineBuildNumber() = 0;
virtual const char *GetProductVersionString() = 0;
virtual void GrabPreColorCorrectedFrame(int x, int y, int width, int height) = 0;
virtual bool IsHammerRunning() const = 0;
virtual void ExecuteClientCmd(const char *szCmdString) = 0;
virtual bool MapHasHDRLighting(void) = 0;
virtual int GetAppID() = 0;
virtual Vector GetLightForPointFast(const Vector &pos, bool bClamp) = 0;
virtual void ClientCmd_Unrestricted(const char *szCmdString) = 0;
virtual void SetRestrictServerCommands(bool bRestrict) = 0;
virtual void SetRestrictClientCommands(bool bRestrict) = 0;
virtual void SetOverlayBindProxy(int iOverlayID, void *pBindProxy) = 0;
virtual bool CopyFrameBufferToMaterial(const char *pMaterialName) = 0;
virtual void ChangeTeam(const char *pTeamName) = 0;
virtual void ReadConfiguration(const bool readDefault = false) = 0;
virtual void SetAchievementMgr(IAchievementMgr *pAchievementMgr) = 0;
virtual IAchievementMgr *GetAchievementMgr() = 0;
virtual bool MapLoadFailed(void) = 0;
virtual void SetMapLoadFailed(bool bState) = 0;
virtual bool IsLowViolence() = 0;
virtual const char *GetMostRecentSaveGame(void) = 0;
virtual void SetMostRecentSaveGame(const char *lpszFilename) = 0;
virtual void StartXboxExitingProcess() = 0;
virtual bool IsSaveInProgress() = 0;
virtual uint32_t OnStorageDeviceAttached(void) = 0;
virtual void OnStorageDeviceDetached(void) = 0;
virtual void ResetDemoInterpolation(void) = 0;
virtual void SetGamestatsData(CGamestatsData *pGamestatsData) = 0;
virtual CGamestatsData *GetGamestatsData() = 0;
//#if defined( USE_SDL )
virtual void GetMouseDelta(int &x, int &y, bool bIgnoreNextMouseDelta = false) = 0;
//#endif
virtual void ServerCmdKeyValues(KeyValues *pKeyValues) = 0;
virtual bool IsSkippingPlayback(void) = 0;
virtual bool IsLoadingDemo(void) = 0;
virtual bool IsPlayingDemoALocallyRecordedDemo() = 0;
virtual const char *Key_LookupBindingExact(const char *pBinding) = 0;
virtual void AddPhonemeFile(const char *pszPhonemeFile) = 0;
virtual float GetPausedExpireTime(void) = 0;
virtual bool StartDemoRecording(const char *pszFilename, const char *pszFolder = NULL) = 0;
virtual void StopDemoRecording(void) = 0;
virtual void TakeScreenshot(const char *pszFilename, const char *pszFolder = NULL) = 0;
};
namespace I { inline IVEngineClient013 *EngineClient; }
class IBaseClientDLL
{
public:
virtual int Init(CreateInterfaceFn appSystemFactory, CreateInterfaceFn physicsFactory, CGlobalVarsBase *pGlobals) = 0;
virtual void PostInit() = 0;
virtual void Shutdown(void) = 0;
virtual bool ReplayInit(CreateInterfaceFn replayFactory) = 0;
virtual bool ReplayPostInit() = 0;
virtual void LevelInitPreEntity(char const *pMapName) = 0;
virtual void LevelInitPostEntity() = 0;
virtual void LevelShutdown(void) = 0;
virtual ClientClass *GetAllClasses(void) = 0;
virtual int HudVidInit(void) = 0;
virtual void HudProcessInput(bool bActive) = 0;
virtual void HudUpdate(bool bActive) = 0;
virtual void HudReset(void) = 0;
virtual void HudText(const char *message) = 0;
virtual void IN_ActivateMouse(void) = 0;
virtual void IN_DeactivateMouse(void) = 0;
virtual void IN_Accumulate(void) = 0;
virtual void IN_ClearStates(void) = 0;
virtual bool IN_IsKeyDown(const char *m_sName, bool &isdown) = 0;
virtual void IN_OnMouseWheeled(int nDelta) = 0;
virtual int IN_KeyEvent(int eventcode, ButtonCode_t keynum, const char *pszCurrentBinding) = 0;
virtual void CreateMove(int sequence_number, float input_sample_frametime, bool active) = 0;
virtual void ExtraMouseSample(float frametime, bool active) = 0;
virtual bool WriteUsercmdDeltaToBuffer(bf_write *buf, int from, int to, bool isnewcommand) = 0;
virtual void EncodeUserCmdToBuffer(bf_write &buf, int slot) = 0;
virtual void DecodeUserCmdFromBuffer(bf_read &buf, int slot) = 0;
virtual void View_Render(vrect_t *rect) = 0;
virtual void RenderView(const CViewSetup &view, int nClearFlags, int whatToDraw) = 0;
virtual void View_Fade(ScreenFade_t *pSF) = 0;
virtual void SetCrosshairAngle(const QAngle &angle) = 0;
virtual void InitSprite(CEngineSprite *pSprite, const char *loadname) = 0;
virtual void ShutdownSprite(CEngineSprite *pSprite) = 0;
virtual int GetSpriteSize(void) const = 0;
virtual void VoiceStatus(int entindex, bool bTalking) = 0;
virtual void InstallStringTableCallback(char const *tableName) = 0;
virtual void FrameStageNotify(ClientFrameStage_t curStage) = 0;
virtual bool DispatchUserMessage(int msg_type, bf_read &msg_data) = 0;
virtual CSaveRestoreData *SaveInit(int size) = 0;
virtual void SaveWriteFields(CSaveRestoreData *, const char *, void *, datamap_t *, typedescription_t *, int) = 0;
virtual void SaveReadFields(CSaveRestoreData *, const char *, void *, datamap_t *, typedescription_t *, int) = 0;
virtual void PreSave(CSaveRestoreData *) = 0;
virtual void Save(CSaveRestoreData *) = 0;
virtual void WriteSaveHeaders(CSaveRestoreData *) = 0;
virtual void ReadRestoreHeaders(CSaveRestoreData *) = 0;
virtual void Restore(CSaveRestoreData *, bool) = 0;
virtual void DispatchOnRestore() = 0;
virtual CStandardRecvProxies *GetStandardRecvProxies() = 0;
virtual void WriteSaveGameScreenshot(const char *pFilename) = 0;
virtual void EmitSentenceCloseCaption(char const *tokenstream) = 0;
virtual void EmitCloseCaption(char const *captionname, float duration) = 0;
virtual bool CanRecordDemo(char *errorMsg, int length) const = 0;
virtual void OnDemoRecordStart(char const *pDemoBaseName) = 0;
virtual void OnDemoRecordStop() = 0;
virtual void OnDemoPlaybackStart(char const *pDemoBaseName) = 0;
virtual void OnDemoPlaybackStop() = 0;
virtual bool ShouldDrawDropdownConsole() = 0;
virtual int GetScreenWidth() = 0;
virtual int GetScreenHeight() = 0;
virtual void WriteSaveGameScreenshotOfSize(const char *pFilename, int width, int height, bool bCreatePowerOf2Padded = false, bool bWriteVTF = false) = 0;
virtual bool GetPlayerView(CViewSetup &playerView) = 0;
virtual void SetupGameProperties(CUtlVector< XUSER_CONTEXT > &contexts, CUtlVector< XUSER_PROPERTY > &properties) = 0;
virtual uint32_t GetPresenceID(const char *pIDName) = 0;
virtual const char *GetPropertyIdString(const uint32_t id) = 0;
virtual void GetPropertyDisplayString(uint32_t id, uint32_t value, char *pOutput, int nBytes) = 0;
virtual void StartStatsReporting(HANDLE handle, bool bArbitrated) = 0;
virtual void InvalidateMdlCache() = 0;
virtual void IN_SetSampleTime(float frametime) = 0;
virtual void ReloadFilesInList(IFileList *pFilesToReload) = 0;
virtual bool HandleUiToggle() = 0;
virtual bool ShouldAllowConsole() = 0;
virtual CRenamedRecvTableInfo *GetRenamedRecvTableInfos() = 0;
virtual CMouthInfo *GetClientUIMouthInfo() = 0;
virtual void FileReceived(const char *fileName, unsigned int transferID) = 0;
virtual const char *TranslateEffectForVisionFilter(const char *pchEffectType, const char *pchEffectName) = 0;
virtual void ClientAdjustStartSoundParams(struct StartSoundParams_t ¶ms) = 0;
virtual bool DisconnectAttempt(void) = 0;
virtual bool IsConnectedUserInfoChangeAllowed(IConVar *pCvar) = 0;
};
namespace I { inline IBaseClientDLL *BaseClientDLL; }
|
// Copyright 2017 Elias Kosunen
//
// 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
//
// https://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.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
#if defined(SCN_HEADER_ONLY) && SCN_HEADER_ONLY
#define SCN_VSCAN_CPP
#endif
#include <scn/scan/vscan.h>
#include <scn/detail/context.h>
#include <scn/detail/parse_context.h>
#include <scn/detail/visitor.h>
namespace scn {
SCN_BEGIN_NAMESPACE
#if SCN_INCLUDE_SOURCE_DEFINITIONS
#define SCN_VSCAN_DEFINE(Range, WrappedAlias, CharAlias) \
vscan_result<detail::vscan_macro::WrappedAlias> vscan( \
detail::vscan_macro::WrappedAlias&& range, \
basic_string_view<detail::vscan_macro::CharAlias> fmt, \
basic_args<detail::vscan_macro::CharAlias>&& args) \
{ \
return detail::vscan_boilerplate(SCN_MOVE(range), fmt, \
SCN_MOVE(args)); \
} \
\
vscan_result<detail::vscan_macro::WrappedAlias> vscan_default( \
detail::vscan_macro::WrappedAlias&& range, int n_args, \
basic_args<detail::vscan_macro::CharAlias>&& args) \
{ \
return detail::vscan_boilerplate_default(SCN_MOVE(range), n_args, \
SCN_MOVE(args)); \
} \
\
vscan_result<detail::vscan_macro::WrappedAlias> vscan_localized( \
detail::vscan_macro::WrappedAlias&& range, \
basic_locale_ref<detail::vscan_macro::CharAlias>&& loc, \
basic_string_view<detail::vscan_macro::CharAlias> fmt, \
basic_args<detail::vscan_macro::CharAlias>&& args) \
{ \
return detail::vscan_boilerplate_localized( \
SCN_MOVE(range), SCN_MOVE(loc), fmt, SCN_MOVE(args)); \
} \
\
error vscan_usertype( \
basic_context<detail::vscan_macro::WrappedAlias>& ctx, \
basic_string_view<detail::vscan_macro::CharAlias> f, \
basic_args<detail::vscan_macro::CharAlias>&& args) \
{ \
auto pctx = make_parse_context(f, ctx.locale()); \
return visit(ctx, pctx, SCN_MOVE(args)); \
}
SCN_VSCAN_DEFINE(string_view, string_view_wrapped, string_view_char)
SCN_VSCAN_DEFINE(wstring_view, wstring_view_wrapped, wstring_view_char)
SCN_VSCAN_DEFINE(std::string, string_wrapped, string_char)
SCN_VSCAN_DEFINE(std::wstring, wstring_wrapped, wstring_char)
SCN_VSCAN_DEFINE(file&, file_ref_wrapped, file_ref_char)
SCN_VSCAN_DEFINE(wfile&, wfile_ref_wrapped, wfile_ref_char)
#endif
SCN_END_NAMESPACE
} // namespace scn
|
#include "mythreadpool.h"
MyThreadPool::MyThreadPool()
{
}
void MyThreadPool::pthread_pool_create(int max,int min,int queue_max)
{
this->thread_shutdown = true;
this->thread_max = max;
this->thread_min = min;
this->thread_busy = 0;
this->thread_alive = 0;
this->thread_exitcode = 0;
this->queue_max = queue_max;
this->queue_size = 0;
this->queue_front = 0;
this->queue_rear = 0;
if(pthread_mutex_init(&this->lock,NULL)||pthread_cond_init(&this->con_customer,NULL) || pthread_cond_init(&this->con_productor,NULL))
{
perror("pthread_pool_create init error\n");
return ;
}
if((this->tids = (pthread_t*)malloc(sizeof(pthread_t) * max)) == NULL)
{
perror("pthread_pool_create malloc tids error\n");
return ;
}
bzero(this->tids,sizeof(pthread_t) * max);
if((this->queue_task = (ITask**)malloc(sizeof(ITask*)*queue_max)) == NULL)
{
perror("pthread_pool_create malloc queue_task error\n");
return ;
}
for(int i = 0;i<min;i++)
{
pthread_create(&this->tids[i],NULL,pthread_pool_customer,this);
this->thread_alive++;
}
pthread_create(&this->managerid,NULL,pthread_pool_manager,this);
}
void MyThreadPool::pthread_pool_destroy()
{
pthread_mutex_destroy(&this->lock);
pthread_cond_destroy(&this->con_customer);
pthread_cond_destroy(&this->con_productor);
free(this->tids);
free(this->queue_task);
}
void MyThreadPool::pthread_pool_addtask(ITask* task)
{
if(this->thread_shutdown)
{
pthread_mutex_lock(&this->lock);
while(this->queue_size == this->queue_max)
{
pthread_cond_wait(&this->con_productor,&this->lock);
if(!this->thread_shutdown)
{
pthread_mutex_unlock(&this->lock);
return ;
}
}
this->queue_task[this->queue_front]=task;
this->queue_front = (this->queue_front + 1)%this->queue_max;
this->queue_size++;
pthread_cond_signal(&this->con_customer);
pthread_mutex_unlock(&this->lock);
}
}
void* MyThreadPool::pthread_pool_customer(void* arg)
{
pthread_detach(pthread_self());
MyThreadPool* pool = (MyThreadPool*)arg;
ITask* task;
while(pool->thread_shutdown)
{
pthread_mutex_lock(&pool->lock);
while(pool->queue_size == 0)
{
pthread_cond_wait(&pool->con_customer,&pool->lock);
if(!pool->thread_shutdown || pool->thread_exitcode > 0)
{
pool->thread_alive--;
pool->thread_exitcode--;
pthread_mutex_unlock(&pool->lock);
pthread_exit(0);
}
}
task = pool->queue_task[pool->queue_rear];
pool->queue_rear = (pool->queue_rear+1)%pool->queue_max;
pool->queue_size--;
pool->thread_busy++;
pthread_mutex_unlock(&pool->lock);
task->TaskJob();
delete task;
pthread_mutex_lock(&pool->lock);
pool->thread_busy--;
pthread_mutex_unlock(&pool->lock);
}
return 0;
}
void* MyThreadPool::pthread_pool_manager(void* arg)
{
pthread_detach(pthread_self());
MyThreadPool* pool = (MyThreadPool*)arg;
int alive;
int busy;
int size;
while(pool->thread_shutdown)
{
pthread_mutex_lock(&pool->lock);
alive = pool->thread_alive;
size = pool->queue_size;
busy = pool->thread_busy;
pthread_mutex_unlock(&pool->lock);
if((size > alive - busy || busy / (float)alive *100 >= 80) && alive + pool->thread_min <= pool->thread_max)
{
printf("hahahahha");
for(int i = 0;i<pool->thread_min;i++)
{
for(int j = 0;j<pool->thread_max;j++)
{
if(pool->tids[j] == 0 || !pthread_pool_alive(pool->tids[j]))
{
pthread_mutex_lock(&pool->lock);
pthread_create(&pool->tids[j],NULL,pthread_pool_customer,pool);
pool->thread_alive++;
pthread_mutex_unlock(&pool->lock);
break;
}
}
}
}
if(busy*2 < alive - size && alive - pool->thread_min >= pool->thread_min)
{
pthread_mutex_lock(&pool->lock);
pool->thread_exitcode = pool->thread_min;
pthread_mutex_unlock(&pool->lock);
for(int i = 0;i<pool->thread_min;i++)
{
pthread_cond_signal(&pool->con_customer);
}
}
printf("manager running alive[%d] busy[%d] size[%d]\n",alive,busy,size);
sleep(1);
}
pthread_exit(0);
}
bool MyThreadPool::pthread_pool_alive(pthread_t tid)
{
pthread_kill(tid,0);
if(errno == ESRCH)
return false;
return true;
}
|
/***************************************************************************
* Sketch Name: Lighting Control System
* Description: This sketch illustrates how an Arduino Yun can be controlled
remotely by subscribing to an MQTT broker
* Created On: March 01, 2016
* Author: Adeel Javed
* Book: Building Arduino Projects for the Internet of Things
* Chapter: Chapter 06 - IoT Patterns: Remote Control
* Website: http://codifythings.com
**************************************************************************/
/***************************************************************************
* External Libraries
**************************************************************************/
#include <Process.h>
#include <YunClient.h>
#include <PubSubClient.h>
/***************************************************************************
* Internet Connectivity Setup - Variables & Functions
**************************************************************************/
// Yun client already connected to the internet
YunClient client;
void printConnectionInformation()
{
// Initialize a new process
Process wifiCheck;
// Run Command
wifiCheck.runShellCommand("/usr/bin/pretty-wifi-info.lua");
// Print Connection Information
while (wifiCheck.available() > 0)
{
char c = wifiCheck.read();
Serial.print(c);
}
Serial.println("-----------------------------------------------");
Serial.println("");
}
/***************************************************************************
* Data Subscribe - Variables & Functions
**************************************************************************/
// IP address of the MQTT broker
char server[] = {"iot.eclipse.org"};
int port = 1883;
char topic[] = {"codifythings/lightcontrol"};
PubSubClient pubSubClient(server, port, callback, client);
void callback(char* topic, byte* payload, unsigned int length)
{
// Print payload
String payloadContent = String((char *)payload);
Serial.println("[INFO] Payload: " + payloadContent);
// Turn lights on/off
turnLightsOnOff();
}
/***************************************************************************
* Controller - Variables & Functions
**************************************************************************/
int ledPin = 3;
void turnLightsOnOff()
{
// Check if lights are currently on or off
if(digitalRead(ledPin) == LOW)
{
//Turn lights on
Serial.println("[INFO] Turning lights on");
digitalWrite(ledPin, HIGH);
}
else
{
// Turn lights off
Serial.println("[INFO] Turning lights off");
digitalWrite(ledPin, LOW);
}
}
/***************************************************************************
* Standard Arduino Functions - setup(), loop()
**************************************************************************/
void setup()
{
// Initialize serial port
Serial.begin(9600);
// Do nothing until serial monitor is opened
while (!Serial);
// Contact the Linux processor
Bridge.begin();
// Print connection information
printConnectionInformation();
// Set LED pin mode
pinMode(ledPin, OUTPUT);
//Connect MQTT Broker
Serial.println("[INFO] Connecting to MQTT Broker");
if (pubSubClient.connect("arduinoClient"))
{
Serial.println("[INFO] Connection to MQTT Broker Successfull");
pubSubClient.subscribe(topic);
Serial.println("[INFO] Successfully Subscribed to MQTT Topic ");
}
else
{
Serial.println("[INFO] Connection to MQTT Broker Failed");
}
}
void loop()
{
// Wait for messages from MQTT broker
pubSubClient.loop();
}
|
#include <iostream>
#include <vector>
#include <complex>
#include <cmath>
#include <random>
#include <cassert>
using std::vector;
using std::complex;
using std::cout;
using std::endl;
typedef complex<double> Complex;
typedef vector<double> DArray;
typedef vector<Complex> ComArray;
typedef vector<ComArray> ComImg, ComArrayTwoDim;
const double PI = 3.1415926535898;
long long int count0 = 0;
inline void swap(Complex& a, Complex& b);
void transpose(ComArrayTwoDim& array_two_dim);
void picture_FFT(ComImg& fft_out, const ComImg& picture);
ComArray FFT(const ComArray& a);
void testFFT();
void initialArrayTwoDim(ComArrayTwoDim& array_two_dim, const int N, bool initialValue);
void swapMatrix(ComArrayTwoDim& a)
{
const int N = a.size();
int m = N / 2;
int n = N / 2;
for (int i = 0; i < N / 2; i++, m++)
{
for (int j = 0; j < N / 2; j++, n++)
{
swap(a[i][j], a[m][n]);
}
n = 0;
for (int j = N / 2; j < N; j++, n++)
{
swap(a[i][j], a[m][n]);
}
}
}
void print(const ComArrayTwoDim& array_two_dim)
{
const int N = array_two_dim.size();
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
cout << array_two_dim[i][j] << " \t";
cout << endl;
}
}
inline void swap(Complex& a, Complex& b)
{
Complex temp = b;
b = a;
a = temp;
}
//resize array with two dimension
void initialArrayTwoDim(ComArrayTwoDim& array_two_dim, const int N, bool initialValue = false)
{
array_two_dim.resize(N);
for (int i = 0; i < N; i++)
{
array_two_dim[i].resize(N);
if (true == initialValue)
for (int j = 0; j < N; j++)
array_two_dim[i][j] = rand()%10;
}
}
//only for n is a power of 2
void transpose(ComArrayTwoDim& array_two_dim)
{
assert(array_two_dim.size() == array_two_dim[0].size());
const int n = array_two_dim.size();
for (int i = 0; i < n; i++, count0++)
for (int j = i + 1; j < n; j++, count0++)
swap(array_two_dim[i][j], array_two_dim[j][i]);
}
void picture_FFT(ComImg& fft_out, const ComImg& picture)
{
assert(picture.size() == picture[0].size());
const int n = picture.size();
for (int i = 0; i < n; i++, count0++)//row fft
{
fft_out[i] = FFT(picture[i]);
}
transpose(fft_out);
static ComArray temp(n);
for (int i = 0; i < n; i++, count0++)//row fft
{
fft_out[i] = FFT(fft_out[i]);
}
transpose(fft_out);
}
ComArray FFT(const ComArray& a)
{
int n = a.size();
if (1 == n) //base case
return a;
assert(n % 2 == 0);
Complex Wn(cos(2 * PI / n), -sin(2 * PI / n));
Complex W0(1, 0);
ComArray a0(n / 2), a1(n / 2);
for (int i = 0; i < n / 2; i++, count0++)
a0[i] = a[2 * i];
for (int i = 0; i < n / 2; i++, count0++)
a1[i] = a[2 * i + 1];
ComArray y0 = FFT(a0);
ComArray y1 = FFT(a1);
ComArray y(n);
for (int k = 0; k < n / 2; k++, count0++)
{
y[k] = y0[k] + W0*y1[k];
y[k + n / 2] = y0[k] - W0*y1[k];
W0 *= Wn;
}
return y;
}
void testFFT()
{
const int N = 4;
ComImg testData;
initialArrayTwoDim(testData, N, true);
print(testData);
cout << endl;
swapMatrix(testData);
print(testData);
//print(testData);
//ComImg FFTData;
//initialArrayTwoDim(FFTData, N, false);
//picture_FFT(FFTData, testData);
//cout << "total running times is " << count0 << endl;
//cout << endl;
//getchar(); getchar();
//print(FFTData);
}
int main()
{
testFFT();
return 0;
}
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>
using namespace std;
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
//基本思想:字典排序(二进制排序)子集,以字典序的顺序获得全部组合,第一个序为000,最后一个序为111,对应nums元素,vec[i]=1则将nums[i]加入cur
vector<vector<int>> res;
vector<int> cur;
vector<int> vec(nums.size(), 0);
int i, carry = 1;
do
{
for (i = 0; i < nums.size(); i++)
{
if (vec[i] == 1)
cur.push_back(nums[i]);
}
res.push_back(cur);
cur.clear();
for (i = 0; i < nums.size(); i++)
{
if (vec[i] + carry == 2)
{
vec[i] = 0;
carry = 1;
}
else
{
vec[i] = 1;
break;
}
}
} while (vec != vector<int>(nums.size(), 0));
return res;
}
};
class Solution1 {
public:
vector<vector<int>> res;
vector<vector<int>> subsets(vector<int>& nums) {
//基本思想:递归回溯法
vector<int> cur;
Recursion(nums, 0, cur);
return res;
}
void Recursion(vector<int>& nums, int pos, vector<int> cur)
{
res.push_back(cur);
for (int i = pos; i < nums.size(); i++)
{
cur.push_back(nums[i]);
Recursion(nums, i + 1, cur);
cur.pop_back();
}
return;
}
};
int main()
{
Solution1 solute;
vector<int> nums = { 1,2,3 };
vector<vector<int>> res = solute.subsets(nums);
for (int i = 0; i < res.size(); i++)
{
copy(res[i].begin(), res[i].end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
return 0;
}
|
#ifndef _PlayerManager_H_
#define _PlayerManager_H_
#include "CDL_Timer_Handler.h"
#include "RobotUtil.h"
#include "Player.h"
#include "Util.h"
#include <map>
struct RobotID
{
int uid;
bool hasused;
};
class PlayerManager
{
typedef std::map<int, Player*> MapPlayer;
Singleton(PlayerManager);
public:
static int productRobot(int tid, short status, short level, short countUser);
int addPlayer(int uid, Player* player);
void delPlayer(int uid, bool iscolsed = false);
Player* getPlayer(int uid);
int getRobotUID();
int delRobotUid(int robotuid);
int getPlayerSize();
private:
MapPlayer m_playerMap;
RobotID m_idpool[MAX_ROBOT_NUMBER];
};
#endif
|
#include<bits/stdc++.h>
#define rep(i,n) for (int i =0; i <(n); i++)
using namespace std;
using ll = long long;
int main(){
int N , K;
cin >> N >> K;
vector<vector<int>>T(N,vector<int>(N));
rep(i,N){
rep(j,N){
cin >> T[i][j];
}
}
//ここまで入力おわり
vector<int>index;
rep(i,N){
index.push_back(i);
}
int ans = 0;
do{
int time = 0;
rep(i,N){
time += T[index[i]][index[(i+1)%N]];
if(time == K)ans++;
}
}while(next_permutation(index.begin()+1,index.end()));
cout << ans << endl;
return 0;
}
|
#pragma once
#include <queue>
#include <mutex>
#include <utility> // move 사용
using namespace std;
template<typename T>
class LockQueue
{
public:
LockQueue() { }
LockQueue(const LockQueue&) = delete;
LockQueue& operator=(const LockQueue&) = delete;
void Push(T value)
{
lock_guard<mutex> lock(_mutex);
_queue.push(std::move(value));
_conVar.notify_one();
}
// 출력매개변수를 받아서 이동대입으로 pop의 결과값을 받아가도록한다.
bool TryPop(T& value)
{
lock_guard<mutex> lock(_mutex);
if (_queue.empty())
return false;
value = std::move(_queue.front());
_queue.pop();
return true;
}
// 출력매개변수를 받아서 이동대입으로 pop의 결과값을 받아가도록한다.
void WaitPop(T& value)
{
// 스레드가 큐의 뮤텍스 소유권이 없으면 역시 코드는 실행이 안 됩니다.
unique_lock<mutex> lock(_mutex);
// 뮤텍스 소유권이 있더라도 조건을 만족하지 못하면
// 만족할 때 까지 lock을 유지하면서 wait 합니다.
_conVar.wait(lock, [this] {return _queue.empty() == false; });
value = std::move(_queue.front()); // pop한 값을 이동대입으로 전달한다.
_queue.pop();
}
private:
queue<T> _queue;
// 현재 스레드가 이mutex객체의 소유자가 아니면 이mutex로 잠군
// 네이임 규칙 : 멀티스레딩용 변수는 앞에 _만 붙임.
// 크티컬 섹션에 접근할 수 없다.
// lock하는 방법이 여러가지 있는데 lock_quard(c++11 이후)도 그중에 하나.
mutex _mutex;
// 바인드해둔 함수가 참을 반환하는 시점까지 기다리는 _conVar.wait를 위해서 필요함.
condition_variable _conVar;
};
|
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
bool ans = false;
cin >> n;
int div_2 = 0, div_4 = 0, others = 0;
for(int i=0; i<n; i++){
int a;
cin >> a;
if(a%4 == 0) div_4++;
else if(a%2 == 0) div_2++;
else others++;
}
if(others == 0) ans = true;
else if(div_4 >= others) ans = true;
//div_4+1 == others + (div_2 == 1) としたところ最後のケースで通らなかった
else if(div_4+1 == others && div_2 == 0) ans = true;
if(ans) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
|
//Name: Dan Haub
//Student ID#: 2315346
//Chapman Email: haub@chapman.edu
//Course Number and Section: CPSC 350-01
//Assignment: 4 - Registrar Simulation
#ifndef WINDOW_H
#define WINDOW_H
#include "GenDoubleLinkedList.h"
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
class Window{
public:
//Default constructor
Window();
//Default destructor
~Window();
//Sets helping to true
void startHelping(Student* s);
//Sets helping to false and begins a new wait time
void stopHelping();
//Returns if the window is currently helping
bool isHelping();
//adds to current wait time if not helping
void step();
//Returns wait times
GenDoublyLinkedList<int>* getWaitTimes();
//string toWindowString();
private:
//Stores if the window is currently helping
bool helping;
//Stores student being helped
Student *studentBeingHelped;
//Stores time remaining for current student
int helpTimeRemaining;
//Stores wait times
GenDoublyLinkedList<int> *idleTimes;
};
#endif //WINDOW_H
|
#pragma once
#include <iostream>
#include "Employee.h"
using namespace std;
class FullTimeEmployee : public Employee
{
private:
double weekSalary;
public:
// Default Constructor
FullTimeEmployee() : Employee() {
weekSalary = 0.0;
}
// Constructor
FullTimeEmployee(int a, string b, string c, double d) : Employee(a, b, c) {
weekSalary = d;
}
// Set function
void setWeekSalary(double a) {
weekSalary = a;
}
// Get function
double getWeekSalary() const {
return weekSalary;
}
// Virtual calculation function
virtual double calculatePay() const;
// Virtual print function
virtual void print() const;
~FullTimeEmployee();
};
|
#include<stdio.h>
#include<math.h>
#include <stdlib.h>
#include<iostream>
#define MAXSIZE 10000
#define STACKINCREMENT 2000
typedef struct {
int stacksize;
int *top, *base;
}SqStack;
typedef struct {
int stacksize;
long long int *top, *base;
}SqStackL;
void InitStack(SqStack &S) {
S.base = (int*)malloc(MAXSIZE * sizeof(int));
if (!S.base) {
return;
}
S.stacksize = MAXSIZE;
S.top = S.base;
}
void InitStackL(SqStackL &S) {
S.base = (long long int*)malloc(MAXSIZE * sizeof(long long int));
if (!S.base) {
return;
}
S.stacksize = MAXSIZE;
S.top = S.base;
}
int StackEmpty(SqStack S) {
if (S.top == S.base)
return 1;
else
return 0;
}
int StackEmptyL(SqStackL S) {
if (S.base == S.top)
return 1;
else
return 0;
}
void Push(SqStack &S, int x) {
if ((S.top - S.base) >= S.stacksize) {
S.base = (int*)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(int));
if (!S.base)return;
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = x;
}
int PushL(SqStackL &S, long long int x) {
if ((S.top - S.base) >= S.stacksize) {
S.base = (long long int*)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(long long int));
if (!S.base)return -1;
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = x;
return 0;
}
int Pop(SqStack&S, int & x) {
if (S.top == S.base)return 0;
S.top--;
x = *S.top;
return 1;
}
int PopL(SqStackL &S, long long int &x) {
if (S.top == S.base)return 0;
S.top--;
x = *S.top;
return 1;
}
void GetTop(SqStack S, int &e) {
if (S.top == S.base) {
return;
}
e = *(S.top - 1);
}
int isoperator(char c) {
if (c == '(' || c == ')' || c == '+' || c == '-' || c == '*' || c == '^' || c == '\0') {
return 1;
}
else return 0;
}
int preop(char c, char ch)
{
int p[8][8] = { { 1,1,-1,-1,-1,-1,1,1 },{ 1,1,-1,-1,-1,-1,1,1 },{ 1,1,1,1,-1,-1,1,1 },{ 1,1,1,1,-1,-1,1,1 },{ 1,1,1,1,1,-1,1,1 },{ -1,-1,-1,-1,-1,-1,0,0 },
{ 1,1,1,1,1,0,1,1 },{ -1,-1,-1,-1,-1,-1,0,0 } };
int i, j;
switch (c) {
case'+': i = 0; break;
case'-': i = 1; break;
case'*': i = 2; break;
case'/': i = 3; break;
case'^': i = 4; break;
case'(': i = 5; break;
case')': i = 6; break;
case'\0': i = 7; break;
}
switch (ch) {
case'+': j = 0; break;
case'-': j = 1; break;
case'*': j = 2; break;
case'/': j = 3; break;
case'^': j = 4; break;
case'(': j = 5; break;
case')': j = 6; break;
case'\0': j = 7; break;
}
return p[i][j];
}
int isleft(char c) {
if (c == '(' || c == '[' || c == '{') {
return 1;
}
else return 0;
}
int isright(char c) {
if (c == ')' || c == ']' || c == '}') {
return 1;
}
return 0;
}
int ismatch(char c, char ch) {
if (c == '('&&ch == ')')
return 1;
if (c == '['&&c == ']')
return 1;
if (c == '{'&&c == '}')
return 1;
return 0;
}
int istrue(char exp[]) {
char *p = exp;
int c, ch;
SqStack S;
InitStack(S);
while ((c = *p) != '\0') {
if (isleft(c)) {
Push(S, c);
}
else if (isright(c)) {
if (!Pop(S, ch)) {
return -1;
}
if (!ismatch(ch, c)) {
return -2;
}
}
p++;
}
if (!StackEmpty(S))
return -3;
else
return 1;
}
long long int operatorl(long long int a, char c, long long int b) {
long long int i, t;
t = 1;
switch (c) {
case'+':
return(a + b);
break;
case'-':
return(a - b);
break;
case'*':
return(a*(b));
break;
case'^':
for (i = b; b > 0; b--) {
t = t * a;
}
return t;
break;
}
return 0;
}
void conver(char exp[], char suffix[]) {
SqStack S;
InitStack(S);
Push(S, '\0');
int k = 0, ch, a, b, c;
char *p;
p = exp;
ch = *p++;
while (!(ch == '\0' && b == '\0')) {
if (ch == ' ') {
ch = *p++;
continue;
}
if (!isoperator(ch)) {
suffix[k++] = ch;
ch = *p++;
if (isoperator(ch) || ch == ' ') {
suffix[k++] = ' ';
}
GetTop(S, b);
}
else {
GetTop(S, c);
switch (preop(c, ch)) {
case -1:
Push(S, ch);
ch = *p++;
GetTop(S, b);
break;
case 0:
Pop(S, a);
ch = *p++;
GetTop(S, b);
break;
case 1:
Pop(S, c);
suffix[k++] = (char)c;
GetTop(S, b);
break;
}
}
}
suffix[k++] = '\0';
}
long long int Value(char exp[], long long int y) {
long long int a, b, e, sum, temp;
SqStackL S;
char *p = exp, ch;
InitStackL(S);
while ((ch = *p) != '\0') {
if (!isoperator(ch)) {
temp = 0;
while (ch != ' ' && !(isoperator(ch))) {
if (ch == 'x') {
temp = temp * 10 + (y);
ch = *(++p);
}
else {
temp = temp * 10 + (ch - '0');
ch = *(++p);
}
}
PushL(S, temp);
p++;
}
else {
PopL(S, b);
PopL(S, a);
PushL(S, operatorl(a, ch, b));
p++;
}
ch = *p;
}
PopL(S, sum);
return sum;
}
int isequal(char exp[], char c[]) {
long long int a[10] = { 0,1,13,30,-2 }, i;
char ta[10000], tb[10000];
conver(exp, ta);
conver(c, tb);
for (i = 0; i <= 5; i = i++) {
if (Value(ta, a[i]) != Value(tb, a[i]))
return 0;
}
return 1;
}
int main() {
using namespace std;
char c[27][400];
int n, i;
cin >> n; getchar();
gets(c[0]);
for (i = 1; i <= n; i++) {
gets(c[i]);
}
for (i = 1; i <= n; i++) {
if ((istrue(c[i])) != 1) {
c[i][0] = '\0';
}
}
for (i = 1; i <= n; i++) {
if (c[i][0] == '\0') {
continue;
}
if (isequal(c[0], c[i])) {
printf("%c", 'A' + i - 1);
}
}
return 0;
}
|
#pragma once
#include "../CHARINFO.h"
namespace NETWORKMODEL {
namespace IOCP {
namespace DETAIL {
struct CONNECTION;
}
}
}
namespace PACKET {
namespace CHARINFO {
void PacketProcessor(FUNCTIONS::CIRCULARQUEUE::QUEUEDATA::CPacketQueueData* const Data);
void ProcessNewCharacter(const NETWORKMODEL::IOCP::DETAIL::CONNECTION* const Owner, const CCHARINFO& Data);
void ProcessGetList(const NETWORKMODEL::IOCP::DETAIL::CONNECTION* const Owner, const CCHARINFO& Data);
}
}
|
#include <vector>
#include <iostream>
#include <time.h>
#include <opencv2\opencv.hpp>
using namespace std;
using namespace cv;
#ifndef __QUAD__
#define __QUAD__
//用于表示网格的四个角的坐标
class Quad
{
public:
Point2f V00;//左上角
Point2f V01;//左下角
Point2f V10;//右上角
Point2f V11;//右下角
Quad();
Quad(const Quad &inQuad);//复制构造函数
Quad(Point2f &inV00, const Point2f &inV01, const Point2f &inV10, const Point2f &inV11);//fz构造函数
~Quad();
//重载
void operator=(const Quad &inQuad);
//
double getMinX() const;
double getMaxX() const;
double getMinY() const;
double getMaxY() const;
bool isPointIn(const Point2f &pt) const;
bool getBilinearCoordinates(const Point2f &pt, vector<double> &coefficient) const;
bool getBilinearCoordinates(const Point2f &pt, double* &coefficient) const;
inline void printfQuad()
{
printf("V00=%f %f\n", V00.x, V00.y);
printf("V01=%f %f\n", V01.x, V01.y);
printf("V10=%f %f\n", V10.x, V10.y);
printf("V11=%f %f\n", V11.x, V11.y);
}
Point2f getPointByBilinearCoordinates(const vector<double> &coefficient) const;
};
#endif
#ifndef __MESH__
#define __MESH__
class Mesh
{
public:
Mesh();
Mesh(const Mesh &inMesh);//复制构造函数
Mesh(int rows, int cols);
Mesh(int rows, int cols, double quadWidth, double quadHeight);
~Mesh();
int imgRows; //视频帧的高度
int imgCols;//视频帧的宽度
int width;
int height;
int quadWidth;
int quadHeight;
void operator=(const Mesh &inMesh);
double differemtFrom(const Mesh &inMesh) const;
//网格中的某一个点
Point2f getVertex(int i, int j)const;
void setVertex(int i, int j, const Point2f &pos);
void initialize(int w, int h);
void buildMesh(double quadWidth, double quadHeight);
void drawMesh(Mat &targetImg);
bool selfCheck();
void smoothMesh();
void HomographyTransformation(const Mat &H);
Quad getQuad(int i, int j) const;
Mat getXMat();
Mat getYMat();
private:
Mat xMat;
Mat yMat;
};
#endif
bool isPointInTriangular(const Point2f &pt, const Point2f &V0, const Point2f &V1, const Point2f &v2);
void meshWarp(const Mat src, Mat dst, Mesh &m1, const Mesh &m2);
void quadWarp(const Mat src, Mat dst, const Quad &q1, const Quad &q2);
void meshWarp_multicore(const Mat src, Mat dst, const Mesh &m1, const Mesh &m2);
void meshWarpRemap(Mat &src, Mat &dst, Mat &mapX, Mat &mapY, Mesh &m1, Mesh &m2);
void myQuickSort(vector<float> &arr, int left, int right);
|
#include <iostream>
using namespace std;
int nums[13];
int matrix[13];
int n;
void combination(int matrix[], int tn, int tr, int index, int tcount){
if(tr <= index){
//end
for(int i = 0; i < tr; i++){
cout << nums[matrix[i]] << " ";
}
cout << '\n';
return;
}
if(tcount >= tn){
return;
}
matrix[index] = tcount;
//cout << "index : " << index << " / tcount : " << tcount << " .. saved!" << '\n';
combination(matrix, tn, tr, index+1, tcount+1);
combination(matrix, tn, tr, index, tcount+1);
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
while(true){
cin >> n;
if(n == 0){
break;
}
for(int i = 0; i < n; i++){
cin >> nums[i];
}
combination(matrix, n, 6, 0, 0);
cout << '\n';
}
return 0;
}
|
#include "library.h"
int FCILibraryBooks::getMaxInt(vector<int>& v)
{
return *max_element(v.begin(), v.end());
}
void FCILibraryBooks::printMenu()
{
cout<<"0 - Exit."<<endl;
cout<<"1 - Add Book."<<endl;
cout<<"2 - Search by name."<<endl;
cout<<"3 - Search by author."<<endl;
cout<<"4 - List books in alphabetical order (Ascending)"<<endl;
cout<<"5 - Update available number of versions of a book (user enters book name and the new number)"<<endl;
cout<<"6 - Find the books which have the highest number of versions and print books information."<<endl;
cout << ">> ";
}
void FCILibraryBooks::AddBook()
{
FCILibraryBooks b;
fstream book;
book.open("Library.txt", ios::app);
cin.ignore();
cout<<"Enter Author name : ";
cin.getline(b.AuthorName,50);
cout<<"Enter The name of the book : ";
cin.getline(b.Name,50);
cout<<"Enter Publish Year : ";
cin.getline(b.Publishyear,5);
cout<<"Enter Number of versions : ";
cin>>b.NumOfversions;
book<<b.AuthorName<<'|'<<b.Name<<'|'<<b.Publishyear<<'|'<<b.NumOfversions;
cout<< "done !\n";
book.close();
}
void FCILibraryBooks::SearchByName()
{
fstream book;
FCILibraryBooks b;
book.open("Library.txt",ios::in);
cin.ignore();
char NameToSearh[50];
cout<<"Enter the Book's Name to search about it : ";
cin.getline(NameToSearh,50);
int x=0;
cout<< "Author name Book's Name Publish Year Number of versions "<<endl;
while(!book.eof())
{
book.getline(b.AuthorName,50,'|');
book.getline(b.Name,50,'|');
book.getline(b.Publishyear,5,'|');
book>>b.NumOfversions;
if(strcmp(b.Name, NameToSearh)==0)
{
cout<< b.AuthorName <<" "<<b.Name<<" "<<b.Publishyear<<" "<<b.NumOfversions<<endl;
x=1;
break;
}
}
if(x==0)
{
cout<<"not found\n";
}
book.close();
}
void FCILibraryBooks::SearchByAuthor()
{
fstream book;
FCILibraryBooks b;
book.open("Library.txt",ios::in);
cin.ignore();
char AuthorToSearh[50];
cout<<"Enter the Book's Author Name to search about it : ";
cin.getline(AuthorToSearh,50);
int x=0;
cout<< "Author name Book's Name Publish Year Number of versions "<<endl;
while(!book.eof())
{
book.getline(b.AuthorName,50,'|');
book.getline(b.Name,50,'|');
book.getline(b.Publishyear,5,'|');
book>>b.NumOfversions;
if(strcmp(b.AuthorName, AuthorToSearh)==0)
{
cout<< b.AuthorName <<" "<<b.Name<<" "<<b.Publishyear<<" "<<b.NumOfversions<<endl;
x=1;
break;
}
}
if(x==0)
{
cout<<"not found\n";
}
book.close();
}
bool cmp(const FCILibraryBooks &n1,const FCILibraryBooks &n2)
{
return n1.Name > n2.Name;
}
void FCILibraryBooks::ListInAlpha()
{
fstream book;
fstream temp;
FCILibraryBooks b;
vector<FCILibraryBooks> list;
cin.ignore();
cout<<"The books listed by Alphabetical order according to its name."<<endl;
book.open("Library.txt",ios::in);
while(!book.eof())
{
FCILibraryBooks t;
book.getline(t.AuthorName,50,'|');
book.getline(t.Name,50,'|');
book.getline(t.Publishyear,5,'|');
book>>t.NumOfversions;
list.push_back(t);
}
sort(list.begin(),list.end(),cmp);
book.close();
book.open("Library.txt",ios::out|ios::trunc);
for(int i = 0;i < list.size();i++)
{
cout<<list[i].AuthorName<<'|'<<list[i].Name<<'|'<<list[i].Publishyear<<'|'<<list[i].NumOfversions<<endl;
book<<list[i].AuthorName<<'|'<<list[i].Name<<'|'<<list[i].Publishyear<<'|'<<list[i].NumOfversions;
}
book.close();
}
void FCILibraryBooks::UpdateBook()
{
fstream book;
fstream temp;
FCILibraryBooks b;
book.open("Library.txt",ios::in);
temp.open("temp.txt",ios::out);
char NameToUpdate[50];
cin.ignore();
cout<<"Enter the book's name to update record : ";
cin.getline(NameToUpdate,50);
while(!book.eof())
{
book.getline(b.AuthorName,50,'|');
book.getline(b.Name,50,'|');
book.getline(b.Publishyear,5,'|');
book>>b.NumOfversions;
if(strcmp(b.Name,NameToUpdate)==0)
{
cout<<"Enter the new number of versions : ";
cin>>b.NumOfversions;
temp<<b.AuthorName<<'|'<<b.Name<<'|'<<b.Publishyear<<'|'<<b.NumOfversions;
}
else
{
temp<<b.AuthorName<<'|'<<b.Name<<'|'<<b.Publishyear<<'|'<<b.NumOfversions;
}
}
temp.close();
book.close();
book.open("Library.txt",ios::out);
temp.open("temp.txt",ios::in);
while(!temp.eof())
{
temp.getline(b.AuthorName,50,'|');
temp.getline(b.Name,50,'|');
temp.getline(b.Publishyear,5,'|');
temp>>b.NumOfversions;
book<<b.AuthorName<<'|'<<b.Name<<'|'<<b.Publishyear<<'|'<<b.NumOfversions;
}
temp.close();
book.close();
remove("temp.txt");
}
void FCILibraryBooks::HighestNumberOfVersions()
{
fstream book;
FCILibraryBooks b;
vector<int> NOV;
cin.ignore();
cout<<"The book of the highest number of versions ."<<endl;
book.open("Library.txt",ios::in);
while(!book.eof())
{
book.getline(b.AuthorName,50,'|');
book.getline(b.Name,50,'|');
book.getline(b.Publishyear,5,'|');
book>>b.NumOfversions;
NOV.push_back(b.NumOfversions);
}
int MAX = this->getMaxInt(NOV);
book.close();
book.open("Library.txt",ios::in);
while(!book.eof())
{
book.getline(b.AuthorName,50,'|');
book.getline(b.Name,50,'|');
book.getline(b.Publishyear,5,'|');
book>>b.NumOfversions;
if(b.NumOfversions==MAX)
{
cout<<b.AuthorName<<'|'<<b.Name<<'|'<<b.Publishyear<<'|'<<b.NumOfversions<<endl;
}
}
book.close();
}
|
/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2011 Steven Lovegrove
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
// Pangolin video supports various cameras and file formats through
// different 3rd party libraries.
//
// Video URI's take the following form:
// scheme:[param1=value1,param2=value2,...]//device
//
// scheme = file | files | pango | shmem | dc1394 | uvc | v4l | openni2 |
// openni | depthsense | pleora | teli | mjpeg | test |
// thread | convert | debayer | split | join | shift | mirror | unpack
//
// file/files - read one or more streams from image file(s) / video
// e.g. "files://~/data/dataset/img_*.jpg"
// e.g. "files://~/data/dataset/img_[left,right]_*.pgm"
// e.g. "files:///home/user/sequence/foo%03d.jpeg"
//
// e.g. "file:[fmt=GRAY8,size=640x480]///home/user/raw_image.bin"
// e.g. "file:[realtime=1]///home/user/video/movie.pango"
// e.g. "file:[stream=1]///home/user/video/movie.avi"
//
// dc1394 - capture video through a firewire camera
// e.g. "dc1394:[fmt=RGB24,size=640x480,fps=30,iso=400,dma=10]//0"
// e.g. "dc1394:[fmt=FORMAT7_1,size=640x480,pos=2+2,iso=400,dma=10]//0"
// e.g. "dc1394:[fmt=FORMAT7_3,deinterlace=1]//0"
//
// v4l - capture video from a Video4Linux (USB) camera (normally YUVY422 format)
// method=mmap|read|userptr
// e.g. "v4l:///dev/video0"
// e.g. "v4l[method=mmap]:///dev/video0"
//
// openni2 - capture video / depth from OpenNI2 SDK (Kinect / Xtrion etc)
// imgN=grey|rgb|ir|ir8|ir24|depth|reg_depth
// e.g. "openni2://'
// e.g. "openni2:[img1=rgb,img2=depth,coloursync=true]//"
// e.g. "openni2:[img1=depth,close=closerange,holefilter=true]//"
// e.g. "openni2:[size=320x240,fps=60,img1=ir]//"
//
// openni - capture video / depth from OpenNI 1.0 SDK (Kinect / Xtrion etc)
// Sensor modes containing '8' will truncate to 8-bits.
// Sensor modes containing '+' explicitly enable IR illuminator
// imgN=rgb|ir|ir8|ir+|ir8+|depth|reg_depth
// autoexposure=true|false
// e.g. "openni://'
// e.g. "openni:[img1=rgb,img2=depth]//"
// e.g. "openni:[size=320x240,fps=60,img1=ir]//"
//
// depthsense - capture video / depth from DepthSense SDK.
// DepthSenseViewer can be used to alter capture settings.
// imgN=depth|rgb
// sizeN=QVGA|320x240|...
// fpsN=25|30|60|...
// e.g. "depthsense://"
// e.g. "depthsense:[img1=depth,img2=rgb]//"
//
// pleora - USB 3 vision cameras accepts any option in the same format reported by eBUSPlayer
// e.g. for lightwise cameras: "pleora:[size=512x256,pos=712x512,sn=00000274,ExposureTime=10000,PixelFormat=Mono12p,AcquisitionMode=SingleFrame,TriggerSource=Line0,TriggerMode=On]//"
// e.g. for toshiba cameras: "pleora:[size=512x256,pos=712x512,sn=0300056,PixelSize=Bpp12,ExposureTime=10000,ImageFormatSelector=Format1,BinningHorizontal=2,BinningVertical=2]//"
// e.g. toshiba alternated "pleora:[UserSetSelector=UserSet1,ExposureTime=10000,PixelSize=Bpp12,Width=1400,OffsetX=0,Height=1800,OffsetY=124,LineSelector=Line1,LineSource=ExposureActive,LineSelector=Line2,LineSource=Off,LineModeAll=6,LineInverterAll=6,UserSetSave=Execute,
// UserSetSelector=UserSet2,PixelSize=Bpp12,Width=1400,OffsetX=1048,Height=1800,OffsetY=124,ExposureTime=10000,LineSelector=Line1,LineSource=Off,LineSelector=Line2,LineSource=ExposureActive,LineModeAll=6,LineInverterAll=6,UserSetSave=Execute,
// SequentialShutterIndex=1,SequentialShutterEntry=1,SequentialShutterIndex=2,SequentialShutterEntry=2,SequentialShutterTerminateAt=2,SequentialShutterEnable=On,,AcquisitionFrameRateControl=Manual,AcquisitionFrameRate=70]//"
//
// thread - thread that continuously pulls from the child streams so that data in, unpacking, debayering etc can be decoupled from the main application thread
// e.g. thread://pleora://
// e.g. thread://unpack://pleora:[PixelFormat=Mono12p]//
//
// convert - use FFMPEG to convert between video pixel formats
// e.g. "convert:[fmt=RGB24]//v4l:///dev/video0"
// e.g. "convert:[fmt=GRAY8]//v4l:///dev/video0"
//
// mjpeg - capture from (possibly networked) motion jpeg stream using FFMPEG
// e.g. "mjpeg://http://127.0.0.1/?action=stream"
//
// debayer - debayer an input video stream
// e.g. "debayer:[tile="BGGR",method="downsample"]//v4l:///dev/video0
//
// split - split an input video into a one or more streams based on Region of Interest / memory specification
// roiN=X+Y+WxH
// memN=Offset:WxH:PitchBytes:Format
// e.g. "split:[roi1=0+0+640x480,roi2=640+0+640x480]//files:///home/user/sequence/foo%03d.jpeg"
// e.g. "split:[mem1=307200:640x480:1280:GRAY8,roi2=640+0+640x480]//files:///home/user/sequence/foo%03d.jpeg"
// e.g. "split:[stream1=2,stream2=1]//pango://video.pango"
//
// join - join streams
// e.g. "join:[sync_tolerance_us=100, sync_continuously=true]//{pleora:[sn=00000274]//}{pleora:[sn=00000275]//}"
//
// test - output test video sequence
// e.g. "test://"
// e.g. "test:[size=640x480,fmt=RGB24]//"
#include <pangolin/utils/uri.h>
#include <pangolin/video/video_exception.h>
#include <pangolin/video/video_interface.h>
#include <pangolin/video/video_output_interface.h>
namespace pangolin
{
//! Open Video Interface from string specification (as described in this files header)
PANGOLIN_EXPORT
std::unique_ptr<VideoInterface> OpenVideo(const std::string& uri);
//! Open Video Interface from Uri specification
PANGOLIN_EXPORT
std::unique_ptr<VideoInterface> OpenVideo(const Uri& uri);
//! Open VideoOutput Interface from string specification (as described in this files header)
PANGOLIN_EXPORT
std::unique_ptr<VideoOutputInterface> OpenVideoOutput(const std::string& str_uri);
//! Open VideoOutput Interface from Uri specification
PANGOLIN_EXPORT
std::unique_ptr<VideoOutputInterface> OpenVideoOutput(const Uri& uri);
//! Create vector of matching interfaces either through direct cast or filter interface.
template<typename T>
std::vector<T*> FindMatchingVideoInterfaces( VideoInterface& video )
{
std::vector<T*> matches;
T* vid = dynamic_cast<T*>(&video);
if(vid) {
matches.push_back(vid);
}
VideoFilterInterface* vidf = dynamic_cast<VideoFilterInterface*>(&video);
if(vidf) {
std::vector<T*> fmatches = vidf->FindMatchingStreams<T>();
matches.insert(matches.begin(), fmatches.begin(), fmatches.end());
}
return matches;
}
template<typename T>
T* FindFirstMatchingVideoInterface( VideoInterface& video )
{
T* vid = dynamic_cast<T*>(&video);
if(vid) {
return vid;
}
VideoFilterInterface* vidf = dynamic_cast<VideoFilterInterface*>(&video);
if(vidf) {
std::vector<T*> fmatches = vidf->FindMatchingStreams<T>();
if(fmatches.size()) {
return fmatches[0];
}
}
return 0;
}
inline
picojson::value GetVideoFrameProperties(VideoInterface* video)
{
VideoPropertiesInterface* pi = dynamic_cast<VideoPropertiesInterface*>(video);
VideoFilterInterface* fi = dynamic_cast<VideoFilterInterface*>(video);
if(pi) {
return pi->FrameProperties();
}else if(fi){
if(fi->InputStreams().size() == 1) {
return GetVideoFrameProperties(fi->InputStreams()[0]);
}else if(fi->InputStreams().size() > 0){
picojson::value streams;
for(size_t i=0; i< fi->InputStreams().size(); ++i) {
const picojson::value dev_props = GetVideoFrameProperties(fi->InputStreams()[i]);
if(dev_props.contains("streams")) {
const picojson::value& dev_streams = dev_props["streams"];
for(size_t i=0; i < dev_streams.size(); ++i) {
streams.push_back(dev_streams[i]);
}
}else{
streams.push_back(dev_props);
}
}
if(streams.size() > 1) {
picojson::value json = streams[0];
json["streams"] = streams;
return json;
}else{
return streams[0];
}
}
}
return picojson::value();
}
inline
picojson::value GetVideoDeviceProperties(VideoInterface* video)
{
VideoPropertiesInterface* pi = dynamic_cast<VideoPropertiesInterface*>(video);
VideoFilterInterface* fi = dynamic_cast<VideoFilterInterface*>(video);
if(pi) {
return pi->DeviceProperties();
}else if(fi){
if(fi->InputStreams().size() == 1) {
return GetVideoDeviceProperties(fi->InputStreams()[0]);
}else if(fi->InputStreams().size() > 0){
picojson::value streams;
for(size_t i=0; i< fi->InputStreams().size(); ++i) {
const picojson::value dev_props = GetVideoDeviceProperties(fi->InputStreams()[i]);
if(dev_props.contains("streams")) {
const picojson::value& dev_streams = dev_props["streams"];
for(size_t i=0; i < dev_streams.size(); ++i) {
streams.push_back(dev_streams[i]);
}
}else{
streams.push_back(dev_props);
}
}
if(streams.size() > 1) {
picojson::value json = streams[0];
json["streams"] = streams;
return json;
}else{
return streams[0];
}
}
}
return picojson::value();
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define TESTC ""
#define PROBLEM "10474"
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 10000
int main(int argc, char const *argv[])
{
#ifdef DBG
freopen("uva" PROBLEM TESTC ".in", "r", stdin);
freopen("uva" PROBLEM ".out", "w", stdout);
#endif
int N,Q,tmp,ans;
int table[MAXN+5];
int kase = 1;
while( ~scanf("%d %d",&N,&Q) && N ){
for(int i = 0 ; i < N ; i++ )
scanf("%d",&table[i]);
sort(table,table+N);
printf("CASE# %d:\n",kase++ );
for(int j = 0 ; j < Q ; j++ ){
scanf("%d",&tmp);
ans = lower_bound(table,table+N,tmp)-table;
if( table[ans] == tmp )
printf("%d found at %d\n", tmp,ans+1);
else
printf("%d not found\n", tmp );
}
}
return 0;
}
|
#include "Config.h"
#ifdef USING_OGL
#include "ModelGL.h"
#include "Utils.h"
#include "XLoader.h"
#include "Timer.h"
#include <iostream>
#include "TextureGL.h"
#include "Mesh.h"
#include "RenderAttributes.h"
#include <vector>
extern sf::RenderWindow window;
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
void ModelGL::Create()
{
Timer x;
x.Init();
x.Update();
auto start = x.GetDTSecs();
XLoader loader( meshes );
if ( !loader.LoadModel( filename, 0 ) ) return;
x.Update();
auto end = x.GetDTSecs();
std::cout << "Tiempo en cargar modelo " << filename << ": " << (end - start) * 1000 << "ms" << std::endl;
char *vsSourceP = file2string( "Shaders/VS_Mesh.glsl" );
char *fsSourceP = file2string( "Shaders/FS_Mesh.glsl" );
char *vsWFSourceP = file2string( "Shaders/VS_Wireframe.glsl" );
char *fsWFSourceP = file2string( "Shaders/FS_Wireframe.glsl" );
for ( size_t i = 0; i < meshes.size(); ++i )
{
MeshGL* mesh = dynamic_cast<MeshGL*>(meshes[i]);
std::string def;
def += "#version 330 core\n\n";
def += "#define USE_NORMALS\n\n";
def += "#define USE_TEXCOORD0\n\n";
def += "#define USE_BINORMALS\n\n";
def += "#define USE_TANGENTS\n\n";
if ( mesh->effectMaps & Subset::NORMAL_MAP )
{
bUseFresnel = true;
def += "#define NORMAL_MAP\n\n";
}
else
{
bUseFresnel = false;
}
if ( mesh->effectMaps & Subset::SPECULAR_MAP )
{
def += "#define SPECULAR_TEXT\n\n";
}
if ( mesh->effectMaps & Subset::GLOSS_MAP )
{
def += "#define GLOSS_MAP\n\n";
}
if ( !vsSourceP || !fsSourceP )
{
mesh->bShaderError = true;
}
if ( !vsWFSourceP || !fsWFSourceP )
{
mesh->bWFShaderError = true;
}
std::string vsS;
std::string vfS;
std::string vswfS;
std::string vfwfS;
if ( !mesh->bShaderError )
{
vsS = def + vsSourceP;
vfS = def + fsSourceP;
}
else
{
vsS = mesh->dummyVS;
vfS = mesh->dummyFS;
}
if ( !mesh->bWFShaderError )
{
vswfS = def + vsWFSourceP;
vfwfS = def + fsWFSourceP;
}
else
{
vswfS = mesh->dummyVS;
vfwfS = mesh->dummyFS;
}
norShader.loadFromMemory( vsS, vfS );
sf::Shader::bind( &norShader );
mesh->shaderID = norShader.getNativeHandle();
mesh->vertexAttribLoc = glGetAttribLocation( mesh->shaderID, "Vertex" );
if ( !mesh->bShaderError )
{
mesh->normalAttribLoc = glGetAttribLocation( mesh->shaderID, "Normal" );
mesh->uvAttribLoc = glGetAttribLocation( mesh->shaderID, "UV" );
mesh->binormalAttribLoc = glGetAttribLocation( mesh->shaderID, "Binormal" );
mesh->tangentAttribLoc = glGetAttribLocation( mesh->shaderID, "Tangent" );
auto alu = glGetUniformLocation( mesh->shaderID, "World" );
int x = 0;
}
/*********************Wireframe********************/
if ( !wfShader.loadFromMemory( vswfS, vfwfS ) )
{
}
sf::Shader::bind( &wfShader );
mesh->shaderWFID = wfShader.getNativeHandle();
mesh->vertexWFAttribLoc = glGetAttribLocation( mesh->shaderWFID, "Vertex" );
/*
mesh->shaderWFID = glCreateProgram();
glAttachShader( mesh->shaderWFID, vswfhader_id );
glAttachShader( mesh->shaderWFID, fswfhader_id );
glLinkProgram( mesh->shaderWFID );
glUseProgram( mesh->shaderWFID );
mesh->matWorldViewWFProjUniformLoc = glGetUniformLocation( mesh->shaderWFID, "WVP" );
*/
/**************************************************/
sf::Shader::bind( 0 );
static std::vector<sf::Uint8> checkered;
for ( int j = 0; j < (int)mesh->subsets.size(); ++j )
{
Subset* subSet = &mesh->subsets[j];
for ( auto& texture : subSet->texturesInfo )
{
TextureInfo* txInfo = &texture.second;
std::string type = txInfo->varName;
if ( !txInfo->texture.loadFromFile( "Textures/" + txInfo->pathName ) )
{
if ( checkered.empty() )
{
checkered.resize(32 * 32 * 4);
for ( int i = 0; i < 32; ++i )
{
int a = i;
for ( int j = 0; j < 32 * 4; j += 4 )
{
unsigned char v = unsigned char( (a++ % 2) * 255 );
checkered[i * 32 * 4 + (j + 0)] = v;
checkered[i * 32 * 4 + (j + 1)] = v;
checkered[i * 32 * 4 + (j + 2)] = v;
checkered[i * 32 * 4 + (j + 3)] = 255;
}
}
}
txInfo->texture.create( 32, 32 );
txInfo->texture.update( checkered.data() );
}
else if ( txInfo->pathName == "grasss.tga" )
{
glBindTexture( GL_TEXTURE_2D, txInfo->texture.getNativeHandle() );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
glBindTexture( GL_TEXTURE_2D, 0 );
}
}
GenBuffer( subSet->indices, subSet->indexBufferID, GL_ELEMENT_ARRAY_BUFFER );
}
GenBuffer( mesh->vertices, mesh->vertexBufferID, GL_ARRAY_BUFFER );
GenBuffer( mesh->indices, mesh->indexBufferID, GL_ELEMENT_ARRAY_BUFFER );
GenBuffer( mesh->vertices_wf, mesh->vertexBufferWFID, GL_ARRAY_BUFFER );
GenBuffer( mesh->indices_wf, mesh->indexBufferWFID, GL_ELEMENT_ARRAY_BUFFER );
}
if ( vsSourceP )
delete[]vsSourceP;
if ( fsSourceP )
delete[]fsSourceP;
if ( vsWFSourceP )
delete[]vsWFSourceP;
if ( fsWFSourceP )
delete[]fsWFSourceP;
transform.Identity();
}
void ModelGL::Transform( float * t )
{
transform = t;
}
void ModelGL::Draw( float *t, const SRenderAttributes& renderAttribs )
{
transform = t;
using Mat4D::CMatrix4D;
using Mat4D::CVector4D;
auto pCam = renderAttribs.iCamera == 1 ? renderAttribs.pLightCamera : renderAttribs.pCamera;
Mat4D::CMatrix4D VP =/* VPForced;*/pCam->GetVP();
Mat4D::CMatrix4D WVP = transform * VP;
Mat4D::CMatrix4D LightWVP = renderAttribs.pLightCamera->GetVP();
Mat4D::CVector4D CamInfo = /*CamInfoForced;*/pCam->GetInfo();
CamInfo.w = renderAttribs.iCamera == 0 ? -1.f : 1.f;
Mat4D::CVector4D lightPos = renderAttribs.pLightCamera->GetPosition();
for ( size_t i = 0; i < meshes.size(); ++i )
{
MeshGL* mesh = dynamic_cast<MeshGL*>(meshes[i]);
if ( *renderAttribs.pDrawMode == DrawMode::Normal )
{
glUseProgram( mesh->shaderID );
norShader.setUniform( "WVP", sf::Glsl::Mat4( WVP.v ) );
if ( !mesh->bShaderError )
{
//norShader.setUniform( "CamPos", sf::Glsl::Vec4( CamPos.x, CamPos.y, CamPos.z, CamPos.w ) );
if ( renderAttribs.iCamera == 1 )
{
//auto lightCamInfo = renderAttribs.pLightCamera->GetInfo();
//auto lightPos = renderAttribs.pLightCamera->GetPosition();
//norShader.setUniform( "LightCameraInfo", sf::Glsl::Vec4( lightCamInfo.x, lightCamInfo.y, lightCamInfo.z, lightCamInfo.w ) );
//norShader.setUniform( "LightPos", sf::Glsl::Vec4( lightPos.x, lightPos.y, lightPos.z, lightPos.w ) );
//norShader.setUniform( "LightWVP", sf::Glsl::Mat4( LightWVP.v ) );
}
norShader.setUniform( "cam_info", sf::Glsl::Vec4(CamInfo.x, CamInfo.y, CamInfo.z, CamInfo.w) );
/*auto& lightPos = renderAttribs.pvLightsPos->at(0);
norShader.setUniform( "light_pos",
sf::Glsl::Vec4( lightPos.x,
lightPos.y,
lightPos.z,
lightPos.w ) );
auto& lightCol = renderAttribs.pvLightsCol->at(0);
norShader.setUniform( "light_color",
sf::Glsl::Vec4( lightCol.x,
lightCol.y,
lightCol.z,
lightCol.w ) );
auto camPos = pCam->GetPosition();
norShader.setUniform( "cam_pos",
sf::Glsl::Vec4( camPos.x, camPos.y, camPos.z, camPos.w) );*/
norShader.setUniform( "World", sf::Glsl::Mat4( transform.v ) );
}
glBindBuffer( GL_ARRAY_BUFFER, mesh->vertexBufferID );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mesh->indexBufferID );
glEnableVertexAttribArray( mesh->vertexAttribLoc );
glVertexAttribPointer( mesh->vertexAttribLoc, 4, GL_FLOAT, GL_FALSE, sizeof( CVertex ), BUFFER_OFFSET( 0 ) );
if ( !mesh->bShaderError )
{
if ( mesh->normalAttribLoc != -1 )
{
glEnableVertexAttribArray( mesh->normalAttribLoc );
glVertexAttribPointer( mesh->normalAttribLoc, 4, GL_FLOAT, GL_FALSE, sizeof( CVertex ), BUFFER_OFFSET( 16 ) );
}
if ( mesh->uvAttribLoc != -1 )
{
glEnableVertexAttribArray( mesh->uvAttribLoc );
glVertexAttribPointer( mesh->uvAttribLoc, 2, GL_FLOAT, GL_FALSE, sizeof( CVertex ), BUFFER_OFFSET( 32 ) );
}
if ( mesh->binormalAttribLoc != -1 )
{
glEnableVertexAttribArray( mesh->binormalAttribLoc );
glVertexAttribPointer( mesh->binormalAttribLoc, 4, GL_FLOAT, GL_FALSE, sizeof( CVertex ), BUFFER_OFFSET( 40 ) );
}
if ( mesh->tangentAttribLoc != -1 )
{
glEnableVertexAttribArray( mesh->tangentAttribLoc );
glVertexAttribPointer( mesh->tangentAttribLoc, 4, GL_FLOAT, GL_FALSE, sizeof( CVertex ), BUFFER_OFFSET( 56 ) );
}
}
for ( std::size_t j = 0; j < mesh->subsets.size(); ++j )
{
Subset* subSet = &mesh->subsets[j];
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, subSet->indexBufferID );
int txIndex = 0;
if ( !mesh->bShaderError )
{
for ( auto& texture : subSet->texturesInfo )
{
auto loc = glGetUniformLocation( mesh->shaderID, texture.second.varName.c_str() );
auto id = texture.second.texture.getNativeHandle();
glActiveTexture( GL_TEXTURE0 + txIndex );
glBindTexture( GL_TEXTURE_2D, id );
glUniform1i( loc, txIndex++ );
}
}
if( renderAttribs.iCamera == 1 )
{
/*auto loc = glGetUniformLocation( mesh->shaderID, "LightDepth" );
auto id = renderAttribs.vTextures[TextureType::LightDepth]->id;
glActiveTexture( GL_TEXTURE0 + txIndex );
glBindTexture( GL_TEXTURE_2D, id );
glUniform1i( loc, txIndex++ );*/
}
glDrawElements( GL_TRIANGLES, subSet->indices.size(), GL_UNSIGNED_SHORT, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
}
glActiveTexture( GL_TEXTURE0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glDisableVertexAttribArray( mesh->vertexAttribLoc );
if ( !mesh->bShaderError )
{
if ( mesh->normalAttribLoc != -1 )
glDisableVertexAttribArray( mesh->normalAttribLoc );
if ( mesh->uvAttribLoc != -1 )
{
glDisableVertexAttribArray( mesh->uvAttribLoc );
}
if ( mesh->binormalAttribLoc != -1 )
{
glDisableVertexAttribArray( mesh->binormalAttribLoc );
}
if ( mesh->tangentAttribLoc != -1 )
{
glDisableVertexAttribArray( mesh->tangentAttribLoc );
}
}
}
else if ( *renderAttribs.pDrawMode == DrawMode::Wireframe )
{
glUseProgram( mesh->shaderWFID );
wfShader.setUniform( "WVP", sf::Glsl::Mat4( WVP.v ) );
glBindBuffer( GL_ARRAY_BUFFER, mesh->vertexBufferWFID );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mesh->indexBufferWFID );
glEnableVertexAttribArray( mesh->vertexWFAttribLoc );
glVertexAttribPointer( mesh->vertexWFAttribLoc, 4, GL_FLOAT, GL_FALSE, sizeof( CWFVertex ), BUFFER_OFFSET( 0 ) );
glDrawElements( GL_LINES, mesh->indices_wf.size(), GL_UNSIGNED_SHORT, 0 );
glActiveTexture( GL_TEXTURE0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glDisableVertexAttribArray( mesh->vertexWFAttribLoc );
}
glUseProgram( 0 );
}
}
void ModelGL::Destroy()
{
for ( size_t i = 0; i < textures.size(); ++i )
{
if ( textures[i] )
delete textures[i];
}
}
void ModelGL::SetUniform( std::string name, const Mat4D::CVector4D & vec4 )
{
}
void ModelGL::SetUniform( std::string name, const Mat4D::CMatrix4D & mat4 )
{
}
void ModelGL::SetUniform( std::string name, float val )
{
}
#endif
|
#include "DepthImageComp.h"
int vcount=0;
unsigned char cdata[120000];
int cbuffer_size=120000;
// Callback function gets invoked during compression...
// It returns the compressed data byte by byte...
void OwnWriteFunction(int byte)
{
if(vcount<cbuffer_size)
cdata[vcount]=(unsigned char)byte;
vcount++;
}
DepthImageComp::DepthImageComp()
{
buffersize = IMAGE_WIDTH*IMAGE_HEIGHT*3;
}
DepthImageComp::~DepthImageComp()
{
}
void DepthImageComp::InitEncoder()
{
// Initialize the compressor
// Initialize table for RGB to YUV conversion
InitLookupTable();
// Initialize the compressor
cparams.format = CPARAM_CIF;
InitH263Encoder(&cparams);
// Set up the callback function
WriteByteFunction = OwnWriteFunction;
}
void DepthImageComp::InitDecoder()
{
// Initialize decompressor
InitH263Decoder();
}
void DepthImageComp::Compress(unsigned char * a_pSrc)
{
//Convert the data from rgb format to YUV format
ConvertRGB2YUV(IMAGE_WIDTH,IMAGE_HEIGHT,a_pSrc,yuv);
vcount=0;
//Compress the data...to h263
cparams.format=CPARAM_CIF;
cparams.inter = CPARAM_INTRA;
cparams.Q_intra = 8;
cparams.data=yuv; // Data in YUV format...
CompressFrame(&cparams, &bits);
compSize = vcount;
memcpy(compImage, cdata, compSize);
}
void DepthImageComp::Decompress(unsigned char * a_pSrc, unsigned int a_size)
{
int retvalue;
retvalue=DecompressFrame(a_pSrc, a_size, rgbdata, buffersize);
}
void DepthImageComp::CompressDepth(unsigned char * a_pSrc)
{
//Convert the data from rgb format to YUV format
ConvertD2YUV(IMAGE_WIDTH,IMAGE_HEIGHT,a_pSrc,yuv);
vcount=0;
//Compress the data...to h263
cparams.format=CPARAM_CIF;
cparams.inter = CPARAM_INTRA;
cparams.Q_intra = 8;
cparams.data=yuv; // Data in YUV format...
CompressFrame(&cparams, &bits);
compDepthSize = vcount;
memcpy(compDepthImage, cdata, compDepthSize);
}
void DepthImageComp::DecompressDepth(unsigned char * a_pSrc, unsigned int a_size)
{
unsigned char tempdata[IMAGE_WIDTH*IMAGE_HEIGHT*3];
int retvalue;
retvalue=DecompressFrame(a_pSrc, a_size, tempdata, buffersize);
for(int i=0; i<buffersize; i+=3) {
depthdata[(int)((float)i/3.0)] = tempdata[i];
}
}
|
// Project 19 Tune Player
int soundPin = 11;
byte sine[] = {0, 22, 44, 64, 82, 98, 111, 120, 126, 127,
126, 120, 111, 98, 82, 64, 44, 22, 0, -22, -44, -64, -82,
-98, -111, -120, -126, -128, -126, -120, -111, -98, -82,
-64, -44, -22};
int toneDurations[] = {120, 105, 98, 89, 78, 74, 62};
char* song = "e e ee e e ee e g c d eeee f f f f f e e e e d d e dd gg e e ee e e ee e g c d eeee f f f f f e e e g g f d cccc";
void setup()
{
// change PWM frequency to 63kHz
cli(); //disable interrupts while registers are configured
bitSet(TCCR2A, WGM20);
bitSet(TCCR2A, WGM21); //set Timer2 to fast PWM mode (doubles PWM frequency)
bitSet(TCCR2B, CS20);
bitClear(TCCR2B, CS21);
bitClear(TCCR2B, CS22);
sei(); //enable interrupts now that registers have been set
pinMode(soundPin, OUTPUT);
}
void loop()
{
int i = 0;
char ch = song[0];
while (ch != 0)
{
if (ch == ' ')
{
delay(75);
}
else if (ch >= 'a' and ch <= 'g')
{
playNote(toneDurations[ch - 'a']);
}
i++;
ch = song[i];
}
delay(5000);
}
void playNote(int pitchDelay)
{
long numCycles = 5000 / pitchDelay;
for (int c = 0; c < numCycles; c++)
{
playSine(pitchDelay);
}
}
void playSine(int period)
{
for( int i = 0; i < 36; i++)
{
analogWrite(soundPin, sine[i] + 128);
delayMicroseconds(period);
}
}
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#ifndef FOO_H
#define FOO_H
#include <QObject>
class Foo
#ifdef FOO
: public QObject
#endif
{
Q_OBJECT
public:
Foo();
public slots:
void doFoo();
};
#endif
|
#include "frame.h"
#include "util.h"
#include "gtest/gtest.h"
#include <string>
#include <iostream>
TEST(UtilTest, NormalTest) {
std::string data = "hello world";
uint8_t enc_a_wire[30];
const uint8_t e_wire[13] = {0x00, 0x0b, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
int32_t enc_a_len = UTF8_encode(enc_a_wire, data);
int32_t enc_e_len = data.size()+2;
EXPECT_EQ(enc_e_len, enc_a_len);
EXPECT_TRUE(0 == memcmp(enc_a_wire, e_wire, enc_a_len));
std::string dec_a_str;
int64_t dec_a_len = UTF8_decode(e_wire, &dec_a_str);
EXPECT_EQ(enc_e_len, dec_a_len);
EXPECT_TRUE(0 == memcmp(data.c_str(), dec_a_str.c_str(), data.size()));
int dataNum = 9;
uint32_t lens[9] = {0, 1, 127, 128, 16383, 16384, 2097151, 2097152, 268435455};
uint8_t remEnc_a_wire[30];
uint8_t remEnc_e_wires[9][4] = {{0x00}, {0x01}, {0x7f}, {0x80, 0x01}, {0xff, 0x7f}, {0x80, 0x80, 0x01},
{0xff, 0xff, 0x7f}, {0x80, 0x80, 0x80, 0x01}, {0xff, 0xff, 0xff, 0x7f}};
uint8_t e_wire_len[9] = {1, 1, 1, 2, 2, 3, 3, 4, 4};
for (int i = 0; i < dataNum; i++) {
int32_t remEnc_e_len = remainEncode(remEnc_a_wire, lens[i]);
EXPECT_TRUE(0 == memcmp(remEnc_e_wires[i], remEnc_a_wire, remEnc_e_len));
}
int wire_progress = 0;
MQTT_ERROR err;
for (int i = 0; i < dataNum; i++) {
int32_t a_remLength = remainDecode(remEnc_e_wires[i], &wire_progress, err);
EXPECT_EQ(e_wire_len[i], wire_progress);
EXPECT_EQ(lens[i], a_remLength);
}
std::vector<std::string> a_parts, e_parts;
e_parts.push_back("a");
e_parts.push_back("b");
e_parts.push_back("c");
std::string splitted = "a/b/c";
int done = split(splitted, "/", &a_parts);
for (int i = 0; i < 3; i++) {
EXPECT_TRUE(e_parts[i] == a_parts[i]);
}
}
TEST(FrameHeaderTest, NormalTest) {
MessageType type = PUBLISH_MESSAGE_TYPE;
bool dup = true;
uint8_t qos = 2;
bool retain = true;
uint32_t len = 1;
uint16_t id = 0;
FixedHeader* fh = new FixedHeader(type, dup, qos, retain, len, id);
EXPECT_EQ(type, fh->type);
EXPECT_EQ(dup, fh->dup);
EXPECT_EQ(qos, fh->qos);
EXPECT_EQ(retain, fh->retain);
EXPECT_EQ(len, fh->length);
EXPECT_EQ(id, fh->packetID);
uint8_t e_wire[2] = {0x3d, 0x01};
int e_len = 2;
uint8_t a_wire[30];
int64_t a_len = fh->getWire(a_wire);
EXPECT_EQ(e_len, a_len);
EXPECT_TRUE(0 == memcmp(e_wire, a_wire, e_len));
MQTT_ERROR a_err = NO_ERROR;
FixedHeader* a_fh = new FixedHeader();
a_len = a_fh->parseHeader(e_wire, a_err);
EXPECT_EQ(type, a_fh->type);
EXPECT_EQ(dup, a_fh->dup);
EXPECT_EQ(qos, a_fh->qos);
EXPECT_EQ(retain, a_fh->retain);
EXPECT_EQ(len, a_fh->length);
EXPECT_EQ(id, a_fh->packetID);
EXPECT_EQ(NO_ERROR, a_err);
EXPECT_EQ(e_len, a_len);
}
TEST(ConnectMessageTead, NormalTest) {
uint16_t keepAlive = 10;
std::string id = "my-ID";
bool cleanSession = false;
uint8_t flags = WILL_FLAG | WILL_RETAIN_FLAG | PASSWORD_FLAG | USERNAME_FLAG;
User* user = new User{"daiki", "pass"};
Will* will = new Will{"daiki/will", "message", true, 1};
uint32_t e_len = 16 + MQTT_3_1_1.name.size() + id.size() + will->topic.size() + will->message.size() + user->name.size() + user->passwd.size();
FixedHeader* a_fh = new FixedHeader(CONNECT_MESSAGE_TYPE, false, 0, false, e_len, 0);
ConnectMessage* a_mess = new ConnectMessage(keepAlive, id, cleanSession, will, user);
uint8_t a_wire[100];
uint8_t e_wire[100];
uint8_t* e_st = e_wire;
uint32_t a_len = a_fh->getWire(a_wire);
uint32_t tmp_len = a_fh->getWire(e_st);
a_len += a_mess->getWire(a_wire+a_len);
e_st += tmp_len;
tmp_len = UTF8_encode(e_st+e_len, MQTT_3_1_1.name);
e_st += tmp_len;
*(e_st++) = MQTT_3_1_1.level;
*(e_st++) = flags;
*(e_st++) = (uint8_t)(keepAlive >> 8);
*(e_st++) = (uint8_t)keepAlive;
tmp_len = UTF8_encode(e_st, id);
e_st += tmp_len;
tmp_len = UTF8_encode(e_st, will->topic);
e_st += tmp_len;
tmp_len = UTF8_encode(e_st, will->message);
e_st += tmp_len;
tmp_len = UTF8_encode(e_st, user->name);
e_st += tmp_len;
tmp_len = UTF8_encode(e_st, user->passwd);
e_st += tmp_len;
EXPECT_EQ(e_st-e_wire, a_len);
EXPECT_TRUE(0 == memcmp(e_wire, a_wire, e_len));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#include "skybox.h"
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "stb_image.h"
#include <iostream>
void skybox::loadCubemap(GLuint& skytexture)
{
//unsigned int textureID;
glGenTextures(1, &skytexture);
glBindTexture(GL_TEXTURE_CUBE_MAP, skytexture);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data
);
stbi_image_free(data);
}
else
{
std::cout << "Cubemap tex failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
skybox::skybox(){
float skyboxVerts[] = {
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
for (int i = 0; i < 108; i++)
{
skyboxVerts[i] *= 200;
}
faces = {
"..\\..\\images\\right.jpg",
"..\\..\\images\\left.jpg",
"..\\..\\images\\top.jpg",
"..\\..\\images\\bottom.jpg",
"..\\..\\images\\front.jpg",
"..\\..\\images\\back.jpg"
};
//skyboxVBO = 0;
glGenBuffers(1, &skyboxVBO);
glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVerts), skyboxVerts, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
skyboxTextureID = 0;
skyboxVAO = 0;
}
void skybox::loadFaces(GLuint& program) {
loadCubemap(skyboxTextureID);
int loc = glGetUniformLocation(program, "skybox");
if (loc > 0) glUniform1i(loc, 0);
}
void skybox::bindSkybox() {
glGenBuffers(1, &skyboxVBO);
glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVerts), skyboxVerts, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void skybox::loadSkybox() {
//glBindVertexArray(skyboxVAO);
glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
glEnableVertexAttribArray(skyboxVAO);
glVertexAttribPointer(skyboxVAO, 3, GL_FLOAT, GL_FALSE, 0, 0);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, skyboxTextureID);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}
void skybox::sendUniforms(glm::mat4 view, glm::mat4 projection) {
}
|
#include<iostream>
#include<memory>
#include<vector>
#include "konto.h"
#include "person.h"
#include "bank.h"
using namespace std;
int main(){
auto konto=make_shared<Girokonto>();
auto person1=make_shared<Person>("Gregor");
auto person2=make_shared<Person>("Melanie");
person2->addKonto(*konto);
person2->konto_teilen(*konto,*person1);
cout << *konto;
/**
Bank b("erst");
b.neuerKunde("Mascha",'g');
b.neuerKunde("Oleg",'b');
b.getKunden().front()->konto_teilen(*b.getKunden().front()->getKonten().front(), *b.getKunden().back());
b.getKunden().front()->getKonten().front()->print(cout);
**/
/**
Konto k;
Person p("Vitalii");
auto sp=make_shared<Person>(p);
k.setZeich(*sp);
cout <<k;
cout <<*sp;
cout <<"____________"<< endl;
**/
/**
auto gg=make_shared<Konto>();
auto cc=make_shared<Person>("Lena");
cc->addKonto(*gg);
cout << *cc;
cout << endl;
cout << endl;
cout << *gg;
cout << endl;
gg->auszahlen(19);
**/
/**
Bank b;
b.neuerKunde("Anton");
b.neuerKunde("ANatolii");
cout << b;
**/
//auto person1=make_shared<Person>("Natasha");
//auto person2=make_shared<Person>("Vitalii");
//auto konto1=make_shared<Konto>("AT123123", 560, 30);
//person1->addKonto(*konto1);
//person1->konto_teilen(*konto1, *person2);
//cout << *konto1<<endl;
/**
Bank b;
b.neuerKunde("Olga",'g');
cout << b;
vector<shared_ptr<Person>>kunden=b.getKunden();
cout << *kunden[0]<< endl;
vector<shared_ptr<Konto>> konten=kunden[0]->getKonten();
konten[0]->einzahlen(50);
cout << *konten[0];
**/
/**
Bank b("erste");
b.neuerKunde("p1", 'g');
b.neuerKunde("p2", 'b');
// cout<< *b.getKunden()[0];
b.getKunden().front()->getKonten().front()->einzahlen(200);
b.getKunden().front()->getKonten().front()->ueberweisen(50, *b.getKunden().back()->getKonten().front());
b.getKunden().back()->getKonten().front()->print(cout);
auto p3 = make_shared<Person>("Aigerim");
b.getKunden().front()->konto_teilen(*b.getKunden().front()->getKonten().front(), *p3);
b.getKunden().front()->konto_teilen(*b.getKunden().front()->getKonten().front(), *b.getKunden().back());
b.getKunden().back()->getKonten().back()->print(cout);
**/
/**
Bank b("erste");
b.neuerKunde("Daniil", 'g');
b.neuerKunde("Alisa", 'b');
b.getKunden().front()->print(cout);
b.getKunden().front()->getKonten().front()->einzahlen(100);
b.getKunden().front()->getKonten().front()->setGebuehren(2);
b.getKunden().front()->getKonten().front()->print(cout);
b.getKunden().front()->getKonten().front()->ueberweisen(10, *(b.getKunden().back()->getKonten().front()));
b.getKunden().back()->getKonten().front()->print(cout);
b.getKunden().front()->getKonten().front()->print(cout);
**/
/**
Bank b("erste");
b.neuerKunde("Daniil", 'g');
// b.getkunden().at(0)->print(cout);
// b.getkunden().front()->getkonten().front()->print(cout);
// b.neuerKunde("asfas",'b');
b.getKunden().front()->getKonten().front()->print(cout);
b.getKunden().front()->getKonten().front()->setGebuehren(2);
cout << "**** Uberweisen test::: "<<endl;
b.getKunden().front()->getKonten().front()->einzahlen(1000);
cout << "Nach der 1000 einzahlung( 1 ): "<<endl;
b.getKunden().front()->getKonten().front()->ueberweisen(10, *b.getKunden().back()->getKonten().front());
cout << "( 2 ) "<<endl;
b.getKunden().back()->getKonten().front()->print(cout);
cout << "Nach der 1000 ueberweisung ( 1 ): "<<endl;
b.getKunden().front()->getKonten().front()->print(cout);
// cout <<"OK"<<endl;
**/
/**
auto person= make_shared<Person>("Alla");
person->neues_konto('g');
cout << *person;
person->getKonten().front()->print(cout);
**/
/**
cout <<endl;
Businesskonto b("AT2313",1000,100,10);
cout <<b;
b.auszahlen(200);
cout << b;
**/
return 0;
}
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#ifndef BAJKA_EQ_BOUNCE_H_
#define BAJKA_EQ_BOUNCE_H_
#include "IEquation.h"
namespace Tween {
class BounceOut : public IEquation {
public:
virtual ~BounceOut () {}
double compute (double t, double b, double c, double d) const { return cmp (t, b, c, d); }
static double cmp (double t, double b, double c, double d);
};
class BounceIn : public IEquation {
public:
virtual ~BounceIn () {}
double compute (double t, double b, double c, double d) const { return cmp (t, b, c, d); }
static double cmp (double t, double b, double c, double d);
};
class BounceInOut : public IEquation {
public:
virtual ~BounceInOut () {}
double compute (double t, double b, double c, double d) const
{
if (t < d / 2) {
return BounceIn::cmp (t * 2, 0, c, d) * 0.5 + b;
}
return BounceOut::cmp (t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
}
};
} /* namespace Tween */
# endif /* BOUNCE_H_ */
|
// you can use includes, for example:
// #include <algorithm>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A, vector<int> &B) {
// write your code in C++14 (g++ 6.2.0)
int N = A.size();
int sol = 0;
int j = 0;
int i = 0;
//for(int i=0; i<N; ++i){
while (i<N && j<N){
while (A[j]<=B[i]){
j++;
if (j>=N) break;
}
i=j;
sol++;
}
return sol;
}
|
#pragma once
#include <vector>
#include <utility>
#include <string>
#include <ionir/construct/type.h>
#include <ionir/tracking/symbol_table.h>
namespace ionir {
typedef std::pair<ionshared::Ptr<Type>, std::string> Arg;
class Args {
private:
ionshared::Ptr<ionshared::SymbolTable<Arg>> items;
bool isVariable;
public:
explicit Args(
ionshared::Ptr<ionshared::SymbolTable<Arg>> items =
std::make_shared<ionshared::SymbolTable<Arg>>(),
bool isVariable = false
);
[[nodiscard]] ionshared::Ptr<ionshared::SymbolTable<Arg>> getItems() const noexcept;
void setItems(ionshared::Ptr<ionshared::SymbolTable<Arg>> items) noexcept;
[[nodiscard]] bool getIsVariable() const noexcept;
void setIsVariable(bool isInfinite) noexcept;
};
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
group "desktop_util.optightvector";
include "adjunct/desktop_util/adt/optightvector.h";
global
{
struct Struct
{
// No operator==(). OpTightVector<Struct>::Find() will not compile,
// but it won't be instantiated if it's not used.
Struct(unsigned i) : i(i) {}
unsigned i;
};
struct StructEqualityComparable
{
StructEqualityComparable(unsigned i) : i(i) {}
bool operator==(const StructEqualityComparable& other) const { return other.i == i; }
unsigned i;
};
}
test("Adding items")
{
OpTightVector<unsigned> vector;
OpTightVector<Struct> struct_vector;
OpTightVector<StructEqualityComparable> struct_ec_vector;
for (unsigned i = 0; i < 10; i++)
{
verify_success(vector.Add(i));
verify_success(struct_vector.Add(i));
verify_success(struct_ec_vector.Add(i));
}
verify(vector.GetCount() == 10);
verify(struct_vector.GetCount() == 10);
verify(struct_ec_vector.GetCount() == 10);
for (unsigned i = 0; i < vector.GetCount(); i++)
{
verify(vector[i] == i);
verify(struct_vector[i].i == i);
verify(struct_ec_vector[i] == StructEqualityComparable(i));
}
}
test("Removing items")
{
OpTightVector<unsigned> vector;
OpTightVector<Struct> struct_vector;
OpTightVector<StructEqualityComparable> struct_ec_vector;
for (unsigned i = 0; i < 10; i++)
{
verify_success(vector.Add(i));
verify_success(struct_vector.Add(i));
verify_success(struct_ec_vector.Add(i));
}
vector.Remove(5);
struct_vector.Remove(5);
struct_ec_vector.Remove(5);
verify(vector.GetCount() == 9);
verify(struct_vector.GetCount() == 9);
verify(struct_ec_vector.GetCount() == 9);
for (unsigned i = 0; i < 5; i++)
{
verify(vector[i] == i);
verify(struct_vector[i].i == i);
verify(struct_ec_vector[i] == StructEqualityComparable(i));
}
for (unsigned i = 5; i < vector.GetCount(); i++)
{
verify(vector[i] == i + 1);
verify(struct_vector[i].i == i + 1);
verify(struct_ec_vector[i] == StructEqualityComparable(i + 1));
}
}
test("Inserting items")
{
OpTightVector<unsigned> vector;
OpTightVector<Struct> struct_vector;
OpTightVector<StructEqualityComparable> struct_ec_vector;
for (unsigned i = 0; i < 10; i++)
{
verify_success(vector.Add(i));
verify_success(struct_vector.Add(i));
verify_success(struct_ec_vector.Add(i));
}
vector.Insert(5, 4);
struct_vector.Insert(5, 4);
struct_ec_vector.Insert(5, 4);
verify(vector.GetCount() == 11);
verify(struct_vector.GetCount() == 11);
verify(struct_ec_vector.GetCount() == 11);
for (unsigned i = 0; i < 5; i++)
{
verify(vector[i] == i);
verify(struct_vector[i].i == i);
verify(struct_ec_vector[i] == StructEqualityComparable(i));
}
for (unsigned i = 5; i < vector.GetCount(); i++)
{
verify(vector[i] == i - 1);
verify(struct_vector[i].i == i - 1);
verify(struct_ec_vector[i] == StructEqualityComparable(i - 1));
}
}
test("Finding items")
{
OpTightVector<unsigned> vector;
// OpTightVector<Struct>::Find() won't compile
OpTightVector<StructEqualityComparable> struct_ec_vector;
for (int i = 0; i < 10; i++)
{
verify(vector.Find(i) == -1);
verify(struct_ec_vector.Find(StructEqualityComparable(i)) == -1);
}
for (unsigned i = 0; i < 10; i++)
{
verify_success(vector.Add(10 - i));
verify_success(struct_ec_vector.Add(10 - i));
}
for (int i = 0; i < 10; i++)
{
verify(vector.Find(i + 1) == 10 - i - 1);
verify(struct_ec_vector.Find(StructEqualityComparable(i + 1)) == 10 - i -1);
}
verify(vector.Find(0) == -1);
verify(struct_ec_vector.Find(0) == -1);
verify(vector.Find(11) == -1);
verify(struct_ec_vector.Find(11) == -1);
}
test("Clear all items")
{
OpTightVector<unsigned> vector;
OpTightVector<Struct> struct_vector;
OpTightVector<StructEqualityComparable> struct_ec_vector;
for (unsigned i = 0; i < 10; i++)
{
verify_success(vector.Add(i));
verify_success(struct_vector.Add(i));
verify_success(struct_ec_vector.Add(i));
}
vector.Clear();
struct_vector.Clear();
struct_ec_vector.Clear();
verify(vector.GetCount() == 0);
verify(struct_vector.GetCount() == 0);
verify(struct_ec_vector.GetCount() == 0);
}
test("Storing pointers")
{
OpTightVector<unsigned*> vector;
unsigned value[10];
for (unsigned i = 0; i < 10; i++)
{
value[i] = i;
verify_success(vector.Add(&value[i]));
}
verify(vector.GetCount() == 10);
for (unsigned i = 0; i < vector.GetCount(); i++)
verify(*vector[i] == i);
}
test("Resizing the vector")
{
OpTightVector<int> vector;
verify_success(vector.Resize(10));
verify(vector.GetCount() == 10);
for (unsigned i = 0; i < 10; i++)
vector[i] = i;
verify_success(vector.Resize(5));
verify(vector.GetCount() == 5);
for (int i = 0; i < 5; i++)
verify(vector[i] == i);
}
test("Moving items forwards")
{
OpTightVector<int> vector;
verify_success(vector.Resize(5));
for (unsigned i = 0; i < 5; i++)
vector[i] = i;
vector.Move(1, 2, 2);
verify(vector[0] == 0);
verify(vector[1] == 3);
verify(vector[2] == 1);
verify(vector[3] == 2);
verify(vector[4] == 4);
}
test("Moving items backwards")
{
OpTightVector<int> vector;
verify_success(vector.Resize(5));
for (unsigned i = 0; i < 5; i++)
vector[i] = i;
vector.Move(2, 1, 2);
verify(vector[0] == 0);
verify(vector[1] == 2);
verify(vector[2] == 3);
verify(vector[3] == 1);
verify(vector[4] == 4);
}
|
//
// StringLib.cpp
// Landru
//
// Created by Nick Porcino on 10/29/14.
//
//
#include "StringLib.h"
#include "LandruActorVM/Fiber.h"
#include "LandruActorVM/Generator.h"
#include "LandruActorVM/Library.h"
#include "LandruActorVM/VMContext.h"
#include <algorithm>
#include <string>
#include <cmath>
#include <memory>
using namespace std;
namespace Landru {
namespace Std {
//-------------
// String Libary \__________________________________________
void StringLib::registerLib(Library& l) {
auto u = unique_ptr<Library::Vtable>(new Library::Vtable("string"));
l.registerVtable(move(u));
l.registerFactory("string", []()->std::shared_ptr<Wires::TypedData> { return std::make_shared<Wires::Data<string>>(); });
}
} // Std
} // Landru
|
#include "sfr_list.h"
SFR_List::SFR_List(QObject *parent) :
QObject(parent)
{
}
SFR_List::Add(SFR_Object *sfr)
{
SFR_List::sfrList.push_back(sfr);
// TODO: Добавить проверку зависимостей и добавление отсутствующих в списке ФТБ.
}
|
# include <iostream>
using namespace std;
int main()
{
int num;
cin >> num;
int *arr = (int *)malloc(num * sizeof(int));
for(int i = 0; i < num; i += 1) {
cin >> arr[i];
}
for(int i = num; i > 0; i -= 1) {
cout << arr[i-1] << endl;
}
return 0;
}
|
#include "monstro2.h"
monstro2::monstro2()
{
for(int i = 0; i < 20; i++) {
shapes[i] = new sphere();
shapes[i]->updateMesh(20, 20, 20);
shapes[i]->updateMaterial(0, 255, 0);
}
}
void monstro2::update()
{
float value = shapes[NUI_SKELETON_POSITION_HAND_LEFT]->position.x - shapes[NUI_SKELETON_POSITION_HAND_RIGHT]->position.x;
float size = abs(value)/3.f;
for(int i = 0; i < 20; i++) {
shapes[i]->updateMesh(size, size, size);
}
}
|
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHVECALGO_H
#define INCLUDED_IMATHVECALGO_H
//-------------------------------------------------------------------------
//
// This file contains algorithms applied to or in conjunction
// with points (Imath::Vec2 and Imath::Vec3).
// The assumption made is that these functions are called much
// less often than the basic point functions or these functions
// require more support classes.
//
//-------------------------------------------------------------------------
#include "ImathVec.h"
#include "ImathLimits.h"
namespace Imath {
//-----------------------------------------------------------------
// Find the projection of vector t onto vector s (Vec2, Vec3, Vec4)
//-----------------------------------------------------------------
template <class Vec> Vec project (const Vec &s, const Vec &t);
//------------------------------------------------
// Find a vector that is perpendicular to s and
// in the same plane as s and t (Vec2, Vec3, Vec4)
//------------------------------------------------
template <class Vec> Vec orthogonal (const Vec &s, const Vec &t);
//-----------------------------------------------
// Find the direction of a ray s after reflection
// off a plane with normal t (Vec2, Vec3, Vec4)
//-----------------------------------------------
template <class Vec> Vec reflect (const Vec &s, const Vec &t);
//--------------------------------------------------------------------
// Find the vertex of triangle (v0, v1, v2) that is closest to point p
// (Vec2, Vec3, Vec4)
//--------------------------------------------------------------------
template <class Vec> Vec closestVertex (const Vec &v0,
const Vec &v1,
const Vec &v2,
const Vec &p);
//---------------
// Implementation
//---------------
template <class Vec>
Vec
project (const Vec &s, const Vec &t)
{
Vec sNormalized = s.normalized();
return sNormalized * (sNormalized ^ t);
}
template <class Vec>
Vec
orthogonal (const Vec &s, const Vec &t)
{
return t - project (s, t);
}
template <class Vec>
Vec
reflect (const Vec &s, const Vec &t)
{
return s - typename Vec::BaseType(2) * (s - project(t, s));
}
template <class Vec>
Vec
closestVertex(const Vec &v0,
const Vec &v1,
const Vec &v2,
const Vec &p)
{
Vec nearest = v0;
typename Vec::BaseType neardot = (v0 - p).length2();
typename Vec::BaseType tmp = (v1 - p).length2();
if (tmp < neardot)
{
neardot = tmp;
nearest = v1;
}
tmp = (v2 - p).length2();
if (tmp < neardot)
{
neardot = tmp;
nearest = v2;
}
return nearest;
}
} // namespace Imath
#endif
|
#include "skipUicGen.hpp"
#include "skipUicNoGen1.hpp"
#include "skipUicNoGen2.hpp"
int main(int, char**)
{
skipGen();
skipNoGen1();
skipNoGen2();
return 0;
}
// -- Function definitions
void ui_nogen1()
{
}
void ui_nogen2()
{
}
|
#ifndef CHASSIS_H
#define CHASSIS_H
//#include "Infantry_Funtion.h"
//#include "main.h"
#include "FreeRTOS.h"
#include "PID.h"
#include <main.h>
#include "drv_can.h"
#include "motor.h"
#include "arm_math.h"
#include "math.h"
extern CAN_HandleTypeDef hcan1;
extern CAN_HandleTypeDef hcan2;
extern Motor_GM6020 pitchyawMotor[2];
enum E_ChassisState
{
LOST_C = 0,
NORMAL_C = 1,
UNLIMITED_C = 2,
};
enum E_MoveMode
{
RUN_C = 0,
ROTATE_C = 1,
};
enum E_CtrlMode
{
REMOTE_CTRL_C = 0,
KEY_BOARD_C = 1,
};
class C_Chassis
{
public:
void Control(E_ChassisState chassis_stste,
E_MoveMode move_mode,
E_CtrlMode ctrl_mode,
float y_data,
float x_data,
float r_data,
float y_back=0 ,
float x_back=0 ); //使用遥控器控制只需要一组x y参数,键鼠需要两组
void Reset();
void maxSpeedUpdate();
void msgSend();
void setMaxSpeed(int16_t max_Y, int16_t max_X, int16_t max_R);
void rSpeedLimit();
void targetUpdate();
void angleCnt();
void pid_init(float kp,float ki,float kd, float ki_max,float out_max);
int16_t speed_Y,speed_X,speed_R;
int16_t speed_Y_last = 0,speed_X_last = 0,speed_R_last = 0;
int16_t maxSpeed_Y,maxSpeed_X,maxSpeed_R,sourcePowerMax;
int16_t velocity[4]; //键盘速度临时数据
int16_t rotateCnt; //记录云台旋转圈数
E_ChassisState chassisMode;
E_MoveMode moveMode;
E_CtrlMode ctrlMode;
bool rewrite_UI;
bool magazinemode;
bool isLandMode;
myPID chassisYawAngle;
uint8_t rad = 180;
uint8_t chassis_states = 0;
float temp, pi=3.1415926;
float rec_Y, rec_X, rec_R, rec_Y_Key, rec_X_Key;
uint8_t snipermode = 0;
uint8_t finalMode = 0;
uint8_t fuckMode = 0;
uint8_t GGMode = 0;
int8_t rodirection = 1;
uint8_t maxSpin = 0;
};
extern C_Chassis Chassis;
#endif
|
#include <stdio.h>
#define GC_DEBUG
#include "gc_cpp.h"
#define CHECK_LEAKS() GC_gcollect()
class Foo: public gc{};
int main() {
GC_find_leak = 1;
Foo *f;
while(1){
f =new Foo; //t2.cpp line10
// delete f;
CHECK_LEAKS();
}
}
|
#include <iostream>
using namespace std;
template<class...Args>
struct type_list;
template<>
struct type_list<>
{
};
template<class T>
struct type_list<T>
{
using first = T;
using remain = type_list<>;
};
template<class T, class...Args>
struct type_list<T, Args...>
{
using first = T;
using remain = type_list<Args...>;
};
template<class T>
struct type_list_first;
template<class T, class...Args>
struct type_list_first<type_list<T, Args...>>
{
using type = T;
};
template<class T>
struct type_list_last;
template<class T>
struct type_list_last<type_list<T>>
{
using type = T;
};
template<class T, class...Args>
struct type_list_last<type_list<T, Args...>>
{
using type = typename type_list_last<type_list<Args...>>::type;
};
template<class T, class...Args>
struct type_list_push_front;
template<class...Args1, class...Args2>
struct type_list_push_front<type_list<Args1...>, Args2...>
{
using type = type_list<Args2..., Args1...>;
};
template<class T>
struct type_list_pop_front;
template<class T, class...Args>
struct type_list_pop_front<type_list<T, Args...>>
{
using type = type_list<Args...>;
};
template<class T, class...Args>
struct type_list_push_back;
template<class...Args1, class...Args2>
struct type_list_push_back<type_list<Args1...>, Args2...>
{
using type = type_list<Args1..., Args2...>;
};
template<class...Args>
struct type_list_cat;
template<class...Args1, class...Args2>
struct type_list_cat<type_list<Args1...>, type_list<Args2...>>
{
using type = type_list<Args1..., Args2...>;
};
template<class...Args1, class...Args2, class...Tuples>
struct type_list_cat<type_list<Args1...>, type_list<Args2...>, Tuples...>
{
using type = typename type_list_cat< type_list<Args1..., Args2...>, Tuples...>::type;
};
template<class T>
struct type_list_reverse;
template<>
struct type_list_reverse<type_list<>>
{
using type = type_list<>;
};
template<class T>
struct type_list_reverse<type_list<T>>
{
using type = type_list<T>;
};
template<class T, class...Args>
struct type_list_reverse<type_list<T, Args...>>
{
using type = typename type_list_push_back< typename type_list_reverse<typename type_list<Args...>>::type, T>::type;
};
template<class T>
struct type_list_pop_back;
template<class...Args>
struct type_list_pop_back<type_list<Args...>>
{
using type = typename type_list_reverse< typename type_list_pop_front< typename type_list_reverse< type_list<Args...> >::type >::type >::type;
};
template<class Tup, int n, class T>
struct type_list_insert;
template<class...Args, int n, class T, class First>
struct type_list_insert<type_list<First, Args...>, n, T>
{
template<unsigned n>
struct process
{
using type = typename type_list_push_front< typename type_list_insert< type_list<Args...>, n - 1, T >::type, First >::type;
};
template<>
struct process<0>
{
using type = type_list<T, First, Args...>;
};
using type = typename process<n>::type;
};
template<class Tup, int n>
struct type_list_get;
template<class T, class...Args>
struct type_list_get<type_list<T, Args...>, 0>
{
using type = T;
};
template<class T, class...Args, int n>
struct type_list_get<type_list<T, Args...>, n>
{
using type = typename type_list_get<type_list<Args...>, n - 1>::type;
};
template<class Tup, class T>
struct type_list_find;
template<class T>
struct type_list_find<type_list<>, T>
{
static const size_t value;
};
template<class T, class...Args, class First>
struct type_list_find<type_list<First, Args...>, T>
{
private:
template<class T1, class T2>
struct process
{
static const size_t value = type_list_find<type_list<Args...>, T>::value + 1;
};
template<class T1>
struct process<T1, T1>
{
static const size_t value = 0;
};
public:
static const size_t value = process<First, T>::value;
};
template<class Tup, size_t n>
struct type_list_right;
template<size_t n, class First, class...Args>
struct type_list_right<type_list<First, Args...>, n>
{
private:
template<size_t i>
struct process
{
using type = typename type_list_right<type_list<Args...>, i - 1>::type;
};
template<>
struct process<0>
{
using type = type_list<Args...>;
};
public:
using type = typename process<n>::type;
};
template<class Tup, size_t n>
struct type_list_left;
template<size_t n, class...Args>
struct type_list_left<type_list<Args...>, n>
{
private:
template<size_t i>
struct process
{
using temp = typename process<i - 1>::type;
using type = typename type_list_push_front<
temp,
typename type_list_get< type_list<Args...>, i >::type
>::type;
};
template<>
struct process<0>
{
using type = type_list<typename type_list_first< type_list<Args...> >::type>;
};
public:
using type = typename process<n-1>::type;
};
template<class Tup, size_t n>
struct type_list_erase;
template<class...Args, size_t n>
struct type_list_erase<type_list<Args...>, n>
{
using type = typename type_list_cat<
typename type_list_left<type_list<Args...>, n>::type,
typename type_list_right<type_list<Args...>, n>::type
>::type;
};
template<class Tup, size_t n, class T>
struct type_list_assign;
template<class...Args, size_t n, class T>
struct type_list_assign<type_list<Args...>, n, T>
{
using type = typename type_list_cat<
typename type_list_left<type_list<Args...>, n>::type,
type_list<T>,
typename type_list_right<type_list<Args...>, n>::type
>::type;
};
template<class T>
struct type_list_size;
template<>
struct type_list_size<type_list<>>
{
static const size_t value = 0;
};
template<class T, class...Args>
struct type_list_size<type_list<T, Args...>>
{
static const size_t value = type_list_size<Args...> +1;
};
template<class T, template<class Elem1, class Elem2> class CompareFunc>
struct type_list_sort;
template<template<class Elem1, class Elem2> class CompareFunc>
struct type_list_sort<type_list<>, CompareFunc>
{
using type = type_list<>;
};
template<class T, template<class Elem1, class Elem2> class CompareFunc>
struct type_list_sort<type_list<T>, CompareFunc>
{
using type = type_list<T>;
};
template<class T1, class T2, template<class Elem1, class Elem2> class CompareFunc>
struct type_list_sort<type_list<T1, T2>, CompareFunc>
{
private:
template<bool less>
struct process
{
using type = type_list<T1, T2>;
};
template<>
struct process<false>
{
using type = type_list<T2, T1>;
};
public:
using type = typename process< CompareFunc<T1, T2>::value >::type;
};
template<class T1, class T2, class...Args, template<class Elem1, class Elem2> class CompareFunc>
struct type_list_sort<type_list<T1, T2, Args...>, CompareFunc>
{
private:
using first_pair = typename type_list_sort< type_list<T1, T2>, CompareFunc >::type;
using type_list_first_pair_sorted = typename type_list_push_front<
typename type_list_sort< type_list<typename first_pair::remain::first, Args...>, CompareFunc >::type,
typename type_list_first<first_pair>::type
>::type;
public:
using type = typename type_list_push_back <
typename type_list_sort < typename type_list_pop_back<type_list_first_pair_sorted>::type, CompareFunc> ::type,
typename type_list_last<type_list_first_pair_sorted>::type
>::type;
};
template<class T1, class T2>
struct compare_sizeof
{
private:
template<class T>
struct r_size
{
static const size_t value = sizeof(T);
};
template<>
struct r_size<void>
{
static const size_t value = 0;
};
template<class T>
struct r_size<T &>
{
static const size_t value = 0;
};
template<class T>
struct r_size<T &&>
{
static const size_t value = 0;
};
template<class FuncRet, class...FuncArgs>
struct r_size<FuncRet(FuncArgs...)>
{
static const size_t value = 0;
};
public:
static const bool value = r_size<T1>::value < r_size<T2>::value;
};
template<class T>
struct type_list_sort_sizeof : public type_list_sort<T, compare_sizeof> {};
template<class T1, class T2>
struct compare_value
{
static const bool value = T1::value < T1::value;
};
int main()
{
typedef type_list<double, int, char, short, char[233], short[3], int&, void> Tup;
typedef type_list_sort_sizeof<Tup>::type Tup2;
cout << typeid(Tup).name() << endl;
cout << typeid(Tup2).name() << endl;
}
|
// Copyright 2017 Elias Kosunen
//
// 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
//
// https://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.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
#ifndef SCN_READER_INT_H
#define SCN_READER_INT_H
#include "../util/math.h"
#include "common.h"
namespace scn {
SCN_BEGIN_NAMESPACE
namespace detail {
template <typename T>
struct integer_scanner : common_parser {
static_assert(std::is_integral<T>::value,
"integer_scanner requires an integral type");
friend struct simple_integer_scanner<T>;
bool skip_preceding_whitespace()
{
// if format_options == single_code_unit,
// then we're scanning a char -> don't skip
return format_options != single_code_unit;
}
template <typename ParseCtx>
error parse(ParseCtx& pctx)
{
using char_type = typename ParseCtx::char_type;
format_options = 0;
int custom_base = 0;
auto each = [&](ParseCtx& p, bool& parsed) -> error {
parsed = false;
auto ch = pctx.next_char();
if (ch == detail::ascii_widen<char_type>('B')) {
// Custom base
p.advance_char();
if (SCN_UNLIKELY(!p)) {
return {error::invalid_format_string,
"Unexpected format string end"};
}
if (SCN_UNLIKELY(p.check_arg_end())) {
return {error::invalid_format_string,
"Unexpected argument end"};
}
ch = p.next_char();
const auto zero = detail::ascii_widen<char_type>('0'),
nine = detail::ascii_widen<char_type>('9');
integer_type_for_char<char_type> tmp = 0;
if (ch < zero || ch > nine) {
return {error::invalid_format_string,
"Invalid character after 'B', "
"expected digit"};
}
tmp = static_cast<integer_type_for_char<char_type>>(
p.next_char() - zero);
if (tmp < 1) {
return {error::invalid_format_string,
"Invalid base, must be between 2 and 36"};
}
p.advance_char();
if (!p) {
return {error::invalid_format_string,
"Unexpected end of format string"};
}
if (p.check_arg_end()) {
custom_base = static_cast<uint8_t>(tmp);
parsed = true;
return {};
}
ch = p.next_char();
if (ch < zero || ch > nine) {
return {error::invalid_format_string,
"Invalid character after 'B', "
"expected digit"};
}
tmp *= 10;
tmp += static_cast<integer_type_for_char<char_type>>(
ch - zero);
if (tmp < 2 || tmp > 36) {
return {error::invalid_format_string,
"Invalid base, must be between 2 and 36"};
}
custom_base = static_cast<uint8_t>(tmp);
parsed = true;
pctx.advance_char();
return {};
}
return {};
};
array<char_type, 9> options{{// decimal
ascii_widen<char_type>('d'),
// binary
ascii_widen<char_type>('b'),
// octal
ascii_widen<char_type>('o'),
// hex
ascii_widen<char_type>('x'),
// detect base
ascii_widen<char_type>('i'),
// unsigned decimal
ascii_widen<char_type>('u'),
// code unit
ascii_widen<char_type>('c'),
// localized digits
ascii_widen<char_type>('n'),
// thsep
ascii_widen<char_type>('\'')}};
bool flags[9] = {false};
auto e = parse_common(
pctx, span<const char_type>{options.begin(), options.end()},
span<bool>{flags, 9}, each);
if (!e) {
return e;
}
int base_flags_set = int(flags[0]) + int(flags[1]) +
int(flags[2]) + int(flags[3]) +
int(flags[4]) + int(flags[5]) +
int(custom_base != 0);
if (SCN_UNLIKELY(base_flags_set > 1)) {
return {error::invalid_format_string,
"Up to one base flags ('d', 'i', 'u', 'b', 'o', "
"'x', 'B') allowed"};
}
else if (base_flags_set == 0) {
// Default:
// 'c' for CharT
// 'd' otherwise
if (std::is_same<T, typename ParseCtx::char_type>::value) {
format_options = single_code_unit;
}
else {
base = 10;
}
}
else if (custom_base != 0) {
// B__
base = static_cast<uint8_t>(custom_base);
}
else if (flags[0]) {
// 'd' flag
base = 10;
}
else if (flags[1]) {
// 'b' flag
base = 2;
format_options |= allow_base_prefix;
}
else if (flags[2]) {
// 'o' flag
base = 8;
format_options |= allow_base_prefix;
}
else if (flags[3]) {
// 'x' flag
base = 16;
format_options |= allow_base_prefix;
}
else if (flags[4]) {
// 'i' flag
base = 0;
}
else if (flags[5]) {
// 'u' flag
base = 10;
format_options |= only_unsigned;
}
// n set, implies L
if (flags[7]) {
common_options |= localized;
format_options |= localized_digits;
}
if ((format_options & localized_digits) != 0 &&
(base != 0 && base != 10 && base != 8 && base != 16)) {
return {error::invalid_format_string,
"Localized integers can only be scanned in "
"bases 8, 10 and 16"};
}
// thsep flag
if (flags[8]) {
format_options |= allow_thsep;
}
// 'c' flag -> no other options allowed
if (flags[6]) {
if (!(format_options == 0 ||
format_options == single_code_unit) ||
base_flags_set != 0) {
return {error::invalid_format_string,
"'c' flag cannot be used in conjunction with "
"any other flags"};
}
format_options = single_code_unit;
}
return {};
}
template <typename Context>
error scan(T& val, Context& ctx)
{
using char_type = typename Context::char_type;
auto do_parse_int = [&](span<const char_type> s) -> error {
T tmp = 0;
expected<std::ptrdiff_t> ret{0};
if (SCN_UNLIKELY((format_options & localized_digits) !=
0)) {
SCN_CLANG_PUSH_IGNORE_UNDEFINED_TEMPLATE
int b{base};
auto r = parse_base_prefix<char_type>(s, b);
if (!r) {
return r.error();
}
if (b == -1) {
// -1 means we read a '0'
tmp = 0;
return {};
}
if (b != 10 && base != b && base != 0) {
return {error::invalid_scanned_value,
"Invalid base prefix"};
}
if (base == 0) {
base = static_cast<uint8_t>(b);
}
if (base != 8 && base != 10 && base != 16) {
return {error::invalid_scanned_value,
"Localized values have to be in base "
"8, 10 or 16"};
}
auto it = r.value();
std::basic_string<char_type> str(to_address(it),
s.size());
ret = ctx.locale().get_localized().read_num(
tmp, str, static_cast<int>(base));
if (tmp < T{0} &&
(format_options & only_unsigned) != 0) {
return {error::invalid_scanned_value,
"Parsed negative value when type was 'u'"};
}
SCN_CLANG_POP_IGNORE_UNDEFINED_TEMPLATE
}
else {
SCN_CLANG_PUSH_IGNORE_UNDEFINED_TEMPLATE
ret = _parse_int(tmp, s);
SCN_CLANG_POP_IGNORE_UNDEFINED_TEMPLATE
}
if (!ret) {
return ret.error();
}
if (ret.value() != s.ssize()) {
auto pb =
putback_n(ctx.range(), s.ssize() - ret.value());
if (!pb) {
return pb;
}
}
val = tmp;
return {};
};
if (format_options == single_code_unit) {
SCN_MSVC_PUSH
SCN_MSVC_IGNORE(4127) // conditional expression is constant
if (sizeof(T) < sizeof(char_type)) {
// sizeof(char_type) > 1 -> wide range
// Code unit might not fit
return error{error::invalid_operation,
"Cannot read this type as a code unit "
"from a wide range"};
}
SCN_MSVC_POP
auto ch = read_code_unit(ctx.range());
if (!ch) {
return ch.error();
}
val = static_cast<T>(ch.value());
return {};
}
SCN_MSVC_PUSH
SCN_MSVC_IGNORE(4127) // conditional expression is constant
if ((std::is_same<T, char>::value ||
std::is_same<T, wchar_t>::value) &&
!std::is_same<T, char_type>::value) {
// T is a character type, but not char_type:
// Trying to read a char from a wide range, or wchar_t from
// a narrow one
// Reading a code unit is allowed, however
return error{error::invalid_operation,
"Cannot read a char from a wide range, or a "
"wchar_t from a narrow one"};
}
SCN_MSVC_POP
std::basic_string<char_type> buf{};
span<const char_type> bufspan{};
auto e = _read_source(
ctx, buf, bufspan,
std::integral_constant<
bool, Context::range_type::is_contiguous>{});
if (!e) {
return e;
}
return do_parse_int(bufspan);
}
enum format_options_type : uint8_t {
// "n" option -> localized digits and digit grouping
localized_digits = 1,
// "'" option -> accept thsep
// if "L" use locale, default=','
allow_thsep = 2,
// "u" option -> don't allow sign
only_unsigned = 4,
// Allow base prefix (e.g. 0B and 0x)
allow_base_prefix = 8,
// "c" option -> scan a code unit
single_code_unit = 16,
};
uint8_t format_options{default_format_options()};
// 0 = detect base
// Otherwise [2,36]
uint8_t base{0};
private:
static SCN_CONSTEXPR14 uint8_t default_format_options()
{
SCN_MSVC_PUSH
SCN_MSVC_IGNORE(4127) // conditional expression is constant
if (std::is_same<T, char>::value ||
std::is_same<T, wchar_t>::value) {
return single_code_unit;
}
return 0;
SCN_MSVC_POP
}
template <typename Context, typename Buf, typename CharT>
error _read_source(Context& ctx,
Buf& buf,
span<const CharT>& s,
std::false_type)
{
auto do_read = [&](Buf& b) -> error {
auto outputit = std::back_inserter(b);
auto is_space_pred = make_is_space_predicate(
ctx.locale(), (common_options & localized) != 0,
field_width);
auto e = read_until_space(ctx.range(), outputit,
is_space_pred, false);
if (!e && b.empty()) {
return e;
}
return {};
};
if (SCN_LIKELY((format_options & allow_thsep) == 0)) {
auto e = do_read(buf);
if (!e) {
return e;
}
s = make_span(buf.data(), buf.size());
return {};
}
Buf tmp;
auto e = do_read(tmp);
if (!e) {
return e;
}
auto thsep = ctx.locale()
.get((common_options & localized) != 0)
.thousands_separator();
auto it = tmp.begin();
for (; it != tmp.end(); ++it) {
if (*it == thsep) {
for (auto it2 = it; ++it2 != tmp.end();) {
*it++ = SCN_MOVE(*it2);
}
break;
}
}
auto n =
static_cast<std::size_t>(std::distance(tmp.begin(), it));
if (n == 0) {
return {error::invalid_scanned_value,
"Only a thousands separator found"};
}
buf = SCN_MOVE(tmp);
s = make_span(buf.data(), n);
return {};
}
template <typename Context, typename Buf, typename CharT>
error _read_source(Context& ctx,
Buf& buf,
span<const CharT>& s,
std::true_type)
{
if (SCN_UNLIKELY((format_options & allow_thsep) != 0)) {
return _read_source(ctx, buf, s, std::false_type{});
}
auto ret = read_zero_copy(
ctx.range(), field_width != 0
? static_cast<std::ptrdiff_t>(field_width)
: ctx.range().size());
if (!ret) {
return ret.error();
}
s = ret.value();
return {};
}
template <typename CharT>
expected<typename span<const CharT>::iterator> parse_base_prefix(
span<const CharT> s,
int& b) const;
template <typename CharT>
expected<std::ptrdiff_t> _parse_int(T& val, span<const CharT> s);
template <typename CharT>
expected<typename span<const CharT>::iterator> _parse_int_impl(
T& val,
bool minus_sign,
span<const CharT> buf) const;
};
// instantiate
template struct integer_scanner<signed char>;
template struct integer_scanner<short>;
template struct integer_scanner<int>;
template struct integer_scanner<long>;
template struct integer_scanner<long long>;
template struct integer_scanner<unsigned char>;
template struct integer_scanner<unsigned short>;
template struct integer_scanner<unsigned int>;
template struct integer_scanner<unsigned long>;
template struct integer_scanner<unsigned long long>;
template struct integer_scanner<char>;
template struct integer_scanner<wchar_t>;
template <typename T>
template <typename CharT>
expected<typename span<const CharT>::iterator>
simple_integer_scanner<T>::scan(span<const CharT> buf,
T& val,
int base,
uint16_t flags)
{
SCN_EXPECT(buf.size() != 0);
integer_scanner<T> s{};
s.base = static_cast<uint8_t>(base);
s.format_options = flags & 0xffu;
s.common_options = static_cast<uint8_t>(flags >> 8u);
SCN_CLANG_PUSH_IGNORE_UNDEFINED_TEMPLATE
auto n = s._parse_int(val, buf);
SCN_CLANG_POP_IGNORE_UNDEFINED_TEMPLATE
if (!n) {
return n.error();
}
return buf.begin() + n.value();
}
template <typename T>
template <typename CharT>
expected<typename span<const CharT>::iterator>
simple_integer_scanner<T>::scan_lower(span<const CharT> buf,
T& val,
int base,
uint16_t flags)
{
SCN_EXPECT(buf.size() != 0);
SCN_EXPECT(base > 0);
integer_scanner<T> s{};
s.base = static_cast<uint8_t>(base);
s.format_options = flags & 0xffu;
s.common_options = static_cast<uint8_t>(flags >> 8u);
bool minus_sign = false;
if (buf[0] == ascii_widen<CharT>('-')) {
buf = buf.subspan(1);
minus_sign = true;
}
SCN_CLANG_PUSH_IGNORE_UNDEFINED_TEMPLATE
return s._parse_int_impl(val, minus_sign, buf);
SCN_CLANG_POP_IGNORE_UNDEFINED_TEMPLATE
}
} // namespace detail
SCN_END_NAMESPACE
} // namespace scn
#if defined(SCN_HEADER_ONLY) && SCN_HEADER_ONLY && !defined(SCN_READER_INT_CPP)
#include "reader_int.cpp"
#endif
#endif
|
/**
* @file DTWRecognizer.h
* @brief Gesture Recognition Algorithm using DTW(Dynamic Time Warping) Algorithm
* @author Dae-Hyun Lee
*/
#if !defined(__DTW_RECOGNIZER_H__)
#define __DTW_RECOGNIZER_H__
#include <vector>
#include "Singleton.h"
#include "Recognition.h"
#define dtwRecognizer (DTWRecognizer::instance())
class DTWRecognizer : public SisaSingleton<DTWRecognizer>
{
public:
/**
* @brief 인식하고자 하는 recognition 을 등록함. decideGesture를 이용하여 제스쳐를 인식하기 전에, 미리 인식하고자 하는 제스쳐 집합(패턴 DB)을 등록해야 함.
* @param[in] Recognition 포인터
* @see decideGesture, deleteRecognition
*/
void registerRecognition(Recognition *recog);
/**
* @brief 현재 등록되어 있는 recognition(제스쳐 집합)들 중에서, 지정된 이름의 recognition을 제거함.
* @param[in] 제거하고자 하는 recognition 이름
* @see decideGesture, registerRecognition
*/
void deleteRecognition(std::string& recogName);
/**
* @brief DTW 알고리즘을 이용하여 제스쳐를 인식함.
* @param[in] 컨트롤러를 통해서 입력받은 제스쳐 벡터
* @return 인식된 제스쳐 이름
* @see decideGesture, registerRecognition
*/
std::string& DTWRecognizer::decideGesture(std::vector<Ogre::Vector3>& inputPattern);
/**
* @brief DTW 알고리즘을 이용하여 제스쳐를 인식함. 패턴 DB를 외부에서 제공함.
* @param[in] 외부에서 제공하는 패턴 DB
* @param[in] 컨트롤러를 통해서 입력받은 제스쳐 벡터
*/
std::string& DTWRecognizer::decideGesture(std::vector<Recognition *>& recognitionArray, std::vector<Ogre::Vector3>& inputPattern);
private:
std::vector<Recognition *> mRecognitionArray;
};
#endif // __DTW_RECOGNIZER_H__
|
/*
* Copyright (c) 2016, The Regents of the University of California (Regents).
* 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.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Author: Erik Nelson ( eanelson@eecs.berkeley.edu )
*/
///////////////////////////////////////////////////////////////////////////////
//
// Model a collision between a 3D ray and a lens. An incoming ray (assuming no
// total internal reflection) will have two collisions with the lens. Therefore
// a collision can be modeled as a set of three rays: one incoming ray, one
// internal ray, and one outgoing ray.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef LENS_LENS_COLLISION_H
#define LENS_LENS_COLLISION_H
#include <lens/lens.h>
#include <raytracing/ray.h>
class LensCollision {
public:
LensCollision();
~LensCollision();
// Calculate collisions between a specified ray and a lens, storing collision
// details internally. Return false if there is no collision between the ray
// and lens.
bool Compute(const Ray& incoming, const Lens& lens);
// Getters and setters.
const Ray& GetIncomingRay() const;
const Ray& GetInternalRay() const;
const Ray& GetOutgoingRay() const;
const Lens& GetLens() const;
double GetIncomingDistance() const;
double GetInternalDistance() const;
void SetIncomingRay(const Ray& incoming);
void SetInternalRay(const Ray& internal);
void SetOutgoingRay(const Ray& outgoing);
void SetLens(const Lens& lens);
private:
// Check if a ray will intersect the top face of the lens first, or the bottom
// face.
bool RayIntersectsTopFaceFirst(const Ray& ray, const Lens& lens) const;
// Check if the input ray intersects the lens face specified by the input
// parameter 'top_face'. If an intersection is found, distance will be set as
// the distance from the ray's origin to the collision.
bool RayIntersectsLensFace(bool top_face,
bool first_face,
const Ray& ray,
const Lens& lens,
double* distance) const;
// Given an input ray and a lens, use Snell's law to compute an output
// refracted ray.
Ray GetRefractedRay(bool top_face,
bool first_face,
double distance,
const Ray& in,
const Lens& lens);
// Three rays model a collision.
Ray incoming_;
Ray internal_;
Ray outgoing_;
// Distance along incoming and internal rays before collision.
double incoming_distance_;
double internal_distance_;
// Copy the lens that this collision refers to.
Lens lens_;
};
#endif
|
// Created on: 1997-03-17
// Created by: Yves FRICAUD
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TNaming_HeaderFile
#define _TNaming_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopTools_DataMapOfShapeShape.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopTools_HArray1OfShape.hxx>
#include <TDF_IDList.hxx>
#include <Standard_OStream.hxx>
#include <TNaming_Evolution.hxx>
#include <TNaming_NameType.hxx>
class TDF_Label;
class TopLoc_Location;
class gp_Trsf;
class TNaming_NamedShape;
class TopoDS_Shape;
class TopoDS_Face;
class TopoDS_Wire;
class TopoDS_Solid;
class TopoDS_Shell;
//! A topological attribute can be seen as a hook
//! into the topological structure. To this hook,
//! data can be attached and references defined.
//! It is used for keeping and access to
//! topological objects and their evolution. All
//! topological objects are stored in the one
//! user-protected TNaming_UsedShapes
//! attribute at the root label of the data
//! framework. This attribute contains map with all
//! topological shapes, used in this document.
//! To all other labels TNaming_NamedShape
//! attribute can be added. This attribute contains
//! references (hooks) to shapes from the
//! TNaming_UsedShapes attribute and evolution
//! of these shapes. TNaming_NamedShape
//! attribute contains a set of pairs of hooks: old
//! shape and new shape (see the figure below).
//! It allows not only get the topological shapes by
//! the labels, but also trace evolution of the
//! shapes and correctly resolve dependent
//! shapes by the changed one.
//! If shape is just-created, then the old shape for
//! accorded named shape is an empty shape. If
//! a shape is deleted, then the new shape in this named shape is empty.
//! Different algorithms may dispose sub-shapes
//! of the result shape at the individual label depending on necessity:
//! - If a sub-shape must have some extra attributes (material of
//! each face or color of each edge). In this case a specific sub-shape is
//! placed to the separate label (usually, sub-label of the result shape label)
//! with all attributes of this sub-shape.
//! - If topological naming is needed, a necessary and sufficient
//! (for selected sub-shapes identification) set of sub-shapes is
//! placed to the child labels of the result
//! shape label. As usual, as far as basic solids and closed shells are
//! concerned, all faces of the shape are disposed. Edges and vertices
//! sub-shapes can be identified as intersection of contiguous faces.
//! Modified/generated shapes may be placed to one named shape and
//! identified as this named shape and source named shape that also can be
//! identified with used algorithms.
//! TNaming_NamedShape may contain a few
//! pairs of hooks with the same evolution. In this
//! case topology shape, which belongs to the
//! named shape, is a compound of new shapes.
//! The data model contains both the topology
//! and the hooks, and functions handle both
//! topological entities and hooks. Consider the
//! case of a box function, which creates a solid
//! with six faces and six hooks. Each hook is
//! attached to a face. If you want, you can also
//! have this function create hooks for edges and
//! vertices as well as for faces. For the sake of
//! simplicity though, let's limit the example.
//! Not all functions can define explicit hooks for
//! all topological entities they create, but all
//! topological entities can be turned into hooks
//! when necessary. This is where topological naming is necessary.
class TNaming
{
public:
DEFINE_STANDARD_ALLOC
//! Subtituter les shapes sur les structures de source
//! vers cible
Standard_EXPORT static void Substitute (const TDF_Label& labelsource, const TDF_Label& labelcible, TopTools_DataMapOfShapeShape& mapOldNew);
//! Mise a jour des shapes du label et de ses fils en
//! tenant compte des substitutions decrite par
//! mapOldNew.
//!
//! Warning: le remplacement du shape est fait dans tous
//! les attributs qui le contiennent meme si ceux
//! ci ne sont pas associees a des sous-labels de <Label>.
Standard_EXPORT static void Update (const TDF_Label& label, TopTools_DataMapOfShapeShape& mapOldNew);
//! Application de la Location sur les shapes du label
//! et de ses sous labels.
Standard_EXPORT static void Displace (const TDF_Label& label, const TopLoc_Location& aLocation, const Standard_Boolean WithOld = Standard_True);
//! Remplace les shapes du label et des sous-labels
//! par des copies.
Standard_EXPORT static void ChangeShapes (const TDF_Label& label, TopTools_DataMapOfShapeShape& M);
//! Application de la transformation sur les shapes du
//! label et de ses sous labels.
//! Warning: le remplacement du shape est fait dans tous
//! les attributs qui le contiennent meme si ceux
//! ci ne sont pas associees a des sous-labels de <Label>.
Standard_EXPORT static void Transform (const TDF_Label& label, const gp_Trsf& aTransformation);
//! Replicates the named shape with the transformation <T>
//! on the label <L> (and sub-labels if necessary)
//! (TNaming_GENERATED is set)
Standard_EXPORT static void Replicate (const Handle(TNaming_NamedShape)& NS, const gp_Trsf& T, const TDF_Label& L);
//! Replicates the shape with the transformation <T>
//! on the label <L> (and sub-labels if necessary)
//! (TNaming_GENERATED is set)
Standard_EXPORT static void Replicate (const TopoDS_Shape& SH, const gp_Trsf& T, const TDF_Label& L);
//! Builds shape from map content
Standard_EXPORT static TopoDS_Shape MakeShape (const TopTools_MapOfShape& MS);
//! Find unique context of shape <S>
Standard_EXPORT static TopoDS_Shape FindUniqueContext (const TopoDS_Shape& S, const TopoDS_Shape& Context);
//! Find unique context of shape <S>,which is pure concatenation
//! of atomic shapes (Compound). The result is concatenation of
//! single contexts
Standard_EXPORT static TopoDS_Shape FindUniqueContextSet (const TopoDS_Shape& S, const TopoDS_Shape& Context, Handle(TopTools_HArray1OfShape)& Arr);
//! Substitutes shape in source structure
Standard_EXPORT static Standard_Boolean SubstituteSShape (const TDF_Label& accesslabel, const TopoDS_Shape& From, TopoDS_Shape& To);
//! Returns True if outer wire is found and the found wire in <theWire>.
Standard_EXPORT static Standard_Boolean OuterWire (const TopoDS_Face& theFace, TopoDS_Wire& theWire);
//! Returns True if outer Shell is found and the found shell in <theShell>.
//! Print of TNaming enumeration
//! =============================
Standard_EXPORT static Standard_Boolean OuterShell (const TopoDS_Solid& theSolid, TopoDS_Shell& theShell);
//! Appends to <anIDList> the list of the attributes
//! IDs of this package. CAUTION: <anIDList> is NOT
//! cleared before use.
Standard_EXPORT static void IDList (TDF_IDList& anIDList);
//! Prints the evolution <EVOL> as a String on the
//! Stream <S> and returns <S>.
Standard_EXPORT static Standard_OStream& Print (const TNaming_Evolution EVOL, Standard_OStream& S);
//! Prints the name of name type <NAME> as a String on
//! the Stream <S> and returns <S>.
Standard_EXPORT static Standard_OStream& Print (const TNaming_NameType NAME, Standard_OStream& S);
//! Prints the content of UsedShapes private attribute as a String Table on
//! the Stream <S> and returns <S>.
Standard_EXPORT static Standard_OStream& Print (const TDF_Label& ACCESS, Standard_OStream& S);
};
#endif // _TNaming_HeaderFile
|
// https://www.boost.org/doc/libs/1_74_0/libs/tokenizer/doc/escaped_list_separator.htm
// simple_example_2.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>
int main(){
std::string csv = "Field 1,\"putting quotes around fields, allows commas\",Field 3";
boost::tokenizer<boost::escaped_list_separator<char> > tok(csv);
for(boost::tokenizer<boost::escaped_list_separator<char> >::iterator beg = tok.begin();
beg != tok.end();
++beg){
std::cout << *beg << std::endl;
}
}
|
#pragma once
#include <SFML/Graphics.hpp>
#include <string>
#include <iostream>
//using namespace sf;
class Cloud
{
private:
int m_CloudId;
sf::Texture m_Texture;
sf::Sprite m_Sprite;
float m_StartingYpos;
float m_SpriteSpeed = 0.0f;
bool m_Active;
sf::Clock clock;
sf::Time dt;
public:
Cloud(std::string backgroundPath, float x_pos, float y_pos, int cloudId);
void randomizeHeight();
void randomizeSpeed();
void move();
bool isActive();
void setActive(bool active);
float getXPos();
sf::Sprite getSprite();
};
|
//
// Created by 钟奇龙 on 2019-05-18.
//
#include <iostream>
using namespace std;
/*
* 定义点
*/
class Point{
public:
double x;
double y;
Point(double x1,double y1):x(x1),y(y1){
}
};
/*
* 定义二维向量
*/
class Vec{
public:
double x;
double y;
Vec(Point *from,Point *to){
this->x = from->x - to->x;
this->y = from->y - to->y;
}
};
/*
* 计算两个二维向量的叉积
*/
double get2DCrossedMulti(Vec *vec1, Vec *vec2){
return vec1->x * vec2->y - vec1->y * vec2->x;
}
bool isPositive(double x){
return x > 0;
}
/*
* 判断d是否在三角形abc内部
*/
bool isInside(Point *a,Point *b,Point *c,Point *d){
Vec *AB = new Vec(a,b);
Vec *BC = new Vec(b,c);
Vec *CA = new Vec(c,a);
Vec *AD = new Vec(a,d);
Vec *BD = new Vec(b,d);
Vec *CD = new Vec(c,d);
return isPositive(get2DCrossedMulti(AB,AD)) == isPositive(get2DCrossedMulti(BC,BD)) &&
isPositive(get2DCrossedMulti(CA,CD)) == isPositive(get2DCrossedMulti(BC,BD));
}
int main(){
Point *a = new Point(0,0);
Point *b = new Point(1,0);
Point *c = new Point(0.5,1);
Point *d = new Point(0.5,-0.1);
cout<<isInside(a,b,c,d)<<endl;
return 0;
}
|
#include <iostream>
#include <vector>
using std::vector;
using std::cin;
using std::cout;
int main() {
int C;
cin>>C;
vector<int> input(C);
int N = 0;
for (int i = 0; i < C; ++i) {
cin>>input[i];
if(input[i] > N){
N = input[i];
}
}
vector<int> ret(N + 1, 0);
ret[0] = 1;
ret[1] = 1;
for(int i = 2; i <= N; ++i)
{
ret[i] = ret[i - 1] + ret[i - 2];
}
for(int i = 0; i < C; ++i)
{
printf("%d\n",ret[input[i]]);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.