blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ee87fe80ce3f68338d94c0a630a257cddca1ca42 | 59418b5794f251391650d8593704190606fa2b41 | /plugin_api/em5/em5/gui/hud/buy/BuyUpgradeDataSource.h | e74b9ec211f0cb30ad638ac453f8f2d03eb6e970 | [] | no_license | JeveruBerry/emergency5_sdk | 8e5726f28123962541f7e9e4d70b2d8d5cc76cff | e5b23d905c356aab6f8b26432c72d18e5838ccf6 | refs/heads/master | 2023-08-25T12:25:19.117165 | 2018-12-18T16:55:16 | 2018-12-18T17:09:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,609 | h | // Copyright (C) 2012-2018 Promotion Software GmbH
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "em5/game/player/Player.h"
#include <Rocket/Controls/DataSource.h>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace em5
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Data grid used to display the current buyable upgrades
*/
class BuyUpgradeDataSource : public Rocket::Controls::DataSource
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
BuyUpgradeDataSource();
/**
* @brief
* Add a new buyable upgrade to table
*/
void addBuyableUpgrades(const Player::BuyOption& buyOptions, uint32 upgradeID);
/**
* @brief
* Clears the datagrid; this seems to be necessary in order to shut libRocket down properly
*/
void clear();
//[-------------------------------------------------------]
//[ Public virtual Rocket::Controls::DataSource methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Includes the "columns" StringList "title" you going to get the title.
* Includes the "columns" StringList "icons" you going to get the icon.
* Includes the "columns" StringList "info" you going to get the info text.
* Includes the "columns" StringList "cost" you going to get the cost.
* Includes the "columns" StringList "upgradeId" you going to get the upgrade ID.
*/
virtual void GetRow(Rocket::Core::StringList& row, const Rocket::Core::String& table, int rowIndex, const Rocket::Core::StringList& columns) override;
virtual int GetNumRows(const Rocket::Core::String& table) override;
//[-------------------------------------------------------]
//[ Private definitions ]
//[-------------------------------------------------------]
private:
struct BuyableUpgradeTableData
{
Rocket::Core::String mTitle;
Rocket::Core::String mIcon;
Rocket::Core::String mInfoText;
uint32 mCost;
uint32 mUpgradeId;
BuyableUpgradeTableData(const Rocket::Core::String& title, const Rocket::Core::String& icon, const Rocket::Core::String& infoText, uint32 cost, uint32 upgradeId) :
mTitle(title),
mIcon(icon),
mInfoText(infoText),
mCost(cost),
mUpgradeId(upgradeId)
{
// Nothing
}
};
typedef std::vector<BuyableUpgradeTableData> BuyableUpgradeTableDataArray;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
BuyableUpgradeTableDataArray mTableData; ///< The Information our datagrid will use to fill itself
};
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // em5
| [
"christian.ofenberg@promotion-software.de"
] | christian.ofenberg@promotion-software.de |
0c63da7e9af0390cfd5dd85b44aaf835a3f95c21 | 06a75b5612b5b41f1e5b2a5d2e42b2377f839b9e | /nbdp0418/src/tmp/ui_systemsetting.h | 7fc4f73ca3ca934069913b5b64aa69e63e5eddb7 | [] | no_license | yzz1/GitStudy | 938258650d5b2268ed02a0a5fc25a6cbbee1d3dc | e58e2800fbecc74d26278b88c2bd24d259850d5e | refs/heads/master | 2021-01-12T10:01:43.331153 | 2016-12-14T01:08:26 | 2016-12-14T01:08:26 | 76,337,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,534 | h | /********************************************************************************
** Form generated from reading UI file 'systemsetting.ui'
**
** Created: Wed May 4 11:49:55 2016
** by: Qt User Interface Compiler version 4.8.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_SYSTEMSETTING_H
#define UI_SYSTEMSETTING_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QComboBox>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QPushButton>
#include <QtGui/QScrollBar>
#include <QtGui/QTableWidget>
#include <QtGui/QToolButton>
#include <QtGui/QWidget>
#include "widgets/titlewidget.h"
QT_BEGIN_NAMESPACE
class Ui_SystemSetting
{
public:
TitleWidget *tiltewidget;
QLabel *label_7;
QWidget *controlWidget;
QToolButton *homeTBnt;
QToolButton *aboutTBtn;
QToolButton *testTBtn;
QToolButton *settingTBtn;
QWidget *widget;
QListWidget *listWidget;
QLabel *languageFocus;
QLabel *printFocus;
QLineEdit *lineEdit;
QLineEdit *lineEdit_2;
QLineEdit *lineEdit_3;
QLineEdit *lineEdit_4;
QLineEdit *lineEdit_6;
QLineEdit *lineEdit_7;
QLineEdit *lineEdit_8;
QLineEdit *lineEdit_9;
QLineEdit *lineEdit_10;
QLineEdit *lineEdit_11;
QLineEdit *lineEdit_12;
QLineEdit *lineEdit_13;
QLineEdit *lineEdit_14;
QLineEdit *lineEdit_15;
QLineEdit *lineEdit_16;
QLineEdit *lineEdit_17;
QLineEdit *lineEdit_18;
QLineEdit *lineEdit_19;
QLineEdit *lineEdit_20;
QPushButton *dateTimeButton;
QWidget *widget_2;
QComboBox *comboBox;
QListWidget *listWidget_2;
QWidget *widget_3;
QListWidget *listWidget_3;
QScrollBar *horizontalScrollBar;
QLabel *horizontalScrollBarFocus;
QWidget *widget_4;
QScrollBar *horizontalScrollBar_2;
QListWidget *listWidget_4;
QLabel *horizontalScrollBarFocus2;
QWidget *widget_5;
QLineEdit *lineEdit_5;
QListWidget *listWidget_5;
QLabel *label_8;
QWidget *widget_6;
QListWidget *listWidget_6;
QTableWidget *identificationSetting;
QLabel *label;
QLabel *label_2;
QLabel *label_3;
QLabel *label_4;
QLabel *label_5;
QLabel *label_6;
QWidget *widget_7;
QComboBox *comboBox_2;
QListWidget *listWidget_7;
void setupUi(QWidget *SystemSetting)
{
if (SystemSetting->objectName().isEmpty())
SystemSetting->setObjectName(QString::fromUtf8("SystemSetting"));
SystemSetting->resize(800, 544);
tiltewidget = new TitleWidget(SystemSetting);
tiltewidget->setObjectName(QString::fromUtf8("tiltewidget"));
tiltewidget->setGeometry(QRect(0, 0, 800, 45));
label_7 = new QLabel(tiltewidget);
label_7->setObjectName(QString::fromUtf8("label_7"));
label_7->setEnabled(false);
label_7->setGeometry(QRect(300, 10, 67, 17));
controlWidget = new QWidget(SystemSetting);
controlWidget->setObjectName(QString::fromUtf8("controlWidget"));
controlWidget->setGeometry(QRect(0, 470, 800, 72));
controlWidget->setAutoFillBackground(false);
controlWidget->setStyleSheet(QString::fromUtf8(" background-color:rgb(10,21,31);"));
homeTBnt = new QToolButton(controlWidget);
homeTBnt->setObjectName(QString::fromUtf8("homeTBnt"));
homeTBnt->setGeometry(QRect(80, 0, 141, 61));
homeTBnt->setFocusPolicy(Qt::NoFocus);
homeTBnt->setStyleSheet(QString::fromUtf8("QToolButton{\n"
" border:none;\n"
" outline: none;\n"
" color:rgb(86, 74, 74);\n"
" background: transparent;\n"
" font: 18pt \"Ubuntu\";\n"
"\n"
"}\n"
"QToolButton:focus{\n"
" color:white;\n"
"\n"
"}\n"
"\n"
""));
QIcon icon;
icon.addFile(QString::fromUtf8(":/images/home_normal"), QSize(), QIcon::Normal, QIcon::On);
icon.addFile(QString::fromUtf8(":/images/home_hover"), QSize(), QIcon::Active, QIcon::On);
icon.addFile(QString::fromUtf8(":/images/home_normal"), QSize(), QIcon::Selected, QIcon::Off);
icon.addFile(QString::fromUtf8(":/images/home_hover"), QSize(), QIcon::Selected, QIcon::On);
homeTBnt->setIcon(icon);
homeTBnt->setIconSize(QSize(56, 42));
homeTBnt->setPopupMode(QToolButton::DelayedPopup);
homeTBnt->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
aboutTBtn = new QToolButton(controlWidget);
aboutTBtn->setObjectName(QString::fromUtf8("aboutTBtn"));
aboutTBtn->setGeometry(QRect(650, 0, 131, 61));
aboutTBtn->setFocusPolicy(Qt::NoFocus);
aboutTBtn->setStyleSheet(QString::fromUtf8("QToolButton{\n"
" border:none;\n"
" outline: none;\n"
" color:rgb(86, 74, 74);\n"
" background: transparent;\n"
" font: 18pt \"Ubuntu\";\n"
"\n"
"}\n"
"QToolButton:focus{\n"
" color:white;\n"
"\n"
"}\n"
"\n"
""));
QIcon icon1;
icon1.addFile(QString::fromUtf8(":/images/System_AboutBtn_SelNo"), QSize(), QIcon::Normal, QIcon::On);
aboutTBtn->setIcon(icon1);
aboutTBtn->setIconSize(QSize(29, 29));
aboutTBtn->setPopupMode(QToolButton::DelayedPopup);
aboutTBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
testTBtn = new QToolButton(controlWidget);
testTBtn->setObjectName(QString::fromUtf8("testTBtn"));
testTBtn->setGeometry(QRect(510, 0, 111, 61));
testTBtn->setFocusPolicy(Qt::NoFocus);
testTBtn->setStyleSheet(QString::fromUtf8("QToolButton{\n"
" border:none;\n"
" outline: none;\n"
" color:rgb(86, 74, 74);\n"
" background: transparent;\n"
" font: 18pt \"Ubuntu\";\n"
" \n"
"}\n"
"QToolButton:focus{\n"
" color:white;\n"
"\n"
"\n"
"}\n"
"\n"
""));
QIcon icon2;
icon2.addFile(QString::fromUtf8(":/images/System_TestBtn_SelNo"), QSize(), QIcon::Normal, QIcon::On);
testTBtn->setIcon(icon2);
testTBtn->setIconSize(QSize(29, 29));
testTBtn->setPopupMode(QToolButton::DelayedPopup);
testTBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
settingTBtn = new QToolButton(controlWidget);
settingTBtn->setObjectName(QString::fromUtf8("settingTBtn"));
settingTBtn->setGeometry(QRect(360, 0, 121, 61));
settingTBtn->setFocusPolicy(Qt::NoFocus);
settingTBtn->setStyleSheet(QString::fromUtf8("QToolButton{\n"
" border:none;\n"
" outline: none;\n"
" color:rgb(86, 74, 74);\n"
" background: transparent;\n"
" font: 18pt \"Ubuntu\";\n"
" \n"
"}\n"
"QToolButton:focus{\n"
" color:white;\n"
"\n"
"\n"
"}\n"
""));
QIcon icon3;
icon3.addFile(QString::fromUtf8(":/images/System_SetBtn_SelYes"), QSize(), QIcon::Normal, QIcon::On);
settingTBtn->setIcon(icon3);
settingTBtn->setIconSize(QSize(27, 28));
settingTBtn->setPopupMode(QToolButton::DelayedPopup);
settingTBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
widget = new QWidget(SystemSetting);
widget->setObjectName(QString::fromUtf8("widget"));
widget->setGeometry(QRect(0, 50, 800, 40));
listWidget = new QListWidget(widget);
listWidget->setObjectName(QString::fromUtf8("listWidget"));
listWidget->setEnabled(true);
listWidget->setGeometry(QRect(40, 0, 212, 40));
listWidget->setFocusPolicy(Qt::WheelFocus);
listWidget->setStyleSheet(QString::fromUtf8("QListWidget {\n"
" border:none;\n"
" outline: none;\n"
" icon-size: 40px;\n"
" background: transparent;\n"
" padding-right:20px;\n"
" color:gray;\n"
"}\n"
"\n"
"QListWidget::item{\n"
" height:50px;\n"
"}\n"
"\n"
"QListWidget:focus{\n"
" border:none;\n"
" outline: none;\n"
"}\n"
"\n"
"QListWidget::item:focus{\n"
" border:none;\n"
" outline: none;\n"
" color:rgb(255, 255, 255);\n"
" font: 57 22pt \"Ubuntu\";\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QListWidget::item:selected{\n"
" border: none;\n"
" outline: none;\n"
" color:rgb(255, 255, 255);\n"
" font: 57 22pt \"Ubuntu\";\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}"));
languageFocus = new QLabel(widget);
languageFocus->setObjectName(QString::fromUtf8("languageFocus"));
languageFocus->setGeometry(QRect(150, 10, 67, 17));
printFocus = new QLabel(widget);
printFocus->setObjectName(QString::fromUtf8("printFocus"));
printFocus->setGeometry(QRect(40, 10, 67, 17));
printFocus->setFocusPolicy(Qt::NoFocus);
lineEdit = new QLineEdit(widget);
lineEdit->setObjectName(QString::fromUtf8("lineEdit"));
lineEdit->setGeometry(QRect(300, 10, 20, 30));
lineEdit->setFocusPolicy(Qt::NoFocus);
lineEdit->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_2 = new QLineEdit(widget);
lineEdit_2->setObjectName(QString::fromUtf8("lineEdit_2"));
lineEdit_2->setGeometry(QRect(320, 10, 20, 30));
lineEdit_2->setFocusPolicy(Qt::NoFocus);
lineEdit_2->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_3 = new QLineEdit(widget);
lineEdit_3->setObjectName(QString::fromUtf8("lineEdit_3"));
lineEdit_3->setGeometry(QRect(340, 10, 20, 30));
lineEdit_3->setFocusPolicy(Qt::NoFocus);
lineEdit_3->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_4 = new QLineEdit(widget);
lineEdit_4->setObjectName(QString::fromUtf8("lineEdit_4"));
lineEdit_4->setGeometry(QRect(360, 10, 20, 30));
lineEdit_4->setFocusPolicy(Qt::NoFocus);
lineEdit_4->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_6 = new QLineEdit(widget);
lineEdit_6->setObjectName(QString::fromUtf8("lineEdit_6"));
lineEdit_6->setGeometry(QRect(380, 10, 10, 30));
lineEdit_6->setFocusPolicy(Qt::NoFocus);
lineEdit_6->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_7 = new QLineEdit(widget);
lineEdit_7->setObjectName(QString::fromUtf8("lineEdit_7"));
lineEdit_7->setGeometry(QRect(390, 10, 20, 30));
lineEdit_7->setFocusPolicy(Qt::NoFocus);
lineEdit_7->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_8 = new QLineEdit(widget);
lineEdit_8->setObjectName(QString::fromUtf8("lineEdit_8"));
lineEdit_8->setGeometry(QRect(410, 10, 20, 30));
lineEdit_8->setFocusPolicy(Qt::NoFocus);
lineEdit_8->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_9 = new QLineEdit(widget);
lineEdit_9->setObjectName(QString::fromUtf8("lineEdit_9"));
lineEdit_9->setGeometry(QRect(430, 10, 10, 30));
lineEdit_9->setFocusPolicy(Qt::NoFocus);
lineEdit_9->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_10 = new QLineEdit(widget);
lineEdit_10->setObjectName(QString::fromUtf8("lineEdit_10"));
lineEdit_10->setGeometry(QRect(440, 10, 20, 30));
lineEdit_10->setFocusPolicy(Qt::NoFocus);
lineEdit_10->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_11 = new QLineEdit(widget);
lineEdit_11->setObjectName(QString::fromUtf8("lineEdit_11"));
lineEdit_11->setGeometry(QRect(460, 10, 20, 30));
lineEdit_11->setFocusPolicy(Qt::NoFocus);
lineEdit_11->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_12 = new QLineEdit(widget);
lineEdit_12->setObjectName(QString::fromUtf8("lineEdit_12"));
lineEdit_12->setGeometry(QRect(492, 10, 20, 30));
lineEdit_12->setFocusPolicy(Qt::NoFocus);
lineEdit_12->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_13 = new QLineEdit(widget);
lineEdit_13->setObjectName(QString::fromUtf8("lineEdit_13"));
lineEdit_13->setGeometry(QRect(512, 10, 20, 30));
lineEdit_13->setFocusPolicy(Qt::NoFocus);
lineEdit_13->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_14 = new QLineEdit(widget);
lineEdit_14->setObjectName(QString::fromUtf8("lineEdit_14"));
lineEdit_14->setGeometry(QRect(532, 10, 10, 30));
lineEdit_14->setFocusPolicy(Qt::NoFocus);
lineEdit_14->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_15 = new QLineEdit(widget);
lineEdit_15->setObjectName(QString::fromUtf8("lineEdit_15"));
lineEdit_15->setGeometry(QRect(542, 10, 20, 30));
lineEdit_15->setFocusPolicy(Qt::NoFocus);
lineEdit_15->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_16 = new QLineEdit(widget);
lineEdit_16->setObjectName(QString::fromUtf8("lineEdit_16"));
lineEdit_16->setGeometry(QRect(562, 10, 20, 30));
lineEdit_16->setFocusPolicy(Qt::NoFocus);
lineEdit_16->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_17 = new QLineEdit(widget);
lineEdit_17->setObjectName(QString::fromUtf8("lineEdit_17"));
lineEdit_17->setGeometry(QRect(582, 10, 10, 30));
lineEdit_17->setFocusPolicy(Qt::NoFocus);
lineEdit_17->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_18 = new QLineEdit(widget);
lineEdit_18->setObjectName(QString::fromUtf8("lineEdit_18"));
lineEdit_18->setGeometry(QRect(592, 10, 20, 30));
lineEdit_18->setFocusPolicy(Qt::NoFocus);
lineEdit_18->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_19 = new QLineEdit(widget);
lineEdit_19->setObjectName(QString::fromUtf8("lineEdit_19"));
lineEdit_19->setGeometry(QRect(612, 10, 20, 30));
lineEdit_19->setFocusPolicy(Qt::NoFocus);
lineEdit_19->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
lineEdit_20 = new QLineEdit(widget);
lineEdit_20->setObjectName(QString::fromUtf8("lineEdit_20"));
lineEdit_20->setGeometry(QRect(475, 10, 20, 30));
lineEdit_20->setFocusPolicy(Qt::NoFocus);
lineEdit_20->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border:none;\n"
" outline: none; \n"
" background: gray;\n"
" color:white;\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
"\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" color:rgb(0, 0, 0);\n"
" background-color:white;\n"
"}\n"
""));
dateTimeButton = new QPushButton(widget);
dateTimeButton->setObjectName(QString::fromUtf8("dateTimeButton"));
dateTimeButton->setGeometry(QRect(300, 0, 331, 45));
dateTimeButton->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" border:none;\n"
" outline: none;\n"
" icon-size: 40px;\n"
" background: transparent;\n"
"font: 15pt \"Ubuntu\";\n"
"text-align: left;\n"
"color: rgb(105, 115, 119);\n"
"}\n"
"QPushButton:focus{\n"
" border:none;\n"
" outline: none;\n"
"color:white;\n"
"text-align: left;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}"));
widget_2 = new QWidget(SystemSetting);
widget_2->setObjectName(QString::fromUtf8("widget_2"));
widget_2->setGeometry(QRect(0, 100, 800, 40));
comboBox = new QComboBox(widget_2);
comboBox->setObjectName(QString::fromUtf8("comboBox"));
comboBox->setGeometry(QRect(300, 5, 292, 40));
comboBox->setFocusPolicy(Qt::NoFocus);
comboBox->setStyleSheet(QString::fromUtf8("QComboBox{\n"
"border:0px;\n"
"background: transparent;\n"
"font: 14pt \"Ubuntu\";\n"
"color: rgb(105, 115, 119);\n"
"}\n"
"\n"
"QComboBox::down-arrow{image: url(:/images/System_Arrow_Down);}\n"
"QComboBox::drop-down{\n"
"border:0px;\n"
"}\n"
"QComboBox QAbstractItemView::item {\n"
"height:100px;\n"
"margin:10px;\n"
"\n"
"}\n"
"QComboBox QAbstractItemView {\n"
"border:0px;\n"
"outer:0px;\n"
"selection-background-color: rgb(140, 146, 150);\n"
"background-color: rgb(140, 146, 150);\n"
"}\n"
""));
listWidget_2 = new QListWidget(widget_2);
listWidget_2->setObjectName(QString::fromUtf8("listWidget_2"));
listWidget_2->setEnabled(true);
listWidget_2->setGeometry(QRect(40, 0, 212, 40));
listWidget_2->setFocusPolicy(Qt::WheelFocus);
listWidget_2->setStyleSheet(QString::fromUtf8("QListWidget {\n"
" border:none;\n"
" outline: none;\n"
" icon-size: 40px;\n"
" background: transparent;\n"
" padding-right:20px;\n"
" color:gray;\n"
"}\n"
"\n"
"QListWidget::item{\n"
" height:50px;\n"
"}\n"
"\n"
"QListWidget:focus{\n"
" border:none;\n"
" outline: none;\n"
"}\n"
"\n"
"QListWidget::item:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QListWidget::item:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
" "));
widget_3 = new QWidget(SystemSetting);
widget_3->setObjectName(QString::fromUtf8("widget_3"));
widget_3->setGeometry(QRect(0, 150, 800, 40));
listWidget_3 = new QListWidget(widget_3);
listWidget_3->setObjectName(QString::fromUtf8("listWidget_3"));
listWidget_3->setEnabled(true);
listWidget_3->setGeometry(QRect(40, 0, 212, 40));
listWidget_3->setFocusPolicy(Qt::WheelFocus);
listWidget_3->setStyleSheet(QString::fromUtf8("QListWidget {\n"
" border:none;\n"
" outline: none;\n"
" icon-size: 40px;\n"
" background: transparent;\n"
" padding-right:20px;\n"
" color:gray;\n"
"}\n"
"\n"
"QListWidget::item{\n"
" height:50px;\n"
"}\n"
"\n"
"QListWidget:focus{\n"
" border:none;\n"
" outline: none;\n"
"}\n"
"\n"
"QListWidget::item:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QListWidget::item:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
" "));
horizontalScrollBar = new QScrollBar(widget_3);
horizontalScrollBar->setObjectName(QString::fromUtf8("horizontalScrollBar"));
horizontalScrollBar->setGeometry(QRect(300, 5, 370, 30));
horizontalScrollBar->setStyleSheet(QString::fromUtf8("QScrollBar:horizontal\n"
"{\n"
"width:8px;\n"
"background:rgba(0,0,0,50%);\n"
"selection-background:rgba(255, 255, 255, 154);\n"
"margin:1px,1px,1px,1px;\n"
"padding-left:20px;\n"
"padding-right:22px;\n"
"}\n"
"QScrollBar:handle\n"
"{\n"
" background:qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0.15 rgba(0, 0, 0, 0), stop:0.16 rgba(193, 190, 190, 255), stop:0.845 rgba(134, 125, 125, 255), stop:0.855 rgba(0, 0, 0, 0));\n"
"\n"
"}\n"
"QScrollBar::add-line:horizontal \n"
"{\n"
" height:15px;width:15px;\n"
" border-image:url(:/images/System_Arrow_Right);\n"
" subcontrol-position:right;\n"
"}\n"
"QScrollBar::sub-line:horizontal \n"
"{\n"
" height:15px;width:15px;\n"
" border-image:url(:/images/System_Arrow_Left);\n"
" subcontrol-position:left;\n"
"\n"
"}\n"
"QScrollBar::add-page:horizontal\n"
"{\n"
" background:rgba(0,0,0,0%);\n"
" border-radius:20px;\n"
"}\n"
"QScrollBar::sub-page:horizontal \n"
"{\n"
" background:qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, sto"
"p:0.15 rgba(0, 0, 0, 0), stop:0.16 rgba(193, 190, 190, 255), stop:0.845 rgba(134, 125, 125, 255), stop:0.855 rgba(0, 0, 0, 0));\n"
"border-radius:20px;\n"
"}"));
horizontalScrollBar->setMaximum(100);
horizontalScrollBar->setOrientation(Qt::Horizontal);
horizontalScrollBarFocus = new QLabel(widget_3);
horizontalScrollBarFocus->setObjectName(QString::fromUtf8("horizontalScrollBarFocus"));
horizontalScrollBarFocus->setGeometry(QRect(680, 10, 67, 17));
widget_4 = new QWidget(SystemSetting);
widget_4->setObjectName(QString::fromUtf8("widget_4"));
widget_4->setGeometry(QRect(0, 200, 800, 40));
horizontalScrollBar_2 = new QScrollBar(widget_4);
horizontalScrollBar_2->setObjectName(QString::fromUtf8("horizontalScrollBar_2"));
horizontalScrollBar_2->setGeometry(QRect(300, 5, 370, 30));
horizontalScrollBar_2->setStyleSheet(QString::fromUtf8("QScrollBar:horizontal\n"
"{\n"
"width:8px;\n"
"background:rgba(0,0,0,50%);\n"
"margin:1px,1px,1px,1px;\n"
"padding-left:20px;\n"
"padding-right:22px;\n"
"selection-background-color:rgba(255, 255, 255, 154);\n"
"}\n"
"QScrollBar:handle\n"
"{\n"
" background:qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0.15 rgba(0, 0, 0, 0), stop:0.16 rgba(193, 190, 190, 255), stop:0.845 rgba(134, 125, 125, 255), stop:0.855 rgba(0, 0, 0, 0));\n"
"\n"
"}\n"
"QScrollBar::add-line:horizontal \n"
"{\n"
" height:15px;width:15px;\n"
" border-image:url(:/images/System_Arrow_Right);\n"
" subcontrol-position:right;\n"
"}\n"
"QScrollBar::sub-line:horizontal \n"
"{\n"
" height:15px;width:15px;\n"
" border-image:url(:/images/System_Arrow_Left);\n"
" subcontrol-position:left;\n"
"\n"
"}\n"
"QScrollBar::add-page:horizontal\n"
"{\n"
" background:rgba(0,0,0,0%);\n"
" border-radius:20px;\n"
"}\n"
"QScrollBar::sub-page:horizontal \n"
"{\n"
" background:qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:"
"1, stop:0.15 rgba(0, 0, 0, 0), stop:0.16 rgba(193, 190, 190, 255), stop:0.845 rgba(134, 125, 125, 255), stop:0.855 rgba(0, 0, 0, 0));\n"
"border-radius:20px;\n"
"}"));
horizontalScrollBar_2->setMaximum(127);
horizontalScrollBar_2->setOrientation(Qt::Horizontal);
listWidget_4 = new QListWidget(widget_4);
listWidget_4->setObjectName(QString::fromUtf8("listWidget_4"));
listWidget_4->setEnabled(true);
listWidget_4->setGeometry(QRect(40, 0, 212, 40));
listWidget_4->setFocusPolicy(Qt::WheelFocus);
listWidget_4->setStyleSheet(QString::fromUtf8("QListWidget {\n"
" border:none;\n"
" outline: none;\n"
" icon-size: 40px;\n"
" background: transparent;\n"
" padding-right:20px;\n"
" color:gray;\n"
"}\n"
"\n"
"QListWidget::item{\n"
" height:50px;\n"
"}\n"
"\n"
"QListWidget:focus{\n"
" border:none;\n"
" outline: none;\n"
"}\n"
"\n"
"QListWidget::item:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QListWidget::item:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
" "));
horizontalScrollBarFocus2 = new QLabel(widget_4);
horizontalScrollBarFocus2->setObjectName(QString::fromUtf8("horizontalScrollBarFocus2"));
horizontalScrollBarFocus2->setGeometry(QRect(680, 10, 67, 17));
horizontalScrollBarFocus2->setFocusPolicy(Qt::NoFocus);
widget_5 = new QWidget(SystemSetting);
widget_5->setObjectName(QString::fromUtf8("widget_5"));
widget_5->setGeometry(QRect(0, 250, 800, 40));
lineEdit_5 = new QLineEdit(widget_5);
lineEdit_5->setObjectName(QString::fromUtf8("lineEdit_5"));
lineEdit_5->setGeometry(QRect(300, 5, 41, 40));
lineEdit_5->setFocusPolicy(Qt::NoFocus);
lineEdit_5->setStyleSheet(QString::fromUtf8("QLineEdit\n"
"{\n"
" border: none;\n"
"font: 14pt \"Ubuntu\";\n"
"text-align: left;\n"
" background: transparent;\n"
"color: rgb(105, 115, 119);\n"
"}\n"
"QLineEdit:focus\n"
"{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
"text-align: left;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QLineEdit:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
""));
lineEdit_5->setEchoMode(QLineEdit::Normal);
lineEdit_5->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);
lineEdit_5->setDragEnabled(false);
lineEdit_5->setReadOnly(true);
listWidget_5 = new QListWidget(widget_5);
listWidget_5->setObjectName(QString::fromUtf8("listWidget_5"));
listWidget_5->setEnabled(true);
listWidget_5->setGeometry(QRect(40, 0, 212, 40));
listWidget_5->setFocusPolicy(Qt::WheelFocus);
listWidget_5->setStyleSheet(QString::fromUtf8("QListWidget {\n"
" border:none;\n"
" outline: none;\n"
" icon-size: 40px;\n"
" background: transparent;\n"
" padding-right:20px;\n"
" color:gray;\n"
"}\n"
"\n"
"QListWidget::item{\n"
" height:50px;\n"
"}\n"
"\n"
"QListWidget:focus{\n"
" border:none;\n"
" outline: none;\n"
"}\n"
"\n"
"QListWidget::item:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QListWidget::item:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
" "));
label_8 = new QLabel(widget_5);
label_8->setObjectName(QString::fromUtf8("label_8"));
label_8->setGeometry(QRect(350, 5, 71, 40));
label_8->setStyleSheet(QString::fromUtf8("QLabel\n"
"{\n"
"font: 15pt \"Ubuntu\";\n"
"color: rgb(105, 115, 119);\n"
"}\n"
"QLabel:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QLabel:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
""));
widget_6 = new QWidget(SystemSetting);
widget_6->setObjectName(QString::fromUtf8("widget_6"));
widget_6->setGeometry(QRect(0, 300, 800, 120));
listWidget_6 = new QListWidget(widget_6);
listWidget_6->setObjectName(QString::fromUtf8("listWidget_6"));
listWidget_6->setEnabled(true);
listWidget_6->setGeometry(QRect(40, 0, 241, 40));
listWidget_6->setFocusPolicy(Qt::WheelFocus);
listWidget_6->setStyleSheet(QString::fromUtf8("QListWidget {\n"
" border:none;\n"
" outline: none;\n"
" icon-size: 40px;\n"
" background: transparent;\n"
" padding-right:20px;\n"
" color:gray;\n"
"}\n"
"\n"
"QListWidget::item{\n"
" height:50px;\n"
"}\n"
"\n"
"QListWidget:focus{\n"
" border:none;\n"
" outline: none;\n"
"}\n"
"\n"
"QListWidget::item:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QListWidget::item:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
" "));
identificationSetting = new QTableWidget(widget_6);
identificationSetting->setObjectName(QString::fromUtf8("identificationSetting"));
identificationSetting->setGeometry(QRect(300, 10, 491, 91));
identificationSetting->setFocusPolicy(Qt::NoFocus);
identificationSetting->setStyleSheet(QString::fromUtf8("QWidget\n"
"{\n"
" border:none;\n"
" outline: none;\n"
"background: transparent;\n"
"}\n"
"QWidget:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QWidget:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
""));
label = new QLabel(widget_6);
label->setObjectName(QString::fromUtf8("label"));
label->setGeometry(QRect(300, 10, 170, 30));
label->setStyleSheet(QString::fromUtf8("QLabel\n"
"{\n"
"font: 15pt \"Ubuntu\";\n"
"color: rgb(105, 115, 119);\n"
"}\n"
"QLabel:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QLabel:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
""));
label->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
label_2 = new QLabel(widget_6);
label_2->setObjectName(QString::fromUtf8("label_2"));
label_2->setGeometry(QRect(300, 40, 170, 30));
label_2->setStyleSheet(QString::fromUtf8("QLabel\n"
"{\n"
"font: 15pt \"Ubuntu\";\n"
"color: rgb(105, 115, 119);\n"
"}\n"
""));
label_2->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
label_3 = new QLabel(widget_6);
label_3->setObjectName(QString::fromUtf8("label_3"));
label_3->setGeometry(QRect(300, 70, 170, 30));
label_3->setStyleSheet(QString::fromUtf8("QLabel\n"
"{\n"
"font: 15pt \"Ubuntu\";\n"
"color: rgb(105, 115, 119);\n"
"}\n"
""));
label_3->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
label_4 = new QLabel(widget_6);
label_4->setObjectName(QString::fromUtf8("label_4"));
label_4->setGeometry(QRect(490, 10, 111, 30));
label_4->setStyleSheet(QString::fromUtf8("QLabel\n"
"{\n"
"font: 15pt \"Ubuntu\";\n"
"color: rgb(105, 115, 119);\n"
"}\n"
"QLabel:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QLabel:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
""));
label_5 = new QLabel(widget_6);
label_5->setObjectName(QString::fromUtf8("label_5"));
label_5->setGeometry(QRect(490, 40, 151, 30));
label_5->setStyleSheet(QString::fromUtf8("QLabel\n"
"{\n"
"font: 15pt \"Ubuntu\";\n"
"color: rgb(105, 115, 119);\n"
"}\n"
"QLabel:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QLabel:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
""));
label_6 = new QLabel(widget_6);
label_6->setObjectName(QString::fromUtf8("label_6"));
label_6->setGeometry(QRect(490, 70, 261, 30));
label_6->setStyleSheet(QString::fromUtf8("QLabel\n"
"{\n"
"font: 15pt \"Ubuntu\";\n"
"color: rgb(105, 115, 119);\n"
"}\n"
"\n"
""));
widget_7 = new QWidget(SystemSetting);
widget_7->setObjectName(QString::fromUtf8("widget_7"));
widget_7->setGeometry(QRect(0, 420, 800, 40));
comboBox_2 = new QComboBox(widget_7);
comboBox_2->setObjectName(QString::fromUtf8("comboBox_2"));
comboBox_2->setGeometry(QRect(300, 5, 292, 40));
comboBox_2->setFocusPolicy(Qt::NoFocus);
comboBox_2->setStyleSheet(QString::fromUtf8("QComboBox{\n"
"border:0px;\n"
"background: transparent;\n"
"font: 14pt \"Ubuntu\";\n"
"color: rgb(105, 115, 119);\n"
"}\n"
"\n"
"QComboBox::down-arrow\n"
"{\n"
"image: url(:/images/System_Arrow_Down);\n"
"}\n"
"QComboBox::drop-down\n"
"{\n"
"border:0px;\n"
"}\n"
"QComboBox QAbstractItemView::item\n"
" {\n"
"height:100px;\n"
"margin:10px;\n"
"\n"
"}\n"
"QComboBox QAbstractItemView {\n"
"border:0px;\n"
"outer:0px;\n"
"selection-background-color: rgb(140, 146, 150);\n"
"background-color: rgb(140, 146, 150);\n"
"}\n"
""));
listWidget_7 = new QListWidget(widget_7);
listWidget_7->setObjectName(QString::fromUtf8("listWidget_7"));
listWidget_7->setEnabled(true);
listWidget_7->setGeometry(QRect(40, 0, 212, 40));
listWidget_7->setFocusPolicy(Qt::WheelFocus);
listWidget_7->setStyleSheet(QString::fromUtf8("QListWidget {\n"
" border:none;\n"
" outline: none;\n"
" icon-size: 40px;\n"
" background: transparent;\n"
" padding-right:20px;\n"
" color:gray;\n"
"}\n"
"\n"
"QListWidget::item{\n"
" height:50px;\n"
"}\n"
"\n"
"QListWidget:focus{\n"
" border:none;\n"
" outline: none;\n"
"}\n"
"\n"
"QListWidget::item:focus{\n"
" border:none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
"\n"
"QListWidget::item:selected{\n"
" border: none;\n"
" outline: none;\n"
" font: bold 20pt;\n"
" color:white;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(48, 60, 76, 255), stop:1 rgba(7, 61, 82, 255));\n"
"}\n"
" "));
retranslateUi(SystemSetting);
QMetaObject::connectSlotsByName(SystemSetting);
} // setupUi
void retranslateUi(QWidget *SystemSetting)
{
SystemSetting->setWindowTitle(QApplication::translate("SystemSetting", "Form", 0, QApplication::UnicodeUTF8));
label_7->setText(QString());
homeTBnt->setText(QApplication::translate("SystemSetting", "&Home", 0, QApplication::UnicodeUTF8));
aboutTBtn->setText(QApplication::translate("SystemSetting", "&About", 0, QApplication::UnicodeUTF8));
testTBtn->setText(QApplication::translate("SystemSetting", "&Test", 0, QApplication::UnicodeUTF8));
settingTBtn->setText(QApplication::translate("SystemSetting", "Setting", 0, QApplication::UnicodeUTF8));
languageFocus->setText(QString());
printFocus->setText(QString());
lineEdit->setText(QApplication::translate("SystemSetting", "2", 0, QApplication::UnicodeUTF8));
lineEdit_2->setText(QApplication::translate("SystemSetting", "0", 0, QApplication::UnicodeUTF8));
lineEdit_3->setText(QApplication::translate("SystemSetting", "1", 0, QApplication::UnicodeUTF8));
lineEdit_4->setText(QApplication::translate("SystemSetting", "5", 0, QApplication::UnicodeUTF8));
lineEdit_6->setText(QApplication::translate("SystemSetting", "/", 0, QApplication::UnicodeUTF8));
lineEdit_7->setText(QApplication::translate("SystemSetting", "1", 0, QApplication::UnicodeUTF8));
lineEdit_8->setText(QApplication::translate("SystemSetting", "0", 0, QApplication::UnicodeUTF8));
lineEdit_9->setText(QApplication::translate("SystemSetting", "/", 0, QApplication::UnicodeUTF8));
lineEdit_10->setText(QApplication::translate("SystemSetting", "2", 0, QApplication::UnicodeUTF8));
lineEdit_11->setText(QApplication::translate("SystemSetting", "0", 0, QApplication::UnicodeUTF8));
lineEdit_12->setText(QApplication::translate("SystemSetting", "1", 0, QApplication::UnicodeUTF8));
lineEdit_13->setText(QApplication::translate("SystemSetting", "6", 0, QApplication::UnicodeUTF8));
lineEdit_14->setText(QApplication::translate("SystemSetting", ":", 0, QApplication::UnicodeUTF8));
lineEdit_15->setText(QApplication::translate("SystemSetting", "4", 0, QApplication::UnicodeUTF8));
lineEdit_16->setText(QApplication::translate("SystemSetting", "0", 0, QApplication::UnicodeUTF8));
lineEdit_17->setText(QApplication::translate("SystemSetting", ":", 0, QApplication::UnicodeUTF8));
lineEdit_18->setText(QApplication::translate("SystemSetting", "1", 0, QApplication::UnicodeUTF8));
lineEdit_19->setText(QApplication::translate("SystemSetting", "1", 0, QApplication::UnicodeUTF8));
lineEdit_20->setText(QString());
dateTimeButton->setText(QString());
horizontalScrollBarFocus->setText(QString());
lineEdit_5->setText(QApplication::translate("SystemSetting", "10", 0, QApplication::UnicodeUTF8));
label_8->setText(QApplication::translate("SystemSetting", "msec", 0, QApplication::UnicodeUTF8));
label->setText(QApplication::translate("SystemSetting", "123", 0, QApplication::UnicodeUTF8));
label_2->setText(QApplication::translate("SystemSetting", "123", 0, QApplication::UnicodeUTF8));
label_3->setText(QApplication::translate("SystemSetting", "TextLabel", 0, QApplication::UnicodeUTF8));
label_4->setText(QApplication::translate("SystemSetting", "NULL", 0, QApplication::UnicodeUTF8));
label_5->setText(QApplication::translate("SystemSetting", "NULL", 0, QApplication::UnicodeUTF8));
label_6->setText(QApplication::translate("SystemSetting", "NULL", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class SystemSetting: public Ui_SystemSetting {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_SYSTEMSETTING_H
| [
"zhenzhongyao@126.com"
] | zhenzhongyao@126.com |
c041658e5067513be2f9d8e58ec427d1a327ffb9 | aa1ef21bf7aa0fab6d5b9f429b086eced97c7b8e | /codeforces/702div3/2.cpp | e2be5430917e4d6ba6ca196f65ccb8279267e81d | [] | no_license | vd-07/CP | ad8f7a0b71e53e2f83b0a69d344f3cf9b9c77580 | 15b0c69574111ebca4b9f428f84d10884bc65bcd | refs/heads/main | 2021-09-08T07:35:16.804319 | 2021-08-04T16:58:47 | 2021-08-04T16:58:47 | 207,377,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,409 | cpp | //Author : Vivek Dubey
#include <bits/stdc++.h>
using namespace std;
// debug start
template <typename A, typename B>
string to_string(pair<A, B> p);
template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) {
return '"' + s + '"';
}
string to_string(const char* s) {
return to_string((string) s);
}
string to_string(bool b) {
return (b ? "true" : "false");
}
string to_string(vector<bool> v) {
bool first = true;
string res = "{";
for (int i = 0; i < static_cast<int>(v.size()); i++) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(v[i]);
}
res += "}";
return res;
}
template <size_t N>
string to_string(bitset<N> v) {
string res = "";
for (size_t i = 0; i < N; i++) {
res += static_cast<char>('0' + v[i]);
}
return res;
}
template <typename A>
string to_string(A v) {
bool first = true;
string res = "{";
for (const auto &x : v) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(x);
}
res += "}";
return res;
}
template <typename A, typename B>
string to_string(pair<A, B> p) {
return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}
template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << " " << to_string(H);
debug_out(T...);
}
#ifndef ONLINE_JUDGE
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif
// end debug
#define int long long
const int mxN = 3e5 + 1;
int n;
void solve() {
vector<int> a(3);
cin >> n;
int c;
for(int i = 1; i <= n; i++) {
cin >> c;
a[c % 3] ++;
}
int cost = 0;
int toEqual = n / 3;
if(a[0] < toEqual) {
int def = toEqual - a[0];
if(a[2] < def) {
def -= a[2];
cost += a[2];
a[2] = 0;
a[1] -= def;
cost += 2 * def;
} else {
a[2] -= def;
cost += def;
}
a[0] = toEqual;
} else {
int def = a[0] - toEqual;
a[1] += def;
cost += def;
a[0] = toEqual;
}
if(a[1] > toEqual) {
int def = a[1] - toEqual;
a[2] += def;
cost += def;
} else {
int def = toEqual - a[1];
a[2] -= def;
cost += 2 * def;
}
a[1] = toEqual;
debug(a);
assert(a[2] == toEqual);
cout << cost << "\n";
}
int32_t main() {
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input.txt", "r", stdin);
// for writing output to output.txt
//this can be opted out if you want to print the output to the sublime console
freopen("output.txt", "w", stdout);
#endif
// for fast i/o
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// test cases
int t = 1;
cin >> t;
while(t--) {
solve();
}
return 0;
} | [
"dubey.vivek.2805@gmail.com"
] | dubey.vivek.2805@gmail.com |
b209f6d0f10facadcd7df000f96df03a664e9396 | 7b9508e1b60e53601b93b96369e4806f691e9f58 | /Algorithm/백준/알고리즘 중급/다이나믹 프로그래밍/다이나믹 프로그래밍/BOJ 14501 퇴사.cpp | 093e2b72b551541dfec5ffab1954f1e99dd6a9e0 | [] | no_license | wkdehdlr/Doo-it | e522b5227e5c92aa34ec7f2f0de9c8eafbedf38e | 4cd7746457c8e1ae34d82e0fae3ae4e820e1a163 | refs/heads/master | 2023-03-04T02:29:57.283182 | 2021-02-19T08:22:56 | 2021-02-19T08:22:56 | 110,106,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 532 | cpp | #pragma warning(disable : 4996)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int N;
int arr[16][2];
int dp[16];
int func(int n)
{
if (n == N + 1)return 0;
int& ret = dp[n];
if (ret != -1)return ret;
ret = 0;
for (int i = n; i <= N; ++i) {
if (i + arr[i][0] <= N + 1)
ret = max(ret, func(i + arr[i][0]) + arr[i][1]);
}
return ret;
}
int main()
{
memset(dp, -1, sizeof(dp));
scanf("%d", &N);
for (int i = 1; i <= N; ++i)scanf("%d %d", &arr[i][0], &arr[i][1]);
printf("%d\n", func(1));
} | [
"wel_789@naver.com"
] | wel_789@naver.com |
f278b0db03b18cba62b6b4f3777b9f74f0d0d38c | 3630f0a5da678419ff6eaf0fcb4875fb1142f5b9 | /1202.cpp | 95305daccb0736af28b414b1f92cb6bcc9a37e7b | [] | no_license | vantaa89/acmicpc | ed1b51ebb3ab8086f3460b4edc4115fbea569d22 | 6d0a0b1a8762fa0f8d269f28fd08142a661b59b6 | refs/heads/main | 2023-08-04T05:32:13.576615 | 2021-09-09T07:41:02 | 2021-09-09T07:41:02 | 403,900,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 823 | cpp | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int MAX_N = 300000;
int main() {
int n, k;
scanf("%d %d", &n, &k);
vector<pair<int, int> > gems(n);
vector<int> bags(k);
priority_queue<int> pq;
for(int i = 0; i < n; ++i){
scanf("%d %d", &gems[i].first, &gems[i].second);
}
for(int i = 0; i < k; ++i){
scanf("%d", &bags[i]);
}
sort(bags.begin(), bags.end());
sort(gems.begin(), gems.end());
long long result = 0;
int j = 0;
for(int i = 0; i < k; ++i){
for(; j < n && gems[j].first <= bags[i]; ++j){
pq.push(gems[j].second);
}
if(!pq.empty()){
result += pq.top();
pq.pop();
}
}
printf("%lld\n", result);
return 0;
}
| [
"leeseojune89@gmail.com"
] | leeseojune89@gmail.com |
12aefaf455645784c070431dda694ff3ded8e04c | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-lookoutvision/include/aws/lookoutvision/LookoutforVisionErrorMarshaller.h | 245f3a05ba1e6ce12a004e665e74180e1a3eeed7 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 545 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/lookoutvision/LookoutforVision_EXPORTS.h>
#include <aws/core/client/AWSErrorMarshaller.h>
namespace Aws
{
namespace Client
{
class AWS_LOOKOUTFORVISION_API LookoutforVisionErrorMarshaller : public Aws::Client::JsonErrorMarshaller
{
public:
Aws::Client::AWSError<Aws::Client::CoreErrors> FindErrorByName(const char* exceptionName) const override;
};
} // namespace Client
} // namespace Aws
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
538111fadcf87d366c518dc0b8ce0c20563a5048 | 2e1200fcec94ea57ffb925ee7f35d21bc4a6443e | /trunk-linux/src/common/cpp/LoggerFactory.cpp | 5556bbfbfcc9ca1159b3411107fbd605ddf37ec9 | [] | no_license | cho934/pm-robotix | acc1eaa80069cce297ee52e08961bfdc04110f5a | e88fcfc3d636b428d88797ed612c2461bce58f1b | refs/heads/master | 2021-01-20T04:32:23.610337 | 2015-06-05T20:28:08 | 2015-06-05T20:28:08 | 39,189,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,599 | cpp | /*!
* \file
* \brief Implémentation de la classe LoggerFactory.
*/
#include "LoggerFactory.hpp"
utils::LoggerFactory::LoggerFactory()
: appenders_(), loggers_(), rootLogger_()
{
lock=new Mutex();
this->initialize();
if(rootLogger() == NULL)
{
//! \todo Must throw an exception
//TODO Exception Must throw an exception
}
}
utils::LoggerFactory::~LoggerFactory()
{
lock->lock();
std::map < std::string, utils::Logger * >::iterator i1 = loggers_.begin();
for (; i1 != loggers_.end(); i1++)
{
delete i1->second;
i1->second = NULL;
}
std::map < std::string, utils::Appender * >::iterator i2 = appenders_.begin();
for (; i2 != appenders_.end(); i2++)
{
delete i2->second;
i2->second = NULL;
}
lock->unlock();
delete lock;
}
const utils::Logger &
utils::LoggerFactory::logger(const std::string & name)
{
LoggerFactory & instance = utils::LoggerFactory::instance();
// instance.lock();
std::map < std::string, utils::Logger * >::iterator value = instance.loggers_.find(name);
if (value == instance.loggers_.end())
{
Logger * logger = new Logger(* instance.rootLogger(), name);
instance.add(logger);
// instance.unlock();
return * logger;
}
// instance.unlock();
return *(value->second);
}
utils::Appender *
utils::LoggerFactory::appender(const std::string & name)
{
// lock->lock();
std::map < std::string, utils::Appender * >::iterator value = this->appenders_.find(name);
if (value == this->appenders_.end())
{
// lock->unlock();
return NULL;
}
else
{
// lock->unlock();
return value->second;
}
}
void
utils::LoggerFactory::add(Logger * logger)
{
// lock->lock();
if (logger->name() == "")
{
// lock->lock();
this->rootLogger_ = logger;
// lock->unlock();
}
else
{
loggers_.insert(std::make_pair(logger->name(), logger));
}
// lock->unlock();
}
void
utils::LoggerFactory::add(const std::string & name, utils::Appender * appender)
{
// lock->lock();
appenders_.insert(std::make_pair(name, appender));
// lock->unlock();
}
void
utils::LoggerFactory::add(const Level & level, const std::string & loggerName, const std::string & appenderName)
{
Appender * appender = this->appender(appenderName);
if (appender == NULL)
{
//! \todo Must throw an exception
}
else
{
Logger *log= new Logger(level, loggerName, * appender);
this->add(log);
}
}
| [
"christophe.chaudelet@gmail.com"
] | christophe.chaudelet@gmail.com |
7def1f297f86b0f26408d75fedc02a4e6e33b4c3 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /content/shell/renderer/shell_content_renderer_client.cc | e5c8b9f8d96e1cfd44e5cc5d0271a45690909d1a | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 4,767 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/renderer/shell_content_renderer_client.h"
#include <string>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/macros.h"
#include "components/cdm/renderer/external_clear_key_key_system_properties.h"
#include "components/web_cache/renderer/web_cache_impl.h"
#include "content/public/test/test_service.mojom.h"
#include "content/shell/common/shell_switches.h"
#include "content/shell/renderer/shell_render_view_observer.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "services/shell/public/cpp/interface_registry.h"
#include "third_party/WebKit/public/web/WebTestingSupport.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "v8/include/v8.h"
#if defined(ENABLE_PLUGINS)
#include "ppapi/shared_impl/ppapi_switches.h"
#endif
#if defined(OS_ANDROID)
#include "base/feature_list.h"
#include "media/base/media_switches.h"
#endif
namespace content {
namespace {
// A test service which can be driven by browser tests for various reasons.
class TestServiceImpl : public mojom::TestService {
public:
explicit TestServiceImpl(mojom::TestServiceRequest request)
: binding_(this, std::move(request)) {
binding_.set_connection_error_handler(
base::Bind(&TestServiceImpl::OnConnectionError,
base::Unretained(this)));
}
~TestServiceImpl() override {}
private:
void OnConnectionError() { delete this; }
// mojom::TestService:
void DoSomething(const DoSomethingCallback& callback) override {
// Instead of responding normally, unbind the pipe, write some garbage,
// and go away.
const std::string kBadMessage = "This is definitely not a valid response!";
mojo::ScopedMessagePipeHandle pipe = binding_.Unbind().PassMessagePipe();
MojoResult rv = mojo::WriteMessageRaw(
pipe.get(), kBadMessage.data(), kBadMessage.size(), nullptr, 0,
MOJO_WRITE_MESSAGE_FLAG_NONE);
DCHECK_EQ(rv, MOJO_RESULT_OK);
// Deletes this.
OnConnectionError();
}
void DoTerminateProcess(const DoTerminateProcessCallback& callback) override {
NOTREACHED();
}
void CreateFolder(const CreateFolderCallback& callback) override {
NOTREACHED();
}
void GetRequestorName(const GetRequestorNameCallback& callback) override {
callback.Run("Not implemented.");
}
void CreateSharedBuffer(const std::string& message,
const CreateSharedBufferCallback& callback) override {
NOTREACHED();
}
mojo::Binding<mojom::TestService> binding_;
DISALLOW_COPY_AND_ASSIGN(TestServiceImpl);
};
void CreateTestService(mojom::TestServiceRequest request) {
// Owns itself.
new TestServiceImpl(std::move(request));
}
} // namespace
ShellContentRendererClient::ShellContentRendererClient() {}
ShellContentRendererClient::~ShellContentRendererClient() {
}
void ShellContentRendererClient::RenderThreadStarted() {
web_cache_impl_.reset(new web_cache::WebCacheImpl());
}
void ShellContentRendererClient::RenderViewCreated(RenderView* render_view) {
new ShellRenderViewObserver(render_view);
}
bool ShellContentRendererClient::IsPluginAllowedToUseCompositorAPI(
const GURL& url) {
#if defined(ENABLE_PLUGINS)
return base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnablePepperTesting);
#else
return false;
#endif
}
bool ShellContentRendererClient::IsPluginAllowedToUseDevChannelAPIs() {
#if defined(ENABLE_PLUGINS)
return base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnablePepperTesting);
#else
return false;
#endif
}
void ShellContentRendererClient::DidInitializeWorkerContextOnWorkerThread(
v8::Local<v8::Context> context) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kExposeInternalsForTesting)) {
blink::WebTestingSupport::injectInternalsObject(context);
}
}
void ShellContentRendererClient::ExposeInterfacesToBrowser(
shell::InterfaceRegistry* interface_registry) {
interface_registry->AddInterface<mojom::TestService>(
base::Bind(&CreateTestService));
}
#if defined(OS_ANDROID)
void ShellContentRendererClient::AddSupportedKeySystems(
std::vector<std::unique_ptr<media::KeySystemProperties>>* key_systems) {
if (!base::FeatureList::IsEnabled(media::kExternalClearKeyForTesting))
return;
static const char kExternalClearKeyKeySystem[] =
"org.chromium.externalclearkey";
key_systems->emplace_back(
new cdm::ExternalClearKeyProperties(kExternalClearKeyKeySystem));
}
#endif
} // namespace content
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
984c22f42552f7d9b50574bd46572fa3219769ba | 01ca325ef7d8ff63ce8ececa5119d3bc2efe1eae | /src/gst/Model.cpp | 5301a15b2ffcb077666a98c3ac475fdb152b14ba | [] | no_license | eleanxr/glstuff | cdd94200fc00cb9ac26741686ebe02ec49a14fa6 | 5c19ff1be8a67c442fab42323cde4a79b510d3cd | refs/heads/master | 2023-02-19T09:30:36.688566 | 2017-05-05T21:23:22 | 2017-05-05T21:23:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 99 | cpp | #include "Model.h"
namespace gst {
Model::Model()
{
}
Model::~Model()
{
}
} // namespace gst
| [
"wdicharry@gmail.com"
] | wdicharry@gmail.com |
ed98dc04a68f865337088f4dabac6808fc7205a0 | c82195607bd185b6a186bc4f3de39829b4069dcd | /hw6/hw6_q3.cpp | 5457d78f4a8670876c499de78fea41baa0c61620 | [] | no_license | hysl/Bridge | 48c05f7ef44bcd1442e6ffb9fddf49b7ac156923 | 35dc4b18bf56764c3b2721e1aed29ff48489a80c | refs/heads/master | 2022-02-24T20:18:16.933209 | 2019-09-11T03:20:26 | 2019-09-11T03:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | /*
Helen Li
August 24, 2018
Homework #6 - Question 3
*/
#include <iostream>
using namespace std;
double eApprox(int n);
int main()
{
cout.precision(30);
int num;
cout << "Please enter a positive integer: ";
cin >> num;
for (int n = 1; n <= num; n++)
cout << "n = " << n << '\t' << eApprox(n) << endl;
return 0;
}
double eApprox(int n)
{
double factorial, result;
factorial = 1;
result = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
result += (1/factorial);
}
return result;
}
| [
"noreply@github.com"
] | noreply@github.com |
9ca94b71ff4b0a1125c215c456fe013df41ee898 | 5b12a0db934624dcc1ec3feff42d50479f97ab72 | /Leetcode/901~1000/934. Shortest Bridge.cpp | bbb06ef440954534a00cbbe07be8b651c9abcdca | [] | no_license | hwchang417/online_judge | 0df7eb9386d2316b37532d026ec5f29fb051f40f | 80e5ef80705de1c5e43b61321ff0721fed9f7881 | refs/heads/master | 2020-04-26T19:03:16.364584 | 2019-03-04T14:46:23 | 2019-03-04T14:46:23 | 173,762,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,804 | cpp | #define getDistance(p1, p2) (abs(p1.first - p2.first) + abs(p1.second - p2.second))
class Solution {
public:
void dfs(vector<vector<int>>& A, int row, int col, int nr, int nc, int group){
if(A[row][col] != 1) return ;
A[row][col] = group;
if(row > 0 && A[row - 1][col] == 1)
dfs(A, row - 1, col, nr, nc, group);
if(col > 0 && A[row][col - 1] == 1)
dfs(A, row, col - 1, nr, nc, group);
if(row < nr - 1 && A[row + 1][col] == 1)
dfs(A, row + 1, col, nr, nc, group);
if(col < nc - 1 && A[row][col + 1] == 1)
dfs(A, row, col + 1, nr, nc, group);
}
int shortestBridge(vector<vector<int>>& A) {
int row, col, group, rowSize, colSize, minDistance;
vector<pair<int, int>> groups[4];
//4 connected labeling
group = 2;
rowSize = A.size();
colSize = A[0].size();
for(row = 0;row < rowSize;row++){
for(col = 0;col < colSize;col++){
if(A[row][col] == 1){
dfs(A, row, col, rowSize, colSize, group);
group++;
}
}
}
//labeling之後把對應的group加到對應的group
for(row = 0;row < rowSize;row++)
for(col = 0;col < colSize;col++)
groups[A[row][col]].push_back(pair<int, int>(row, col));
minDistance = INT_MAX;
//兩個group做O(N^2)的棋盤式檢查
for(pair<int, int> p1 : groups[2]){
for(pair<int, int> p2 : groups[3]){
minDistance = min(minDistance, getDistance(p1, p2));
}
}
return minDistance - 1;
}
}; | [
"hwchang.miat@gmail.com"
] | hwchang.miat@gmail.com |
5c96eed961167ede6e2567ee583ea9c8941d177b | 30114f6730aac693971d826f58e46f6d158e6957 | /ComTypeLibfor7/dcom/drawserv/drawserv.cpp | f8d40ec3696746dfcaa1f3a66f579f0401b34f2d | [] | no_license | oudream/vc_example_official | 67111751a416df93cdc4b9f1048d93f482819992 | 8075deebd4755b2a7531a8f918c19ad2e82e2b23 | refs/heads/master | 2020-06-14T08:00:01.267447 | 2019-07-03T01:03:59 | 2019-07-03T01:03:59 | 194,953,887 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,817 | cpp | // DrawServ.cpp : Implementation of WinMain
//
// This is a part of the ActiveX Template Library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// ActiveX Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// ActiveX Template Library product.
//
// You will need the NT SUR Beta 2 SDK or VC 4.2 in order to build this
// project. This is because you will need MIDL 3.00.15 or higher and new
// headers and libs. If you have VC 4.2 installed, then everything should
// already be configured correctly.
// Note: Proxy/Stub Information
// To build a separate proxy/stub DLL,
// run nmake -f DrawServps.mak in the project directory.
#include "predraw.h"
#include "drawres.h"
#include "initguid.h"
#include "DrawServ.h"
#include "DrawObj.h"
#define IID_DEFINED
#include "DrawServ_i.c"
#include <stdio.h>
CServiceModule _Module;
BEGIN_OBJECT_MAP(ObjectMap)
OBJECT_ENTRY(CLSID_CDrawServ, CDrawObj)
END_OBJECT_MAP()
// Although some of these functions are big they are declared inline since they are only used once
inline HRESULT CServiceModule::RegisterServer(BOOL bRegTypeLib)
{
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr))
return hr;
// Remove any previous service since it may point to
// the incorrect file
Uninstall();
// Add service entries
UpdateRegistryFromResource(IDR_DrawServ, TRUE);
// Create service
Install();
// Add object entries
HRESULT hRes = CComModule::RegisterServer(bRegTypeLib);
CoUninitialize();
return hRes;
}
inline HRESULT CServiceModule::UnregisterServer()
{
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr))
return hr;
// Remove service entries
UpdateRegistryFromResource(IDR_DrawServ, FALSE);
// Remove service
Uninstall();
// Remove object entries
CComModule::UnregisterServer();
CoUninitialize();
return S_OK;
}
inline void CServiceModule::Init(_ATL_OBJMAP_ENTRY* p, HINSTANCE h, UINT nServiceNameID)
{
CComModule::Init(p, h);
m_bService = TRUE;
LoadString(h, nServiceNameID, m_szServiceName, sizeof(m_szServiceName) / sizeof(TCHAR));
// set up the initial service status
m_hServiceStatus = NULL;
m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
m_status.dwCurrentState = SERVICE_STOPPED;
m_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
m_status.dwWin32ExitCode = 0;
m_status.dwServiceSpecificExitCode = 0;
m_status.dwCheckPoint = 0;
m_status.dwWaitHint = 0;
}
LONG CServiceModule::Unlock()
{
LONG l = CComModule::Unlock();
if (l == 0 && !m_bService)
PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
return l;
}
BOOL CServiceModule::IsInstalled()
{
BOOL bResult = FALSE;
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM != NULL)
{
SC_HANDLE hService = ::OpenService(hSCM, m_szServiceName, SERVICE_QUERY_CONFIG);
if (hService != NULL)
{
bResult = TRUE;
::CloseServiceHandle(hService);
}
::CloseServiceHandle(hSCM);
}
return bResult;
}
inline BOOL CServiceModule::Install()
{
if (IsInstalled())
return TRUE;
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (hSCM == NULL)
{
if (GetLastError() == ERROR_ACCESS_DENIED)
MessageBox(NULL, _T("Please verify that you are an administrator or other user authorized to create services on this machine"), _T("Couldn't open service manager"), MB_OK);
else
MessageBox(NULL, _T("Please verify that the service control manager is accessible"), _T("Couldn't open service manager"), MB_OK);
return FALSE;
}
// Get the executable file path
TCHAR szFilePath[_MAX_PATH];
::GetModuleFileName(NULL, szFilePath, _MAX_PATH);
SC_HANDLE hService = ::CreateService(
hSCM, m_szServiceName, m_szServiceName,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
szFilePath, NULL, NULL, _T("RPCSS\0"), NULL, NULL);
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
MessageBox(NULL, _T("Couldn't create service"), m_szServiceName, MB_OK);
return FALSE;
}
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
return TRUE;
}
inline BOOL CServiceModule::Uninstall()
{
if (!IsInstalled())
return TRUE;
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
MessageBox(NULL, _T("Couldn't open service manager"), m_szServiceName, MB_OK);
return FALSE;
}
SC_HANDLE hService = ::OpenService(hSCM, m_szServiceName, DELETE);
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
MessageBox(NULL, _T("Couldn't open service"), m_szServiceName, MB_OK);
return FALSE;
}
BOOL bDelete = ::DeleteService(hService);
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
if (bDelete)
return TRUE;
MessageBox(NULL, _T("Service could not be deleted"), m_szServiceName, MB_OK);
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////////////
// Logging functions
void CServiceModule::LogEvent(LPCTSTR pFormat, ...)
{
TCHAR chMsg[256];
HANDLE hEventSource;
LPTSTR lpszStrings[1];
va_list pArg;
va_start(pArg, pFormat);
_vstprintf_s(chMsg, 256, pFormat, pArg);
va_end(pArg);
lpszStrings[0] = chMsg;
if (m_bService)
{
/* Get a handle to use with ReportEvent(). */
hEventSource = RegisterEventSource(NULL, m_szServiceName);
if (hEventSource)
{
/* Write to event log. */
ReportEvent(hEventSource, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, (LPCTSTR*) &lpszStrings[0], NULL);
DeregisterEventSource(hEventSource);
}
}
else
{
// As we are not running as a service, just write the error to the console.
_putts(chMsg);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Service startup and registration
inline void CServiceModule::Start()
{
SERVICE_TABLE_ENTRY st[] =
{
{ m_szServiceName, _ServiceMain },
{ NULL, NULL }
};
if (!::StartServiceCtrlDispatcher(st))
{
m_bService = FALSE;
if (GetLastError()==ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
Run();
}
}
inline void CServiceModule::ServiceMain(DWORD /* dwArgc */, LPTSTR* /* lpszArgv */)
{
// Register the control request handler
m_status.dwCurrentState = SERVICE_START_PENDING;
m_hServiceStatus = RegisterServiceCtrlHandler(m_szServiceName, _Handler);
if (m_hServiceStatus == NULL)
{
LogEvent(_T("Handler not installed"));
return;
}
SetServiceStatus(SERVICE_START_PENDING);
m_status.dwWin32ExitCode = S_OK;
m_status.dwCheckPoint = 0;
m_status.dwWaitHint = 0;
// When the Run function returns, the service has stopped.
Run();
SetServiceStatus(SERVICE_STOPPED);
LogEvent(_T("Service stopped"));
}
inline void CServiceModule::Handler(DWORD dwOpcode)
{
switch (dwOpcode)
{
case SERVICE_CONTROL_STOP:
SetServiceStatus(SERVICE_STOP_PENDING);
PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
break;
case SERVICE_CONTROL_PAUSE:
break;
case SERVICE_CONTROL_CONTINUE:
break;
case SERVICE_CONTROL_INTERROGATE:
break;
case SERVICE_CONTROL_SHUTDOWN:
break;
default:
LogEvent(_T("Bad service request"));
}
}
void WINAPI CServiceModule::_ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
{
_Module.ServiceMain(dwArgc, lpszArgv);
}
void WINAPI CServiceModule::_Handler(DWORD dwOpcode)
{
_Module.Handler(dwOpcode);
}
void CServiceModule::SetServiceStatus(DWORD dwState)
{
m_status.dwCurrentState = dwState;
::SetServiceStatus(m_hServiceStatus, &m_status);
}
void CServiceModule::Run()
{
HRESULT hr;
_Module.dwThreadID = GetCurrentThreadId();
// If you are running on NT 4.0 or higher you can use the following call
// instead to make your service free threaded.
// This means that calls come in on a random RPC thread
hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
// Otherwise, for single threaded use
// hr = CoInitialize(NULL);
_ASSERTE(SUCCEEDED(hr));
// In NT 4.0 and higher where DCOM is supported you may wish to initialize
// the security layer. The following code will give you a DCOM service which
// would allow ALL users access to objects
CSecurityDescriptor sd;
sd.InitializeFromThreadToken();
hr = CoInitializeSecurity(NULL, -1, NULL, NULL,
RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IDENTIFY, NULL, EOAC_NONE, NULL);
_ASSERTE(SUCCEEDED(hr));
// If you wish to have your object creatable remotely using DCOM use the following
hr = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER, REGCLS_MULTIPLEUSE);
// Otherwise, only local activation
// hr = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE);
_ASSERTE(SUCCEEDED(hr));
LogEvent(_T("Service started"));
SetServiceStatus(SERVICE_RUNNING);
MSG msg;
while (GetMessage(&msg, 0, 0, 0))
DispatchMessage(&msg);
_Module.RevokeClassObjects();
CoUninitialize();
}
/////////////////////////////////////////////////////////////////////////////
//
extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
LPTSTR lpCmdLine, int /* nShowCmd */)
{
_Module.Init(ObjectMap, hInstance, IDS_SERVICENAME);
TCHAR szTokens[] = _T("-/");
TCHAR* nextToken;
LPTSTR lpszToken = _tcstok_s(lpCmdLine, szTokens, &nextToken);
while (lpszToken != NULL)
{
if (_tcsicmp(lpszToken, _T("UnregServer"))==0)
return _Module.UnregisterServer();
if (_tcsicmp(lpszToken, _T("RegServer"))==0)
return _Module.RegisterServer(TRUE);
lpszToken = _tcstok_s(NULL, szTokens, &nextToken);
}
_Module.Start();
// When we get here, the service has been stopped
return _Module.m_status.dwWin32ExitCode;
}
| [
"oudream@126.com"
] | oudream@126.com |
88bc895ed92ae0e2aa62db9a6c4ef3f4555ab9bd | 40a169a21516453364b641428fb5b4e11ef1338d | /main.cpp | 3b00c98c470e5af5fb9d4450dcb30cb4961ad5a9 | [] | no_license | blagalucianflorin/OOP-Tema-1 | 35fb484f104e86a750b3429130069f4aa066db6b | c7c013d01813ecc1fc27726ecaeba52550d0a1e4 | refs/heads/master | 2021-04-24T05:17:58.016861 | 2020-03-25T21:04:36 | 2020-03-25T21:04:36 | 250,083,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | cpp | #include <iostream>
#include "List.h"
int main() {
List myList1({1, 2, 3, 4});
List myList2({5, 6, 7});
List myList3({8, 9, 10});
List myList4;
myList4 = myList1 + myList2 + myList3;
myList4 >> 11 >> 12;
myList4[9] = 10;
std::cout << myList4 << std::endl;
std::cout << myList4[myList4.find(2)] << std::endl;
// Throws std::out_of_range
// std::cout << myList4[20] << std::endl;
return 0;
}
| [
"blaga.lucianflorin@gmail.com"
] | blaga.lucianflorin@gmail.com |
31e9feb5a0b0cc01c2bcf47d6703f81307ea09ea | b889757935d14cac4932874fd99451b96c5f43f5 | /umbc/CMSC/2XX/202/Projects/Proj2/card.cpp | 3b778ad7c560b84b34eaea72d6818db3f93c707f | [] | no_license | RobRoseKnows/umbc-cs-projects | c98c8fb201b9c6fe29a7e30d7b048d0c41e7c093 | f6c44681e15587f31100dcc9d6ccbdef670580dc | refs/heads/master | 2020-06-12T21:45:20.273594 | 2019-12-19T23:45:48 | 2019-12-19T23:45:48 | 75,505,149 | 2 | 0 | null | 2018-11-06T01:36:01 | 2016-12-03T22:57:09 | C | UTF-8 | C++ | false | false | 1,582 | cpp | /* File: card.cpp
* Name: Robert Rose
* Date: 3/8/16
* E-mail: robrose2@umbc.edu
* Section: Thursday 11:30
CMSC 202 Computer Science II
Spring 2016 Project 2
Implementation of Card member functions.
See card.h for documentation.
*/
#include <iostream>
#include <string>
#include "card.h"
using namespace std;
// Default constructor marks card as invalid
//
Card::Card() {
m_suit = Invalid;
m_points = 0;
}
Card::Card(cSuit s, cPoints p) {
if (s == Clubs || s == Diamonds || s == Hearts || s == Spades) {
m_suit = s;
} else {
m_suit = Invalid;
m_points = 0;
}
if (p >= 1 && p <= 14 && m_suit != Invalid) {
m_points = p;
} else {
m_suit = Invalid;
m_points = 0;
}
}
Card::cPoints Card::points() {
return m_points;
}
Card::cSuit Card::suit() {
return m_suit;
}
void Card::print() {
// Check to make sure the card isn't invalid.
if (m_points == 0 || m_suit == Invalid) {
cout << "Invalid Card";
} else if (m_points >= 2 && m_points <= 10) {
cout << m_points;
} else {
switch (m_points) {
case 11:
cout << "Jack";
break;
case 12:
cout << "Queen";
break;
case 13:
cout << "King";
break;
case 14:
cout << "Ace";
break;
default:
cout << "Invalid";
break;
}
}
cout << " of ";
switch (m_suit) {
case (Invalid):
cout << "Invalid";
break;
case (Clubs):
cout << "Clubs";
break;
case (Diamonds):
cout << "Diamonds";
break;
case (Hearts):
cout << "Hearts";
break;
case (Spades):
cout << "Spades";
break;
default:
cout << "Default";
break;
}
cout << endl;
}
| [
"bertra97@gmail.com"
] | bertra97@gmail.com |
a69a1f63d846549a577e1f6f99066a7042b0b88a | 0cf4d867ca87f205d5e65e37966e48a30bd6098f | /PolyRender/AutoTest.h | a5da26af92a908a9c831d28bb18fd91b6a21c955 | [
"ISC"
] | permissive | pauldoo/scratch | 344fd0c2a081caca7c75be93279b9b531ed53ee7 | 400e2647e1026402c8b72828f694db3cda682d0d | refs/heads/master | 2023-03-08T19:27:29.911309 | 2022-05-10T18:40:30 | 2022-05-10T18:40:30 | 393,548 | 2 | 1 | ISC | 2023-03-02T22:56:23 | 2009-12-03T00:37:13 | C++ | UTF-8 | C++ | false | false | 138 | h | #pragma once
#include "ITestable.h"
class AutoTest : public ITestable {
public:
void Execute();
std::string Name() const;
};
| [
"paul.richards@gmail.com"
] | paul.richards@gmail.com |
97d42b6c9991ca0496108b48febdf08e4e3e87d6 | 09b0c367b7ffb93c74779a3bb759a2975b766691 | /sorting algorithms/sortbasic/06-Bubble-Sort/SelectionSort.h | 4ce4aa349aa235a886ba0a409e97b21956a5277f | [] | no_license | hanwenfei/hanwenfei.github.io | 21f419ffcd8694daa6f25f4d9fbdc58680f615b0 | 8612fef1c6a835185dcc9a5f3ed2dd170ad4a0ca | refs/heads/master | 2021-01-21T06:02:23.729044 | 2017-09-02T00:18:45 | 2017-09-02T00:18:45 | 101,934,549 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 490 | h | #ifndef INC_04_INSERTION_SORT_SELECTIONSORT_H
#define INC_04_INSERTION_SORT_SELECTIONSORT_H
#include <iostream>
#include <algorithm>
using namespace std;
template<typename T>
void selectionSort(T arr[], int n){
for(int i = 0 ; i < n ; i ++){
int minIndex = i;
for( int j = i + 1 ; j < n ; j ++ )
if( arr[j] < arr[minIndex] )
minIndex = j;
swap( arr[i] , arr[minIndex] );
}
}
#endif //INC_04_INSERTION_SORT_SELECTIONSORT_H
| [
"31489648+hanwenfei@users.noreply.github.com"
] | 31489648+hanwenfei@users.noreply.github.com |
ce6e49a83bf7132a7a34679709d4a8a05eb48f58 | db74a616de1d34c98549e3977fe299c808396db3 | /src/transition.h | 9019459c28e0eab5f789f3c2ae482d7046c73e9c | [] | no_license | tushar117/QueryBlazer | 52e539eb82a0f1dddc4152f29879716c1942b23c | 77d900f45ed127ddb49dfe66ffa53363dc4b24c3 | refs/heads/master | 2023-08-25T17:54:14.449565 | 2021-10-12T19:01:33 | 2021-10-12T19:01:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,113 | h | /*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef QUERYBLAZER_EMITTINGPHI_H
#define QUERYBLAZER_EMITTINGPHI_H
#include "common.h"
#include "fst/fstlib.h"
namespace qbz {
/**
* Make transitions (possibly phi-transition)
* @param graph: deterministic fst graph
* @param matcher: fst matcher to use (either sorted or generic); this is
* because construction of matcher is very slow
* @param ilabel: if phi, will take phi transition(s); else, will make viable
* transition (including phi)
* @param olabels: olabel vector to which to append olabels
* @param out_state: if not null, destination state will be written
* @return: output labels collected during the transition (will ignore epsilon
* outputs)
*/
template <typename FST, typename Matcher>
void MakeTransitions(const FST &graph, Matcher &matcher, int in_state,
int ilabel, std::vector<int> *olabels = nullptr,
int *out_state = nullptr) {
auto state = in_state;
auto break_flag = false;
while (!break_flag) {
matcher.SetState(state);
if (matcher.Find(ilabel)) {
break_flag = true;
} else {
QBZ_ASSERT(matcher.Find(IDX_PHI),
"no viable transition found at state " +
std::to_string(state));
}
const auto &arc = matcher.Value();
if (olabels && arc.olabel != IDX_EPSILON)
olabels->push_back(arc.olabel);
state = arc.nextstate;
}
// make phi transition if state is not an exit state and state has only a
// single phi transition
while (graph.Final(state) == fst::StdArc::Weight::Zero() &&
graph.NumArcs(state) == 1) {
matcher.SetState(state);
if (!matcher.Find(IDX_PHI)) break;
const auto &arc = matcher.Value();
if (olabels && arc.olabel != IDX_EPSILON)
olabels->push_back(arc.olabel);
state = arc.nextstate;
}
if (out_state) *out_state = state;
}
/**
* Make phi-transitions until exit state is reached
* @param graph: deterministic graph
*/
template <typename FST, typename Matcher>
float MakeExitTransitions(const FST &graph, Matcher &matcher, int in_state,
std::vector<int> *olabels = nullptr,
int *out_state = nullptr) {
auto state = in_state;
float cost = 0.0f;
while (graph.Final(state) == fst::StdArc::Weight::Zero()) {
matcher.SetState(state);
QBZ_ASSERT(matcher.Find(IDX_PHI), "Final state transitions not found");
const auto &arc = matcher.Value();
state = arc.nextstate;
cost += arc.weight.Value();
if (arc.olabel != IDX_EPSILON && olabels)
olabels->push_back(arc.olabel);
}
cost += graph.Final(state).Value();
if (out_state) *out_state = state;
return cost;
}
} // namespace qbz
#endif // QUERYBLAZER_EMITTINGPHI_H
| [
"ykang@salesforce.com"
] | ykang@salesforce.com |
edf7929a058859c50723bdfc00bb061382dfcb02 | 0a119572a9016b642e9103a3ef3d465fccf05016 | /dsacpp-vs2019.210216/src/string_pm_bf2/pm_brute2.cpp | 82505d07ed692dea67d9ed80a860210cf5a998f7 | [] | no_license | zcaxer/algorithm | 61c5cec7a755ee78bc1907819fb495d8c488edda | af9da8157710f51ca52c0b9c38c6bbcd1aac5f9a | refs/heads/main | 2023-07-11T14:52:49.937353 | 2021-08-19T13:59:07 | 2021-08-19T13:59:07 | 374,084,759 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,680 | cpp | /******************************************************************************************
* Data Structures in C++
* ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3
* Junhui DENG, deng@tsinghua.edu.cn
* Computer Science & Technology, Tsinghua University
* Copyright (c) 2003-2020. All rights reserved.
******************************************************************************************/
/*DSA*/#include <cstdio>
#include <cstring>
/*DSA*/void showProgress ( char*, char*, int, int );
/******************************************************************************************
* Text : 0 1 2 . . . i i+1 . . . i+j . . n-1
* ------------------------|-------------------|------------
* Pattern : 0 1 . . . j . .
* |-------------------|
******************************************************************************************/
int match ( char* P, char* T ) { //串匹配算法(Brute-force-2)
size_t n = strlen ( T ), i = 0; //文本串长度、与模式串首字符的对齐位置
size_t m = strlen ( P ), j; //模式串长度、当前接受比对字符的位置
for ( i = 0; i < n - m + 1; i++ ) { //文本串从第i个字符起,与
for ( j = 0; j < m; j++ ) //模式串中对应的字符逐个比对
/*DSA*/{showProgress ( T, P, i, j ); getchar();
if ( T[i + j] != P[j] ) break; //若失配,模式串整体右移一个字符,再做一轮比对
/*DSA*/}
if ( j >= m ) break; //找到匹配子串
}
return i; //如何通过返回值,判断匹配结果?
} | [
"zcaxer@gmail.com"
] | zcaxer@gmail.com |
3d91ce79e9353ab980e73b3e6d7ae50bf0cfd97f | 6b7cb5e1a66f4af9ea0a8b675a6abb8f6927b9fc | /src/04_RealTime/NimotsuKunRealTime/File.cpp | f1c319c3903a31829c0baa32bd6f1981c9b34ca8 | [] | no_license | supercaracal/game-programmer-book-build | dc405763ed255e81ea8244d2c48dc24a8d98293e | c9e1f65cab3f59a4d552128d0ee22233d79b2773 | refs/heads/master | 2022-06-10T14:17:00.122380 | 2020-04-29T04:03:14 | 2020-04-29T04:03:14 | 259,812,505 | 1 | 0 | null | 2020-04-29T03:14:35 | 2020-04-29T03:14:34 | null | WINDOWS-1250 | C++ | false | false | 796 | cpp | #include "File.h"
#include <fstream>
using namespace std;
File::File( const char* filename ) : mSize( 0 ), mData( 0 ){
ifstream in( filename, ifstream::binary );
if ( in ){
in.seekg( 0, ifstream::end );
mSize = static_cast< int >( in.tellg() );
in.seekg( 0, ifstream::beg );
mData = new char[ mSize ];
in.read( mData, mSize );
}
}
File::~File(){
delete[] mData;
mData = 0;
}
int File::getSize() const {
return mSize;
}
const char* File::getData() const {
return mData;
}
//unsignedŽć‚čŹo‚µ
unsigned File::getUnsigned( int p ) const {
const unsigned char* up;
up = reinterpret_cast< const unsigned char* >( mData );
unsigned r = up[ p ];
r |= up[ p + 1 ] << 8;
r |= up[ p + 2 ] << 16;
r |= up[ p + 3 ] << 24;
return r;
}
| [
"slash@watery.dip.jp"
] | slash@watery.dip.jp |
07dd95bdf2acde511873022de9d5c2d0d64b3f11 | f83acb6c676b18a74b8a7cfac2b3a83bfd1d6fc8 | /paddle.h | d2853dc2ab6e4316a175c1eb4fcfcc9d724dfbe5 | [] | no_license | OhanaMeansFamily/QtCreator | e15ebe2f2d02374fae483f9f2633ab7b59c27bf8 | a79f006d936a712443227ffbc964ddb396ee53e3 | refs/heads/master | 2021-01-01T18:11:18.258670 | 2014-05-02T09:16:38 | 2014-05-02T09:16:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | h | #ifndef PADDLE_H
#define PADDLE_H
#include <QPainter>
#include "configurationmanager.h"
class Paddle
{
public:
Paddle();
Paddle(int x1, int y1, int x2, int y2,int x3, int y3, int x4, int y4);
void render(QPainter &painter, Paddle *p, int pressed);
int getX1Coordinate();
int getX2Coordinate();
int getY1Coordinate();
int getY2Coordinate();
int getX3Coordinate();
int getX4Coordinate();
int getY3Coordinate();
int getY4Coordinate();
void changeX(int change);
~Paddle();
private:
int height;
int width;
int coordinateX1;
int coordinateY1;
int coordinateX2;
int coordinateY2;
int coordinateX3;
int coordinateY3;
int coordinateX4;
int coordinateY4;
};
#endif // PADDLE_H
| [
"yermek@vlan-2659-10-19-230-236.student.wireless.sydney.edu.au"
] | yermek@vlan-2659-10-19-230-236.student.wireless.sydney.edu.au |
d968f946a895d4ba7ac752e019db9cc0aca90ab8 | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-datapipeline/include/aws/datapipeline/model/Field.h | 8ad45653baa1625e75b07545bd3d848e36545685 | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 5,198 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/datapipeline/DataPipeline_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace DataPipeline
{
namespace Model
{
/**
* <p>A key-value pair that describes a property of a pipeline object. The value is
* specified as either a string value (<code>StringValue</code>) or a reference to
* another object (<code>RefValue</code>) but not as both.</p><p><h3>See Also:</h3>
* <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/Field">AWS
* API Reference</a></p>
*/
class AWS_DATAPIPELINE_API Field
{
public:
Field();
Field(const Aws::Utils::Json::JsonValue& jsonValue);
Field& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The field identifier.</p>
*/
inline const Aws::String& GetKey() const{ return m_key; }
/**
* <p>The field identifier.</p>
*/
inline void SetKey(const Aws::String& value) { m_keyHasBeenSet = true; m_key = value; }
/**
* <p>The field identifier.</p>
*/
inline void SetKey(Aws::String&& value) { m_keyHasBeenSet = true; m_key = value; }
/**
* <p>The field identifier.</p>
*/
inline void SetKey(const char* value) { m_keyHasBeenSet = true; m_key.assign(value); }
/**
* <p>The field identifier.</p>
*/
inline Field& WithKey(const Aws::String& value) { SetKey(value); return *this;}
/**
* <p>The field identifier.</p>
*/
inline Field& WithKey(Aws::String&& value) { SetKey(value); return *this;}
/**
* <p>The field identifier.</p>
*/
inline Field& WithKey(const char* value) { SetKey(value); return *this;}
/**
* <p>The field value, expressed as a String.</p>
*/
inline const Aws::String& GetStringValue() const{ return m_stringValue; }
/**
* <p>The field value, expressed as a String.</p>
*/
inline void SetStringValue(const Aws::String& value) { m_stringValueHasBeenSet = true; m_stringValue = value; }
/**
* <p>The field value, expressed as a String.</p>
*/
inline void SetStringValue(Aws::String&& value) { m_stringValueHasBeenSet = true; m_stringValue = value; }
/**
* <p>The field value, expressed as a String.</p>
*/
inline void SetStringValue(const char* value) { m_stringValueHasBeenSet = true; m_stringValue.assign(value); }
/**
* <p>The field value, expressed as a String.</p>
*/
inline Field& WithStringValue(const Aws::String& value) { SetStringValue(value); return *this;}
/**
* <p>The field value, expressed as a String.</p>
*/
inline Field& WithStringValue(Aws::String&& value) { SetStringValue(value); return *this;}
/**
* <p>The field value, expressed as a String.</p>
*/
inline Field& WithStringValue(const char* value) { SetStringValue(value); return *this;}
/**
* <p>The field value, expressed as the identifier of another object.</p>
*/
inline const Aws::String& GetRefValue() const{ return m_refValue; }
/**
* <p>The field value, expressed as the identifier of another object.</p>
*/
inline void SetRefValue(const Aws::String& value) { m_refValueHasBeenSet = true; m_refValue = value; }
/**
* <p>The field value, expressed as the identifier of another object.</p>
*/
inline void SetRefValue(Aws::String&& value) { m_refValueHasBeenSet = true; m_refValue = value; }
/**
* <p>The field value, expressed as the identifier of another object.</p>
*/
inline void SetRefValue(const char* value) { m_refValueHasBeenSet = true; m_refValue.assign(value); }
/**
* <p>The field value, expressed as the identifier of another object.</p>
*/
inline Field& WithRefValue(const Aws::String& value) { SetRefValue(value); return *this;}
/**
* <p>The field value, expressed as the identifier of another object.</p>
*/
inline Field& WithRefValue(Aws::String&& value) { SetRefValue(value); return *this;}
/**
* <p>The field value, expressed as the identifier of another object.</p>
*/
inline Field& WithRefValue(const char* value) { SetRefValue(value); return *this;}
private:
Aws::String m_key;
bool m_keyHasBeenSet;
Aws::String m_stringValue;
bool m_stringValueHasBeenSet;
Aws::String m_refValue;
bool m_refValueHasBeenSet;
};
} // namespace Model
} // namespace DataPipeline
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
7001b559801ffb74ac36302d39f2c02288711be0 | 51c1c5e9b8489ef8afa029b162aaf4c8f8bda7fc | /easyeditor/include/ee/DelaunayTriangulation.h | 3dff801ca872d4a66ce93dd5e65c9f6cea1e3546 | [
"MIT"
] | permissive | aimoonchen/easyeditor | 3e5c77f0173a40a802fd73d7b741c064095d83e6 | 9dabdbfb8ad7b00c992d997d6662752130d5a02d | refs/heads/master | 2021-04-26T23:06:27.016240 | 2018-02-12T02:28:50 | 2018-02-12T02:28:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,525 | h | #ifndef _EASYEDITOR_DELAUNAY_TRIANGULATION_H_
#define _EASYEDITOR_DELAUNAY_TRIANGULATION_H_
#include <SM_Vector.h>
#include <cu/cu_stl.h>
#include <set>
namespace ee
{
class DelaunayTriangulation
{
public:
class Node;
class Triangle;
class NodeCmp;
public:
DelaunayTriangulation(const CU_VEC<sm::vec2>& src, bool bFixBound = true);
~DelaunayTriangulation();
const CU_VEC<Triangle*>& GetAllTris() const { return m_tris; }
const std::set<Node*, NodeCmp>& GetAllNodes() const { return m_nodes; }
void GetAllTrisInRegion(CU_VEC<CU_VEC<sm::vec2> >& triBounds, const CU_VEC<sm::vec2>& region) const;
void GetAllTrisInRegion(CU_VEC<sm::vec2>& triBounds, const CU_VEC<sm::vec2>& region) const;
bool InsertNode(const sm::vec2& p);
void DeleteNodes(const CU_VEC<sm::vec2>& pos);
bool IsBoundNode(const sm::vec2& n) const;
void GetBoundLinePos(CU_VEC<CU_VEC<sm::vec2> >& bounds) const;
void GetSurroundPos(const sm::vec2& pos, CU_VEC<sm::vec2>& surround) const;
public:
class Edge;
class Node
{
public:
Node(const sm::vec2& pos, bool bFake = false)
: m_pos(pos), m_fake(bFake) {}
void GetSurroundTris(CU_VEC<const Triangle*>& tris) const;
bool IsMargin() const;
public:
const sm::vec2 m_pos;
const bool m_fake;
private:
CU_VEC<Edge*> m_edges;
friend class DelaunayTriangulation;
}; // Node
class Edge
{
public:
// only has left tri, this is the edge of bound tri
Edge(Node* in0, Node* in1, const std::pair<Triangle*, Node*>& t)
: m_start(in0), m_end(in1), m_left(t) {}
// from node0 to node1, tri0 is left, tri1 is right
Edge(Node* node0, Node* node1, const std::pair<Triangle*, Node*>& tri0, const std::pair<Triangle*, Node*>& tri1)
: m_start(node0), m_end(node1), m_left(tri0), m_right(tri1) {}
void InsertNode(Node* n);
// left triangle is new
void LegalizeEdge(bool checkRightTri);
void ResetTri(const std::pair<Triangle*, Node*>& tri, bool bLeft) {
bLeft ? m_left = tri : m_right = tri;
}
float Length() const;
bool IsMargin() const {
size_t c = 0;
if (m_left.first->IsFake() || m_left.first->m_removed) ++c;
if (m_right.first->IsFake() || m_right.first->m_removed) ++c;
return c == 1;
}
bool IsErase() const {
size_t c = 0;
if (m_left.first->IsFake() || m_left.first->m_removed) ++c;
if (m_right.first->IsFake() || m_right.first->m_removed) ++c;
return c == 2;
}
bool IsLeafEdge() const { return m_left.first->m_leaf && m_right.first->m_leaf; }
Triangle* LeftTri() const { return m_left.first; }
Triangle* RightTri() const { return m_right.first; }
Node* LeftNode() const { return m_left.second; }
Node* RightNode() const { return m_right.second; }
public:
Node *const m_start, *const m_end;
private:
std::pair<Triangle*, Node*> m_left, m_right;
friend class DelaunayTriangulation;
}; // Edge
class Triangle
{
public:
Triangle();
// create edge info, only used for init boundary triangle
void InitTri(Node* in0, Node* in1, Node* in2);
void InsertNode(Node* n);
void GetNodesPos(CU_VEC<sm::vec2>& pos) const {
for (size_t i = 0; i < 3; ++i)
pos.push_back(m_nodes[i]->m_pos);
}
bool IsFake() const { return m_nodes[0]->m_fake
|| m_nodes[1]->m_fake || m_nodes[2]->m_fake; }
private:
void InitTri(Node* in0, Node* in1, Node* in2, const std::pair<Edge*, bool>& e01,
const std::pair<Edge*, bool>& e12, const std::pair<Edge*, bool>& e20);
void AddChildren(Triangle* t0, Triangle* t1);
void AddChildren(Triangle* t0, Triangle* t1, Triangle* t2);
void GetNextTwoEdge(const Edge* e, std::pair<Edge*, bool>* ret0, std::pair<Edge*, bool>* ret1) const;
private:
bool m_leaf, m_removed;
// array nodes anticlockwise of triangle
// n[0] - n[1] - n[2] is anticlockwise for triangle
Node* m_nodes[3];
// m_e01 is connect n0 with n1 ...
// bool: sign triangle's edge if same direction with edge itself
std::pair<Edge*, bool> m_e01, m_e12, m_e20;
// not have particular order
CU_VEC<Triangle*> m_children, m_parent;
friend class DelaunayTriangulation;
}; // Triangle
private:
bool InsertNode(Node* n);
void DeleteNode(const Node* n);
void InitSurrondTri(const CU_VEC<sm::vec2>& src);
void InitSrcNodes(const CU_VEC<sm::vec2>& src);
void BuildTriangulationStruct();
void SetAllDestTris(bool bFixBound = true);
void GetAllLeafTris();
void SetNodeConnection();
void SetRemovedTris();
float GetAvgEdgesLen() const;
void CheckSingleNode();
void GetAllDelTris(const Node* n, std::set<Triangle*>& totDel) const;
void GetReinsertNodes(const std::set<Triangle*>& totDel, std::set<Node*>& reinsertNodes) const;
void UpdateConnection(const std::set<Triangle*>& totDel);
void UpdateEdgeInfo();
void UpdateEdgeInfo(Triangle* tri, const std::pair<Edge*, bool>& edge);
void Reinsert(const std::set<Node*>& reinsertNodes);
private:
static const size_t BOUND_EXTEND_TIMES = 1000;
static const size_t BOUND_FIX_THRESHOLD_TIMES = 2;
public:
class NodeCmp
{
public:
bool operator () (const Node* lhs, const Node* rhs) const {
return lhs->m_pos.x < rhs->m_pos.x
|| lhs->m_pos.x == rhs->m_pos.x && lhs->m_pos.y < rhs->m_pos.y;
}
}; // NodeCmp
class PosDownCmp
{
public:
bool operator () (const sm::vec2& lhs, const sm::vec2& rhs) const {
return lhs.y > rhs.y
|| lhs.y == rhs.y && lhs.y < rhs.y;
}
}; // PosDownCmp
private:
Triangle* m_root;
std::set<Node*, NodeCmp> m_nodes;
CU_VEC<Triangle*> m_tris;
}; // DelaunayTriangulation
}
#endif // _EASYEDITOR_DELAUNAY_TRIANGULATION_H_ | [
"zhuguang@ejoy.com"
] | zhuguang@ejoy.com |
9782c6fe5a521c605fa65b26cb63907e48c1e79b | ce484ca632aa728ca4d448b91bfee2c2ee08eb6c | /src/views/viewnormaleditor.cpp | 41d2d4632de61d61846dd5bf209f38d87feca76b | [
"MIT"
] | permissive | sharkpp/Jugemutter | 3326357f311c8cf3c2bbefc7cb041182c795afb3 | 8bb07a44f2974dab689478f5148d3a92ce0c50f8 | refs/heads/master | 2021-01-23T03:59:49.980749 | 2017-10-21T08:02:12 | 2017-10-21T08:02:12 | 86,144,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,053 | cpp | #include "viewnormaleditor.h"
#include "ui_viewnormaleditor.h"
#include "mainwindow.h"
#include "preference.h"
#include "autosizetextedit.h"
#include "twitter.h"
#include "accountlist.h"
#include "postprogress.h"
#include <QMessageBox>
ViewNormalEditor::ViewNormalEditor(QWidget *parent)
: PageSelectorView(parent)
, ui(new Ui::ViewNormalEditor)
, m_preference(nullptr)
, postProgress(new PostProgress(this))
, currentAccount(nullptr)
{
ui->setupUi(this);
ui->prefixFreeText->setVisible(false);
ui->prefixContinueText->setVisible(false);
ui->prefixFinishedText->setVisible(false);
ui->postfixFreeText->setVisible(false);
ui->postfixContinueText->setVisible(false);
ui->postfixFinishedText->setVisible(false);
}
ViewNormalEditor::~ViewNormalEditor()
{
delete postProgress;
delete ui;
}
QWidget *ViewNormalEditor::getPostTextWidget(Preference::PostTextType type)
{
switch (type) {
case Preference::postTextPrefixFreeText:
return ui->prefixFreeText;
case Preference::postTextPrefixContinue:
ui->prefixContinueText->setText(m_preference->postPrefixContinueText());
return ui->prefixContinueText;
case Preference::postTextPrefixFinished:
ui->prefixFinishedText->setText(m_preference->postPrefixFinishedText());
return ui->prefixFinishedText;
case Preference::postTextPostfixFreeText:
return ui->postfixFreeText;
case Preference::postTextPostfixContinue:
ui->postfixContinueText->setText(m_preference->postPostfixContinueText());
return ui->postfixContinueText;
case Preference::postTextPostfixFinished:
ui->postfixFinishedText->setText(m_preference->postPostfixFinishedText());
return ui->postfixFinishedText;
default:
return nullptr;
}
}
TwitterTextSplitter::TextTypeValue ViewNormalEditor::textTypeValueFromPostType(Preference::PostTextType type)
{
switch (type) {
case Preference::postTextPrefixFreeText:
return TwitterTextSplitter::TextTypeValue(
TwitterTextSplitter::textPrefixFreeText,
ui->prefixFreeText->toPlainText()
);
case Preference::postTextPrefixContinue:
return TwitterTextSplitter::TextTypeValue(
TwitterTextSplitter::textPrefixContinue,
m_preference->postPrefixContinueText()
);
case Preference::postTextPrefixFinished:
return TwitterTextSplitter::TextTypeValue(
TwitterTextSplitter::textPrefixFinished,
m_preference->postPrefixFinishedText()
);
case Preference::postTextPostfixFreeText:
return TwitterTextSplitter::TextTypeValue(
TwitterTextSplitter::textPostfixFreeText,
ui->postfixFreeText->toPlainText()
);
case Preference::postTextPostfixContinue:
return TwitterTextSplitter::TextTypeValue(
TwitterTextSplitter::textPostfixContinue,
m_preference->postPostfixContinueText()
);
case Preference::postTextPostfixFinished:
return TwitterTextSplitter::TextTypeValue(
TwitterTextSplitter::textPostfixFinished,
m_preference->postPostfixFinishedText()
);
default:
return TwitterTextSplitter::TextTypeValue((TwitterTextSplitter::TextType)-1, "");
}
}
void ViewNormalEditor::setPreference(Preference *preference)
{
m_preference = preference;
connect(m_preference, &Preference::update,
this, &ViewNormalEditor::onPreferenceUpdate);
// ui->prefix->blockSignals(true);
// ui->postfix->blockSignals(true);
onPreferenceUpdate();
// ui->prefix->blockSignals(false);
// ui->postfix->blockSignals(false);
}
void ViewNormalEditor::setDocument(PageSelectorDocument *document)
{
PageSelectorView::setDocument(document);
currentAccount = nullptr;
if (EditorPageDocument *document_
= qobject_cast<EditorPageDocument*>( document )) {
if (const TwitterAccount *account_
= qobject_cast<const TwitterAccount*>(document_->account())) {
currentAccount = account_->twitter();
connect(currentAccount, &Twitter::tweeted,
this, &ViewNormalEditor::onTwitterTweeted);
connect(currentAccount, &Twitter::tweetFailure,
this, &ViewNormalEditor::onTwitterTweetFailure);
ui->tweetButton->setEnabled(currentAccount->isAuthenticated());
ui->prefixFreeText->setPlainText(m_preference->postPrefixFreeText());
ui->tweetEditor->setPlainText("");
ui->postfixFreeText->setPlainText(m_preference->postPostfixFreeText());
ui->tweetEditor->setFocus();
}
}
}
void ViewNormalEditor::updateSplitStatus()
{
TwitterTextSplitter splitter;
QString text = ui->tweetEditor->toPlainText();
QList<TwitterTextSplitter::TextTypeValue> list;
list.clear();
foreach (auto type, m_preference->postPrefixText()) {
list.append(textTypeValueFromPostType(type));
}
splitter.setPrefix(list);
splitter.setText(text);
list.clear();
foreach (auto type, m_preference->postPostfixText()) {
list.append(textTypeValueFromPostType(type));
}
splitter.setPostfix(list);
ui->tweetEditor->setTextSplitter(splitter);
tweetQueue = splitter.split();
ui->partitionCount->setText(QString("%1").arg(tweetQueue.size()));
ui->textLength->setText(QString("%1").arg(text.size()));
ui->totalLength->setText(QString("%1").arg(splitter.size()));
}
void ViewNormalEditor::startPost()
{
postProgress->setCount( tweetQueue.size() );
postProgress->show();
postProgress->raise();
postProgress->activateWindow();
}
void ViewNormalEditor::stepPost()
{
postProgress->step();
}
void ViewNormalEditor::finishPost()
{
postProgress->step();
postProgress->hide();
}
void ViewNormalEditor::onPreferenceUpdate()
{
for (QLayoutItem *child;
(child = ui->prefixLayout->takeAt(0)) != 0;) {
child->widget()->setVisible(false);
delete child;
}
foreach (auto type, m_preference->postPrefixText()) {
QWidget *w = getPostTextWidget(type);
w->setVisible(true);
ui->prefixLayout->addWidget(w);
}
for (QLayoutItem *child;
(child = ui->postfixLayout->takeAt(0)) != 0;) {
child->widget()->setVisible(false);
delete child;
}
foreach (auto type, m_preference->postPostfixText()) {
QWidget *w = getPostTextWidget(type);
w->setVisible(true);
ui->postfixLayout->addWidget(w);
}
updateSplitStatus();
}
void ViewNormalEditor::onTwitterTweeted(const QString &tweetId)
{
qDebug() << "add tweet" << tweetId;
if (tweetQueue.isEmpty()) {
finishPost();
QMessageBox::information(this, qAppName(), tr("Your post has been completed."));
return;
}
// まだ残りがあれば投稿する
stepPost();
QString tweetText = tweetQueue.front().toString();
tweetQueue.pop_front();
currentAccount->tweet(tweetText, tweetId);
}
void ViewNormalEditor::onTwitterTweetFailure(const QList<QPair<int, QString> > & errors)
{
qDebug() << "error post tweet" << errors;
QMessageBox::warning(this, qAppName(), tr("Posting failed."));
finishPost();
}
// ツイート投稿
void ViewNormalEditor::on_tweetButton_clicked()
{
tweetQueue.clear();
// まずは認証済みかチェック
if (!currentAccount ||
!currentAccount->isAuthenticated()) {
return;
}
TwitterTextSplitter splitter;
QList<TwitterTextSplitter::TextTypeValue> list;
list.clear();
foreach (auto type, m_preference->postPrefixText()) {
list.append(textTypeValueFromPostType(type));
}
splitter.setPrefix(list);
splitter.setText( ui->tweetEditor->toPlainText() );
list.clear();
foreach (auto type, m_preference->postPostfixText()) {
list.append(textTypeValueFromPostType(type));
}
splitter.setPostfix(list);
ui->tweetEditor->setTextSplitter(splitter);
tweetQueue = splitter.split();
if (tweetQueue.isEmpty()) {
return;
}
startPost();
#ifndef QT_NO_DEBUG
QString msg;
QList<SplittedItem>::iterator i;
for (i = tweetQueue.begin(); i != tweetQueue.end(); ++i) {
qDebug() << QString("[%1]\n").arg(i->toString());
msg += QString("[%1]\n").arg(i->toString());
}
QMessageBox::information(this, "", msg);
#endif
QString tweetText = tweetQueue.front().toString();
tweetQueue.pop_front();
currentAccount->tweet(tweetText);
}
void ViewNormalEditor::on_prefixFreeText_textChanged()
{
updateSplitStatus();
}
void ViewNormalEditor::on_postfixFreeText_textChanged()
{
updateSplitStatus();
}
void ViewNormalEditor::on_tweetEditor_textChanged()
{
updateSplitStatus();
}
| [
"touroku@sharkpp.net"
] | touroku@sharkpp.net |
146de12777b1c036b8222a86038c1214a465d7f1 | 205ee84cf7b61ca4af8ef3bd8a907262a36f4de7 | /queue_stack/main.cpp | 99a6a953c4d42f965dddd91eea434841c5435555 | [] | no_license | igornatan/advanced-structures | c6f32cf3f5461f111039d8084c4b8cdca9cd4b83 | 5c356b04bfca2b72e1f2050490ccd94b0fb44ce2 | refs/heads/master | 2021-01-16T13:31:27.109887 | 2020-02-27T23:02:38 | 2020-02-27T23:02:38 | 243,139,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | cpp | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
struct stack {
int x;
struct stack *p;
};
stack *insert(){
struct stack *p1;
p1 = (struct stack*) malloc(sizeof(struct stack));
p1->p = nullptr;
std::cout << "Type your code: " << std::endl;
scanf("%d", p1->x);
}
void print(){
}
int main() {
std::cout << "Hello, World!" << std::endl;
struct stack *top;
struct stack *bot;
bool first = true;
char option;
do {
std::cout << "I - Insert" << std::endl;
std::cout << "P - Print" << std::endl;
std::cout << "E - Exit" << std::endl;
} while (option != 'a' && option != 'S');
return 0;
} | [
"igor.natanbagio@gmail.com"
] | igor.natanbagio@gmail.com |
aa30dd045b6265cde57ba241548ee3b5b7b778a4 | b53f1953f5520e5208f34bb87d42d86ead33dba6 | /src/Platform/Code/ShareLib/loki-0.1.5/include/loki/SmallObj.h | b3a89b0198f9aab6ce385d20d2ea32acdfa511ae | [] | no_license | Jonkoping/data | e01b2ded3335742165ea3feb9c06e0d111ab5fb7 | 03de309b5f7998f394b2ed1d8b0bc0114ca686f3 | refs/heads/master | 2020-06-30T18:24:29.032625 | 2018-01-04T09:18:55 | 2018-01-04T09:18:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,717 | h | ////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2001 by Andrei Alexandrescu
// This code accompanies the book:
// Alexandrescu, Andrei. "Modern C++ Design: Generic Programming and Design
// Patterns Applied". Copyright (c) 2001. Addison-Wesley.
// Permission to use, copy, modify, distribute and sell this software for any
// purpose is hereby granted without fee, provided that the above copyright
// notice appear in all copies and that both that copyright notice and this
// permission notice appear in supporting documentation.
// The author or Addison-Wesley Longman make no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////
// $Header: //BQT/VM67/Prjbase3/QSyncher_V2/PlatformTool/Code/ShareLib/loki-0.1.5/include/loki/SmallObj.h.-arc 1.1 Apr 01 2009 14:21:52 Kevin Tai $
#ifndef LOKI_SMALLOBJ_INC_
#define LOKI_SMALLOBJ_INC_
#include "LokiExport.h"
#include "Threads.h"
#include "Singleton.h"
#include <cstddef>
#include <new> // needed for std::nothrow_t parameter.
#ifndef LOKI_DEFAULT_CHUNK_SIZE
#define LOKI_DEFAULT_CHUNK_SIZE 4096
#endif
#ifndef LOKI_MAX_SMALL_OBJECT_SIZE
#define LOKI_MAX_SMALL_OBJECT_SIZE 256
#endif
#ifndef LOKI_DEFAULT_OBJECT_ALIGNMENT
#define LOKI_DEFAULT_OBJECT_ALIGNMENT 4
#endif
#ifndef LOKI_DEFAULT_SMALLOBJ_LIFETIME
#define LOKI_DEFAULT_SMALLOBJ_LIFETIME LongevityLifetime::DieAsSmallObjectParent
#endif
#if defined(LOKI_SMALL_OBJECT_USE_NEW_ARRAY) && defined(_MSC_VER)
#pragma message("Don't define LOKI_SMALL_OBJECT_USE_NEW_ARRAY when using a Microsoft compiler to prevent memory leaks.")
#pragma message("now calling '#undef LOKI_SMALL_OBJECT_USE_NEW_ARRAY'")
#undef LOKI_SMALL_OBJECT_USE_NEW_ARRAY
#endif
/// \defgroup SmallObjectGroup Small objects
///
/// \defgroup SmallObjectGroupInternal Internals
/// \ingroup SmallObjectGroup
namespace Loki
{
namespace LongevityLifetime
{
/** @struct DieAsSmallObjectParent
@ingroup SmallObjectGroup
Lifetime policy to manage lifetime dependencies of
SmallObject base and child classes.
The Base class should have this lifetime
*/
template <class T>
struct DieAsSmallObjectParent : DieLast<T> {};
/** @struct DieAsSmallObjectChild
@ingroup SmallObjectGroup
Lifetime policy to manage lifetime dependencies of
SmallObject base and child classes.
The Child class should have this lifetime
*/
template <class T>
struct DieAsSmallObjectChild : DieDirectlyBeforeLast<T> {};
}
class FixedAllocator;
/** @class SmallObjAllocator
@ingroup SmallObjectGroupInternal
Manages pool of fixed-size allocators.
Designed to be a non-templated base class of AllocatorSingleton so that
implementation details can be safely hidden in the source code file.
*/
class LOKI_EXPORT SmallObjAllocator
{
protected:
/** The only available constructor needs certain parameters in order to
initialize all the FixedAllocator's. This throws only if
@param pageSize # of bytes in a page of memory.
@param maxObjectSize Max # of bytes which this may allocate.
@param objectAlignSize # of bytes between alignment boundaries.
*/
SmallObjAllocator( std::size_t pageSize, std::size_t maxObjectSize,
std::size_t objectAlignSize );
/** Destructor releases all blocks, all Chunks, and FixedAllocator's.
Any outstanding blocks are unavailable, and should not be used after
this destructor is called. The destructor is deliberately non-virtual
because it is protected, not public.
*/
~SmallObjAllocator( void );
public:
/** Allocates a block of memory of requested size. Complexity is often
constant-time, but might be O(C) where C is the number of Chunks in a
FixedAllocator.
@par Exception Safety Level
Provides either strong-exception safety, or no-throw exception-safety
level depending upon doThrow parameter. The reason it provides two
levels of exception safety is because it is used by both the nothrow
and throwing new operators. The underlying implementation will never
throw of its own accord, but this can decide to throw if it does not
allocate. The only exception it should emit is std::bad_alloc.
@par Allocation Failure
If it does not allocate, it will call TrimExcessMemory and attempt to
allocate again, before it decides to throw or return NULL. Many
allocators loop through several new_handler functions, and terminate
if they can not allocate, but not this one. It only makes one attempt
using its own implementation of the new_handler, and then returns NULL
or throws so that the program can decide what to do at a higher level.
(Side note: Even though the C++ Standard allows allocators and
new_handlers to terminate if they fail, the Loki allocator does not do
that since that policy is not polite to a host program.)
@param size # of bytes needed for allocation.
@param doThrow True if this should throw if unable to allocate, false
if it should provide no-throw exception safety level.
@return NULL if nothing allocated and doThrow is false. Else the
pointer to an available block of memory.
*/
void * Allocate( std::size_t size, bool doThrow );
/** Deallocates a block of memory at a given place and of a specific
size. Complexity is almost always constant-time, and is O(C) only if
it has to search for which Chunk deallocates. This never throws.
*/
void Deallocate( void * p, std::size_t size );
/** Deallocates a block of memory at a given place but of unknown size
size. Complexity is O(F + C) where F is the count of FixedAllocator's
in the pool, and C is the number of Chunks in all FixedAllocator's. This
does not throw exceptions. This overloaded version of Deallocate is
called by the nothow delete operator - which is called when the nothrow
new operator is used, but a constructor throws an exception.
*/
void Deallocate( void * p );
/// Returns max # of bytes which this can allocate.
inline std::size_t GetMaxObjectSize() const
{ return maxSmallObjectSize_; }
/// Returns # of bytes between allocation boundaries.
inline std::size_t GetAlignment() const { return objectAlignSize_; }
/** Releases empty Chunks from memory. Complexity is O(F + C) where F
is the count of FixedAllocator's in the pool, and C is the number of
Chunks in all FixedAllocator's. This will never throw. This is called
by AllocatorSingleto::ClearExtraMemory, the new_handler function for
Loki's allocator, and is called internally when an allocation fails.
@return True if any memory released, or false if none released.
*/
bool TrimExcessMemory( void );
/** Returns true if anything in implementation is corrupt. Complexity
is O(F + C + B) where F is the count of FixedAllocator's in the pool,
C is the number of Chunks in all FixedAllocator's, and B is the number
of blocks in all Chunks. If it determines any data is corrupted, this
will return true in release version, but assert in debug version at
the line where it detects the corrupted data. If it does not detect
any corrupted data, it returns false.
*/
bool IsCorrupt( void ) const;
private:
/// Default-constructor is not implemented.
SmallObjAllocator( void );
/// Copy-constructor is not implemented.
SmallObjAllocator( const SmallObjAllocator & );
/// Copy-assignment operator is not implemented.
SmallObjAllocator & operator = ( const SmallObjAllocator & );
/// Pointer to array of fixed-size allocators.
Loki::FixedAllocator * pool_;
/// Largest object size supported by allocators.
const std::size_t maxSmallObjectSize_;
/// Size of alignment boundaries.
const std::size_t objectAlignSize_;
};
/** @class AllocatorSingleton
@ingroup SmallObjectGroupInternal
This template class is derived from
SmallObjAllocator in order to pass template arguments into it, and still
have a default constructor for the singleton. Each instance is a unique
combination of all the template parameters, and hence is singleton only
with respect to those parameters. The template parameters have default
values and the class has typedefs identical to both SmallObject and
SmallValueObject so that this class can be used directly instead of going
through SmallObject or SmallValueObject. That design feature allows
clients to use the new_handler without having the name of the new_handler
function show up in classes derived from SmallObject or SmallValueObject.
Thus, the only functions in the allocator which show up in SmallObject or
SmallValueObject inheritance hierarchies are the new and delete
operators.
*/
template
<
template <class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
std::size_t chunkSize = LOKI_DEFAULT_CHUNK_SIZE,
std::size_t maxSmallObjectSize = LOKI_MAX_SMALL_OBJECT_SIZE,
std::size_t objectAlignSize = LOKI_DEFAULT_OBJECT_ALIGNMENT,
template <class> class LifetimePolicy = LOKI_DEFAULT_SMALLOBJ_LIFETIME,
class MutexPolicy = LOKI_DEFAULT_MUTEX
>
class AllocatorSingleton : public SmallObjAllocator
{
public:
/// Defines type of allocator.
typedef AllocatorSingleton< ThreadingModel, chunkSize,
maxSmallObjectSize, objectAlignSize, LifetimePolicy > MyAllocator;
/// Defines type for thread-safety locking mechanism.
typedef ThreadingModel< MyAllocator, MutexPolicy > MyThreadingModel;
/// Defines singleton made from allocator.
typedef Loki::SingletonHolder< MyAllocator, Loki::CreateStatic,
LifetimePolicy, ThreadingModel > MyAllocatorSingleton;
/// Returns reference to the singleton.
inline static AllocatorSingleton & Instance( void )
{
return MyAllocatorSingleton::Instance();
}
/// The default constructor is not meant to be called directly.
inline AllocatorSingleton() :
SmallObjAllocator( chunkSize, maxSmallObjectSize, objectAlignSize )
{}
/// The destructor is not meant to be called directly.
inline ~AllocatorSingleton( void ) {}
/** Clears any excess memory used by the allocator. Complexity is
O(F + C) where F is the count of FixedAllocator's in the pool, and C
is the number of Chunks in all FixedAllocator's. This never throws.
@note This function can be used as a new_handler when Loki and other
memory allocators can no longer allocate. Although the C++ Standard
allows new_handler functions to terminate the program when they can
not release any memory, this will not do so.
*/
static void ClearExtraMemory( void );
/** Returns true if anything in implementation is corrupt. Complexity
is O(F + C + B) where F is the count of FixedAllocator's in the pool,
C is the number of Chunks in all FixedAllocator's, and B is the number
of blocks in all Chunks. If it determines any data is corrupted, this
will return true in release version, but assert in debug version at
the line where it detects the corrupted data. If it does not detect
any corrupted data, it returns false.
*/
static bool IsCorrupted( void );
private:
/// Copy-constructor is not implemented.
AllocatorSingleton( const AllocatorSingleton & );
/// Copy-assignment operator is not implemented.
AllocatorSingleton & operator = ( const AllocatorSingleton & );
};
template
<
template <class, class> class TM,
std::size_t CS,
std::size_t MSOS,
std::size_t OAS,
template <class> class LP,
class MX
>
void AllocatorSingleton< TM, CS, MSOS, OAS, LP, MX >::ClearExtraMemory( void )
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
Instance().TrimExcessMemory();
}
template
<
template <class, class> class TM,
std::size_t CS,
std::size_t MSOS,
std::size_t OAS,
template <class> class LP,
class MX
>
bool AllocatorSingleton< TM, CS, MSOS, OAS, LP, MX >::IsCorrupted( void )
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
return Instance().IsCorrupt();
}
/** This standalone function provides the longevity level for Small-Object
Allocators which use the Loki::SingletonWithLongevity policy. The
SingletonWithLongevity class can find this function through argument-
dependent lookup.
@par Longevity Levels
No Small-Object Allocator depends on any other Small-Object allocator, so
this does not need to calculate dependency levels among allocators, and
it returns just a constant. All allocators must live longer than the
objects which use the allocators, it must return a longevity level higher
than any such object.
*/
template
<
template <class, class> class TM,
std::size_t CS,
std::size_t MSOS,
std::size_t OAS,
template <class> class LP,
class MX
>
inline unsigned int GetLongevity(
AllocatorSingleton< TM, CS, MSOS, OAS, LP, MX > * )
{
// Returns highest possible value.
return 0xFFFFFFFF;
}
/** @class SmallObjectBase
@ingroup SmallObjectGroup
Base class for small object allocation classes.
The shared implementation of the new and delete operators are here instead
of being duplicated in both SmallObject or SmallValueObject, later just
called Small-Objects. This class is not meant to be used directly by clients,
or derived from by clients. Class has no data members so compilers can
use Empty-Base-Optimization.
@par Lifetime Policy
The SmallObjectBase template needs a lifetime policy because it owns
a singleton of SmallObjAllocator which does all the low level functions.
When using a Small-Object in combination with the SingletonHolder template
you have to choose two lifetimes, that of the Small-Object and that of
the singleton. The rule is: The Small-Object lifetime must be greater than
the lifetime of the singleton hosting the Small-Object. Violating this rule
results in a crash on exit, because the hosting singleton tries to delete
the Small-Object which is then already destroyed.
The lifetime policies recommended for use with Small-Objects hosted
by a SingletonHolder template are
- LongevityLifetime::DieAsSmallObjectParent / LongevityLifetime::DieAsSmallObjectChild
- SingletonWithLongevity
- FollowIntoDeath (not supported by MSVC 7.1)
- NoDestroy
The default lifetime of Small-Objects is
LongevityLifetime::DieAsSmallObjectParent to
insure that memory is not released before a object with the lifetime
LongevityLifetime::DieAsSmallObjectChild using that
memory is destroyed. The LongevityLifetime::DieAsSmallObjectParent
lifetime has the highest possible value of a SetLongevity lifetime, so
you can use it in combination with your own lifetime not having also
the highest possible value.
The DefaultLifetime and PhoenixSingleton policies are *not* recommended
since they can cause the allocator to be destroyed and release memory
for singletons hosting a object which inherit from either SmallObject
or SmallValueObject.
@par Lifetime usage
- LongevityLifetime: The Small-Object has
LongevityLifetime::DieAsSmallObjectParent policy and the Singleton
hosting the Small-Object has LongevityLifetime::DieAsSmallObjectChild.
The child lifetime has a hard coded SetLongevity lifetime which is
shorter than the lifetime of the parent, thus the child dies
before the parent.
- Both Small-Object and Singleton use SingletonWithLongevity policy.
The longevity level for the singleton must be lower than that for the
Small-Object. This is why the AllocatorSingleton's GetLongevity function
returns the highest value.
- FollowIntoDeath lifetime: The Small-Object has
FollowIntoDeath::With<LIFETIME>::AsMasterLiftime
policy and the Singleton has
FollowIntoDeath::AfterMaster<MASTERSINGLETON>::IsDestroyed policy,
where you could choose the LIFETIME.
- Both Small-Object and Singleton use NoDestroy policy.
Since neither is ever destroyed, the destruction order does not matter.
Note: yow will get memory leaks!
- The Small-Object has NoDestroy policy but the Singleton has
SingletonWithLongevity policy. Note: yow will get memory leaks!
You should *not* use NoDestroy for the singleton, and then use
SingletonWithLongevity for the Small-Object.
@par Examples:
- test/SmallObj/SmallSingleton.cpp
- test/Singleton/Dependencies.cpp
*/
template
<
template <class, class> class ThreadingModel,
std::size_t chunkSize,
std::size_t maxSmallObjectSize,
std::size_t objectAlignSize,
template <class> class LifetimePolicy,
class MutexPolicy
>
class SmallObjectBase
{
#if (LOKI_MAX_SMALL_OBJECT_SIZE != 0) && (LOKI_DEFAULT_CHUNK_SIZE != 0) && (LOKI_DEFAULT_OBJECT_ALIGNMENT != 0)
public:
/// Defines type of allocator singleton, must be public
/// to handle singleton lifetime dependencies.
typedef AllocatorSingleton< ThreadingModel, chunkSize,
maxSmallObjectSize, objectAlignSize, LifetimePolicy > ObjAllocatorSingleton;
private:
/// Defines type for thread-safety locking mechanism.
typedef ThreadingModel< ObjAllocatorSingleton, MutexPolicy > MyThreadingModel;
/// Use singleton defined in AllocatorSingleton.
typedef typename ObjAllocatorSingleton::MyAllocatorSingleton MyAllocatorSingleton;
public:
/// Throwing single-object new throws bad_alloc when allocation fails.
#ifdef _MSC_VER
/// @note MSVC complains about non-empty exception specification lists.
static void * operator new ( std::size_t size )
#else
static void * operator new ( std::size_t size ) throw ( std::bad_alloc )
#endif
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
return MyAllocatorSingleton::Instance().Allocate( size, true );
}
/// Non-throwing single-object new returns NULL if allocation fails.
static void * operator new ( std::size_t size, const std::nothrow_t & ) throw ()
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
return MyAllocatorSingleton::Instance().Allocate( size, false );
}
/// Placement single-object new merely calls global placement new.
inline static void * operator new ( std::size_t size, void * place )
{
return ::operator new( size, place );
}
/// Single-object delete.
static void operator delete ( void * p, std::size_t size ) throw ()
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
MyAllocatorSingleton::Instance().Deallocate( p, size );
}
/** Non-throwing single-object delete is only called when nothrow
new operator is used, and the constructor throws an exception.
*/
static void operator delete ( void * p, const std::nothrow_t & ) throw()
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
MyAllocatorSingleton::Instance().Deallocate( p );
}
/// Placement single-object delete merely calls global placement delete.
inline static void operator delete ( void * p, void * place )
{
::operator delete ( p, place );
}
#ifdef LOKI_SMALL_OBJECT_USE_NEW_ARRAY
/// Throwing array-object new throws bad_alloc when allocation fails.
#ifdef _MSC_VER
/// @note MSVC complains about non-empty exception specification lists.
static void * operator new [] ( std::size_t size )
#else
static void * operator new [] ( std::size_t size )
throw ( std::bad_alloc )
#endif
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
return MyAllocatorSingleton::Instance().Allocate( size, true );
}
/// Non-throwing array-object new returns NULL if allocation fails.
static void * operator new [] ( std::size_t size,
const std::nothrow_t & ) throw ()
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
return MyAllocatorSingleton::Instance().Allocate( size, false );
}
/// Placement array-object new merely calls global placement new.
inline static void * operator new [] ( std::size_t size, void * place )
{
return ::operator new( size, place );
}
/// Array-object delete.
static void operator delete [] ( void * p, std::size_t size ) throw ()
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
MyAllocatorSingleton::Instance().Deallocate( p, size );
}
/** Non-throwing array-object delete is only called when nothrow
new operator is used, and the constructor throws an exception.
*/
static void operator delete [] ( void * p,
const std::nothrow_t & ) throw()
{
typename MyThreadingModel::Lock lock;
(void)lock; // get rid of warning
MyAllocatorSingleton::Instance().Deallocate( p );
}
/// Placement array-object delete merely calls global placement delete.
inline static void operator delete [] ( void * p, void * place )
{
::operator delete ( p, place );
}
#endif // #if use new array functions.
#endif // #if default template parameters are not zero
protected:
inline SmallObjectBase( void ) {}
inline SmallObjectBase( const SmallObjectBase & ) {}
inline SmallObjectBase & operator = ( const SmallObjectBase & ) {}
inline ~SmallObjectBase() {}
}; // end class SmallObjectBase
/** @class SmallObject
@ingroup SmallObjectGroup
SmallObject Base class for polymorphic small objects, offers fast
allocations & deallocations. Destructor is virtual and public. Default
constructor is trivial. Copy-constructor and copy-assignment operator are
not implemented since polymorphic classes almost always disable those
operations. Class has no data members so compilers can use
Empty-Base-Optimization.
*/
template
<
template <class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
std::size_t chunkSize = LOKI_DEFAULT_CHUNK_SIZE,
std::size_t maxSmallObjectSize = LOKI_MAX_SMALL_OBJECT_SIZE,
std::size_t objectAlignSize = LOKI_DEFAULT_OBJECT_ALIGNMENT,
template <class> class LifetimePolicy = LOKI_DEFAULT_SMALLOBJ_LIFETIME,
class MutexPolicy = LOKI_DEFAULT_MUTEX
>
class SmallObject : public SmallObjectBase< ThreadingModel, chunkSize,
maxSmallObjectSize, objectAlignSize, LifetimePolicy, MutexPolicy >
{
public:
virtual ~SmallObject() {}
protected:
inline SmallObject( void ) {}
private:
/// Copy-constructor is not implemented.
SmallObject( const SmallObject & );
/// Copy-assignment operator is not implemented.
SmallObject & operator = ( const SmallObject & );
}; // end class SmallObject
/** @class SmallValueObject
@ingroup SmallObjectGroup
SmallValueObject Base class for small objects with value-type
semantics - offers fast allocations & deallocations. Destructor is
non-virtual, inline, and protected to prevent unintentional destruction
through base class. Default constructor is trivial. Copy-constructor
and copy-assignment operator are trivial since value-types almost always
need those operations. Class has no data members so compilers can use
Empty-Base-Optimization.
*/
template
<
template <class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
std::size_t chunkSize = LOKI_DEFAULT_CHUNK_SIZE,
std::size_t maxSmallObjectSize = LOKI_MAX_SMALL_OBJECT_SIZE,
std::size_t objectAlignSize = LOKI_DEFAULT_OBJECT_ALIGNMENT,
template <class> class LifetimePolicy = LOKI_DEFAULT_SMALLOBJ_LIFETIME,
class MutexPolicy = LOKI_DEFAULT_MUTEX
>
class SmallValueObject : public SmallObjectBase< ThreadingModel, chunkSize,
maxSmallObjectSize, objectAlignSize, LifetimePolicy, MutexPolicy >
{
protected:
inline SmallValueObject( void ) {}
inline SmallValueObject( const SmallValueObject & ) {}
inline SmallValueObject & operator = ( const SmallValueObject & ) {}
inline ~SmallValueObject() {}
}; // end class SmallValueObject
} // namespace Loki
////////////////////////////////////////////////////////////////////////////////
// Change log:
// June 20, 2001: ported by Nick Thurn to gcc 2.95.3. Kudos, Nick!!!
// Nov. 26, 2004: re-implemented by Rich Sposato.
//
/* $Log: //BQT/VM67/Prjbase3/QSyncher_V2/PlatformTool/Code/ShareLib/loki-0.1.5/include/loki/SmallObj.h.-arc $
*
* Rev 1.1 Apr 01 2009 14:21:52 Kevin Tai
* no change
*
* Rev 1.0 Apr 22 2008 20:56:20 Alan Tu
* Initial revision.
*
* Rev 1.2 Nov 10 2006 14:49:58 Alan Tu
* Update*
*
* Rev 1.1 Nov 10 2006 14:31:14 Alan Tu
* Update
// Revision 1.30 2006/06/19 12:39:08 syntheticpp
// replace tabs with 4 spaces
//
// Revision 1.29 2006/03/08 17:07:11 syntheticpp
// replace tabs with 4 spaces in all files
//
// Revision 1.28 2006/02/27 19:59:20 syntheticpp
// add support of loki.dll
//
// Revision 1.27 2006/02/20 21:56:06 rich_sposato
// Fixed typo.
//
// Revision 1.26 2006/01/22 13:37:33 syntheticpp
// use macro LOKI_DEFAULT_MUTEX for Mutex default value, defined in Threads.h
//
// Revision 1.25 2006/01/22 13:31:45 syntheticpp
// add additional template parameter for the changed threading classes
//
// Revision 1.24 2005/12/08 22:09:08 rich_sposato
// Added functions to check for memory corruption. Also made some minor
// coding changes.
//
// Revision 1.23 2005/11/13 16:51:22 syntheticpp
// update documentation due to the new lifetime policies
//
// Revision 1.22 2005/11/07 12:06:43 syntheticpp
// change lifetime policy DieOrder to a msvc7.1 compilable version. Make this the default lifetime for SmallObject
//
// Revision 1.21 2005/11/05 17:43:55 syntheticpp
// disable FollowIntoDeath/DieOrder lifetime policies when using the msvc 7.1 compiler, bug article: 839821 'Microsoft has confirmed that this is a problem..'
//
// Revision 1.20 2005/11/02 20:01:10 syntheticpp
// more doxygen documentation, modules added
//
// Revision 1.19 2005/11/01 11:11:52 syntheticpp
// add lifetime policies to manage singleton lifetime dependencies: FollowIntoDeath and DieOrder. Change SmallObject.h to avoid memory leaks by default
//
// Revision 1.18 2005/10/30 14:03:23 syntheticpp
// replace tabs space
//
// Revision 1.17 2005/10/29 08:10:13 syntheticpp
// #undef LOKI_SMALL_OBJECT_USE_NEW_ARRAY when using a Microsoft compiler
//
// Revision 1.16 2005/10/26 00:50:44 rich_sposato
// Minor changes to documentation comments.
//
// Revision 1.15 2005/10/15 19:41:23 syntheticpp
// fix bug 1327060. Add missing template parameter to make different static variables possible
//
// Revision 1.14 2005/10/13 22:43:03 rich_sposato
// Added documentation comments about lifetime policies.
//
// Revision 1.13 2005/10/07 01:22:09 rich_sposato
// Added GetLongevity function so allocator can work with a certain lifetime
// policy class used with Loki::SingletonHolder.
//
// Revision 1.12 2005/10/06 00:19:56 rich_sposato
// Added clarifying comment about destructor.
//
// Revision 1.11 2005/09/27 00:41:13 rich_sposato
// Added array forms of new and delete.
//
// Revision 1.10 2005/09/26 21:38:54 rich_sposato
// Changed include path to be direct instead of relying upon project settings.
//
// Revision 1.9 2005/09/26 07:33:04 syntheticpp
// move macros into LOKI_ namespace
//
// Revision 1.8 2005/09/09 00:24:59 rich_sposato
// Added functions to trim extra memory within allocator. Made a new_handler
// function for allocator. Added deallocator function for nothrow delete
// operator to insure nothing is leaked when constructor throws.
//
// Revision 1.7 2005/09/01 22:01:33 rich_sposato
// Added #ifdef to deal with MSVC warning about exception specification lists.
//
// Revision 1.6 2005/08/27 13:22:56 syntheticpp
// samll fix
//
// Revision 1.5 2005/08/25 15:49:51 syntheticpp
// small corrections
//
// Revision 1.4 2005/08/25 15:23:14 syntheticpp
// small corrections
//
// Revision 1.3 2005/07/31 14:00:48 syntheticpp
// make object level threading possible
//
// Revision 1.2 2005/07/31 13:51:31 syntheticpp
// replace old implementation with the ingeious from Rich Sposato
//
// Revision 1.2 2005/07/22 00:22:38 rich_sposato
// Added SmallValueObject, SmallObjectBase, and AllocatorSingleton classes.
*/
////////////////////////////////////////////////////////////////////////////////
#endif // SMALLOBJ_INC_
| [
"faulfish@gmail.com"
] | faulfish@gmail.com |
cdb66a3c2760cb61e97e2a6c9b00a38a012ee64f | 801bb9a6bca5743828484c19185cf22e79ffdcc4 | /Player.h | 4477ca4512ab5a29b7448ca4745e851a05264286 | [] | no_license | MousaMohammad/project | c947682619ccfdc19e20e5fc10fa390e7b2536de | d21dc38908eba1084476b67144dca10564a592f9 | refs/heads/master | 2020-11-24T23:23:18.764587 | 2019-12-16T11:06:37 | 2019-12-16T11:06:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,284 | h | #pragma once
#include "Grid.h"
#include "Cell.h"
class Player
{
Cell * pCell; // pointer to the current Cell of the player
const int playerNum; // the player number (from 0 to MaxPlayerCount-1)
// player number does NOT change after construction (const.)
int stepCount; // step count which is the same as his cellNum: from 1 to NumVerticalCells*NumHorizontalCells
int wallet; // player's wallet (how many coins he has -- integer)
int justRolledDiceNum; // the current dice number which is just rolled by the player
int turnCount; // a counter that starts with 0, is incremented with each dice roll
bool Roll; // and reset again when reached 3
// it is used to indicate when to move and when to add to your wallet
bool freeze;
public:
Player(Cell * pCell, int playerNum); // Constructor making any needed initializations
// ====== Setters and Getters ======
void set_roll(bool roll);
void setfreeze(bool f);
void SetCell(Cell * cell); // A setter for the pCell
Cell* GetCell() const; // A getter for the pCell
void Set_turncount(int count);
void SetWallet(int wallet); // A setter for the wallet
int GetWallet() const; // a getter for the wallet
int GetTurnCount() const; // A getter for the turnCount
///TODO: You can add setters and getters for data members here (if needed)
void Set_justRolledDiceNum(int dicenum);
int GetjustRolledDiceNum()const;
// ====== Drawing Functions ======
void Draw(Output* pOut) const; // Draws the Player's Circle on its current cell
void ClearDrawing(Output* pOut) const; // Clears the Player's Circle from its current cell
// ====== Game Functions ======
void Move(Grid * pGrid, int diceNumber); // Moves the Player with the passed diceNumber
// and Applies the Game Object's effect (if any) of the end reached cell
// for example, if the end cell contains a ladder, take it
void AppendPlayerInfo(string & playersInfo) const; // Appends player's info to the input string,
// for example: P0(wallet, turnCount)
};
| [
"noreply@github.com"
] | noreply@github.com |
a054ca21ab592e8861532dfcc1f756ec0ae31072 | 32f541dd6dcb2121f21b13071678a799eb293f10 | /libraries/chain/lockbalance_evaluator.cpp | d8fb4d475ef66ee3fdb27d91fdc2daa869047203 | [
"MIT"
] | permissive | Whitecoin-XWC/Whitecoin-core | b62de0b712ab8557ecd16dc1d0e4389c439eb3db | 8f15e0764fe60ff8d77228a2aca6bdff723439bd | refs/heads/develop | 2022-12-10T18:12:23.027195 | 2022-11-23T03:53:04 | 2022-11-23T03:53:04 | 397,646,406 | 0 | 3 | MIT | 2022-11-28T01:20:26 | 2021-08-18T15:17:39 | C++ | UTF-8 | C++ | false | false | 4,702 | cpp | #include <graphene/chain/lockbalance_evaluator.hpp>
#include <graphene/chain/witness_object.hpp>
namespace graphene{
namespace chain{
void_result lockbalance_evaluator::do_evaluate(const lockbalance_operation& o){
try{
const database& d = db();
if (o.contract_addr == address()) {
const asset_object& asset_type = o.lock_asset_id(d);
// auto & iter = d.get_index_type<miner_index>().indices().get<by_account>();
// auto itr = iter.find(o.lockto_miner_account);
// FC_ASSERT(itr != iter.end(), "Dont have lock account");
optional<miner_object> iter = d.get(o.lockto_miner_account);
FC_ASSERT(iter.valid(),"Dont have lock account");
optional<account_object> account_iter = d.get(o.lock_balance_account);
FC_ASSERT(account_iter.valid() && account_iter->addr == o.lock_balance_addr, "Address is wrong");
bool insufficient_balance = d.get_balance(o.lock_balance_addr, asset_type.id).amount >= o.lock_asset_amount;
FC_ASSERT(insufficient_balance, "Lock balance fail because lock account own balance is not enough");
}
else {
//TODO : ADD Handle Contact lock balance
}
return void_result();
}FC_CAPTURE_AND_RETHROW((o))
}
void_result lockbalance_evaluator::do_apply(const lockbalance_operation& o){
try {
if (o.contract_addr == address()) {
database& d = db();
const asset_object& asset_type = o.lock_asset_id(d);
d.adjust_balance(o.lock_balance_addr, asset(-o.lock_asset_amount,o.lock_asset_id));
d.adjust_lock_balance(o.lockto_miner_account, o.lock_balance_account,asset(o.lock_asset_amount,o.lock_asset_id));
//optional<miner_object> itr = d.get(o.lockto_miner_account);
if (d.head_block_num() < LOCKBALANCE_CORRECT)
{
d.modify(d.get(o.lockto_miner_account), [o, asset_type](miner_object& b) {
auto map_lockbalance_total = b.lockbalance_total.find(asset_type.symbol);
if (map_lockbalance_total != b.lockbalance_total.end()) {
map_lockbalance_total->second += asset(o.lock_asset_amount, o.lock_asset_id);
}
else {
b.lockbalance_total[asset_type.symbol] = asset(o.lock_asset_amount, o.lock_asset_id);
}
});
}
d.modify(d.get_lockbalance_records(), [o](lockbalance_record_object& obj) {
obj.record_list[o.lock_balance_addr][o.lock_asset_id] += o.lock_asset_amount;
});
}
else {
//TODO : ADD Handle Contact lock balance
}
return void_result();
} FC_CAPTURE_AND_RETHROW((o))
}
void_result foreclose_balance_evaluator::do_evaluate(const foreclose_balance_operation& o) {
try {
const database& d = db();
if (o.foreclose_contract_addr == address()) {
const asset_object& asset_type = o.foreclose_asset_id(d);
optional<miner_object> iter = d.get(o.foreclose_miner_account);
FC_ASSERT(iter.valid(), "Dont have lock account");
optional<account_object> account_iter = d.get(o.foreclose_account);
FC_ASSERT(account_iter.valid() && account_iter->addr == o.foreclose_addr, "Address is wrong");
bool insufficient_balance = d.get_lock_balance(o.foreclose_account, o.foreclose_miner_account, asset_type.id).amount >= o.foreclose_asset_amount;
FC_ASSERT(insufficient_balance, "Lock balance fail because lock account own balance is not enough");
}
else {
//TODO : ADD Handle Contact lock balance
}
return void_result();
}FC_CAPTURE_AND_RETHROW((o))
}
void_result foreclose_balance_evaluator::do_apply(const foreclose_balance_operation& o) {
try {
database& d = db();
if (o.foreclose_contract_addr == address()) {
const asset_object& asset_type = o.foreclose_asset_id(d);
d.adjust_lock_balance(o.foreclose_miner_account, o.foreclose_account, asset(-o.foreclose_asset_amount,o.foreclose_asset_id));
d.adjust_balance(o.foreclose_addr, asset(o.foreclose_asset_amount,o.foreclose_asset_id));
//optional<miner_object> itr = d.get(o.foreclose_miner_account);
if (d.head_block_num() < LOCKBALANCE_CORRECT)
d.modify(d.get(o.foreclose_miner_account), [o, asset_type](miner_object& b) {
auto map_lockbalance_total = b.lockbalance_total.find(asset_type.symbol);
if (map_lockbalance_total != b.lockbalance_total.end()) {
map_lockbalance_total->second -= asset(o.foreclose_asset_amount, o.foreclose_asset_id);
}
});
d.modify(d.get_lockbalance_records(), [o](lockbalance_record_object& obj) {
obj.record_list[o.foreclose_addr][o.foreclose_asset_id] -= o.foreclose_asset_amount;
});
}
else {
// TODO : ADD Handle Contact lock balance
}
return void_result();
} FC_CAPTURE_AND_RETHROW((o))
}
}
}
| [
"WhitecoinFounder@gmail.com"
] | WhitecoinFounder@gmail.com |
d533e60688223365cada28118b505491767bd195 | f7856e99413b3b8a41235ecabd21806e286c0b6b | /lab3.cpp | 18bf7c7da3de50dab52b60f30709962dbea4ee3f | [] | no_license | viancamadrid/Laboratorio3 | e40d0d01bf7af2d4bfceec07dbf4a2671ef15573 | c5467db32f6ec68749830ab2d631f96d1912595d | refs/heads/master | 2021-01-10T02:01:18.150394 | 2016-02-05T23:51:23 | 2016-02-05T23:51:23 | 51,171,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,096 | cpp | #include <iostream>
#include <cstdlib>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
void ordenar(int []);
void imprimir(int []);
int datos(int, int, int [4][3]);
int main( int argc, char*argv[]){
int opcion=0;
cout<<"1. Ejercicio 1\n2. Ejercicio 2\nIngrese Opcion: ";
cin>>opcion;
if(opcion==1){
srand(time(NULL));
int num=-500+rand()%((500+1)-(-500));
int adivinar=600;
int scores[10]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
int intentos=0;
int seguir=0;
int i=0;
//int temp=0;
cout<<"-----------"<<num<<"--------------"<<endl;
while(seguir==0){
intentos++;
cout<<"Ingrese Numero: ";
cin>>adivinar;
while(adivinar!=num){
intentos++;
cout<<"Ingrese Numero: ";
cin>>adivinar;
//intentos++;
//if(adivinar==num)
//temp=1;
}
scores[i]=intentos;
i++;
intentos=0;
adivinar=600;
cout<<"Seguir? 0. Si 1. No: ";
cin>>seguir;
//if(seguir==1)
//break;
}
ordenar(scores);
cout<<"---Tabla de Highscore---"<<endl;
imprimir(scores);
}
if(opcion==2){
srand(time(NULL));
int matriz[4][3];
int num, num2;
for(int i=0; i<4; i++){
int num=85+rand()%((115+1)-85);
matriz[i][0]=num;
}
for(int i=0; i<4; i++){
int num=50+rand()%((75+1)-50);
matriz[i][1]=num;
}
for(int i=0; i<4; i++){
int num=150+rand()%((150+1)-200);
matriz[i][2]=num;
}
for(int i=0; i<4; i++){
for(int j=0; j<3; j++){
cout<<setw(6)<<matriz[i][j]<<setw(6);
}
cout<<endl;
}
int n1, n2, n3, n4, n5, n6;
n1=rand()%4+1;
n2=rand()%4+1;
n3=rand()%4+1;
n4=rand()%4+1;
n5=rand()%4+1;
n6=rand()%4+1;
//cout<<n1<<" "<<n2<<" "<<n3<<" "<<n4<<" "<<n5<<" "<<n6<<endl;
int a1, a2, d1, d2, v1, v2;
a1=datos(n1-1,0,matriz);
a2=datos(n2-1,0,matriz);
d1=datos(n3-1,1,matriz);
d2=datos(n4-1,1,matriz);
v1=datos(n5-1,2,matriz);
v2=datos(n6-1,2,matriz);
//cout<<a1<<" "<<a2<<" "<<d1<<" "<<d2<<" "<<v1<<" "<<v2<<endl;
int p1,p2;
p1=a1-d2;
p2=a2-d1;
cout<<"Juagador 1: ataque "<<a1<<", defensa "<<d1<<", velocidad "<<v1<<endl;
cout<<"Juagador 2: ataque "<<a2<<", defensa "<<d2<<", velocidad "<<v2<<endl;
if(p1==p2){
if(v1>v2)
cout<<"Jugador 1 gano por velocidad"<<endl;
else
cout<<"Jugador 2 gano por velocidad"<<endl;
}else{
if(p1>p2)
cout<<"Jugador 1 gano con "<<p1-p2<<" puntos de diferencia, no gano por velocidad"<<endl;
else
cout<<"Jugador 2 gano con "<<p2-p1<<" puntos de diferencia, no gano por velocidad"<<endl;
}
}
return 0;
}
void ordenar(int scores[]){
int temp;
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
if(scores[j]<scores[i]){
temp=scores[i];
scores[i]=scores[j];
scores[j]=temp;
}
}
}
}
void imprimir(int scores[]){
for(int i=0; i<10; i++){
cout<<"Posicion "<<i+1<<": "<<scores[i]<<endl;
}
}
int datos(int i, int j, int matriz[4][3]){
int d= matriz[i][j];
return d;
}
| [
"viancamadrid@unitec.edu"
] | viancamadrid@unitec.edu |
8b200dbc9be09a49d3f59a6449b5ac9b3b331378 | c828544e95bcd39030d47c76f92a4c7270074353 | /bsearch.cpp | bca902a1082159f8cde92490e533c62b5cadd7d1 | [] | no_license | Ayan-code/ADA-Lab | 2f66692d75eee3a4c889aa6fe842488cf5ed8acd | d6011365784e860b33a62e7275103b32870c9b6e | refs/heads/master | 2020-12-29T14:00:43.804809 | 2020-05-03T12:02:51 | 2020-05-03T12:02:51 | 238,630,721 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | cpp |
#include <iostream>
using namespace std;
int binarySearch(int arr[], int low,
int high, int key)
{
if (high < low)
return -1;
int mid = (low + high)/2;
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
// else
return binarySearch(arr, low, (mid -1), key);
}
int findPivot(int arr[], int low, int high)
{
if (high < low) return -1;
if (high == low) return low;
int mid = (low + high)/2;
if (mid < high && arr[mid] > arr[mid + 1])
return mid;
if (mid > low && arr[mid] < arr[mid - 1])
return (mid-1);
if (arr[low] >= arr[mid])
return findPivot(arr, low, mid-1);
return findPivot(arr, mid + 1, high);
}
int pivotedBinarySearch(int arr[], int n, int key)
{
int pivot = findPivot(arr, 0, n-1);
if (pivot == -1)
return binarySearch(arr, 0, n-1, key);
if (arr[pivot] == key)
return pivot;
if (arr[0] <= key)
return binarySearch(arr, 0, pivot-1, key);
return binarySearch(arr, pivot+1, n-1, key);
}
int main()
{
int arr1[5];
cout<<"Enter the array:";
for(int i=0;i<5;i++)
cin>>arr1[i];
int n = sizeof(arr1)/sizeof(arr1[0]);
int key;
cout<<"Enter the key:";
cin>>key;
cout << "Index of the element is : " <<
pivotedBinarySearch(arr1, n, key);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
c5914dc4d3eb181a8c46485297c27183a8101dec | b65655dd7bf2d7aa21d5b2de615d908f2f057c4f | /include/hurricane/util/Configuration.h | 983bfa1aeaaedbc98c2040fbfa34d7c6171d19af | [
"Apache-2.0"
] | permissive | eagle518/hurricane | c7cfa18a888e4d98869876d13ef91ed42f9b8f9c | 27f9722843aebfa48c55576b814682b8200f6dea | refs/heads/master | 2021-01-11T20:14:16.525327 | 2016-12-25T10:03:23 | 2016-12-25T10:03:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,850 | h | /**
* licensed to the apache software foundation (asf) under one
* or more contributor license agreements. see the notice file
* distributed with this work for additional information
* regarding copyright ownership. the asf licenses this file
* to you under the apache license, version 2.0 (the
* "license"); you may not use this file except in compliance
* with the license. you may obtain a copy of the license at
*
* http://www.apache.org/licenses/license-2.0
*
* unless required by applicable law or agreed to in writing, software
* distributed under the license is distributed on an "as is" basis,
* without warranties or conditions of any kind, either express or implied.
* see the license for the specific language governing permissions and
* limitations under the license.
*/
#pragma once
#include <map>
#include <string>
#include <cstdint>
#include <sstream>
namespace hurricane {
namespace util {
class Configuration {
public:
const std::string& GetProperty(const std::string& propertyName) const {
return _properties.at(propertyName);
}
const int32_t GetIntegerProperty(const std::string& propertyName) const {
return std::stoi(_properties.at(propertyName));
}
void SetProperty(const std::string& propertyName, const std::string& propertyValue) {
_properties[propertyName] = propertyValue;
}
void SetProperty(const std::string& propertyName, int32_t propertyValue) {
std::ostringstream os;
os << propertyValue;
_properties[propertyName] = os.str();
}
void Parse(const std::string& fileName);
private:
std::map<std::string, std::string> _properties;
};
}
}
| [
"kinuxroot@163.com"
] | kinuxroot@163.com |
78ef3838a13a161dbe72079c1149e5de045d35f1 | 1880ae99db197e976c87ba26eb23a20248e8ee51 | /cynosdb/include/tencentcloud/cynosdb/v20190107/model/DescribeInstanceSpecsRequest.h | cfacbf3cb95dcae14e2e57c2aed2c7024b8f7001 | [
"Apache-2.0"
] | permissive | caogenwang/tencentcloud-sdk-cpp | 84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d | 6e18ee6622697a1c60a20a509415b0ddb8bdeb75 | refs/heads/master | 2023-08-23T12:37:30.305972 | 2021-11-08T01:18:30 | 2021-11-08T01:18:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,548 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_CYNOSDB_V20190107_MODEL_DESCRIBEINSTANCESPECSREQUEST_H_
#define TENCENTCLOUD_CYNOSDB_V20190107_MODEL_DESCRIBEINSTANCESPECSREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Cynosdb
{
namespace V20190107
{
namespace Model
{
/**
* DescribeInstanceSpecs请求参数结构体
*/
class DescribeInstanceSpecsRequest : public AbstractModel
{
public:
DescribeInstanceSpecsRequest();
~DescribeInstanceSpecsRequest() = default;
std::string ToJsonString() const;
/**
* 获取数据库类型,取值范围:
<li> MYSQL </li>
* @return DbType 数据库类型,取值范围:
<li> MYSQL </li>
*/
std::string GetDbType() const;
/**
* 设置数据库类型,取值范围:
<li> MYSQL </li>
* @param DbType 数据库类型,取值范围:
<li> MYSQL </li>
*/
void SetDbType(const std::string& _dbType);
/**
* 判断参数 DbType 是否已赋值
* @return DbType 是否已赋值
*/
bool DbTypeHasBeenSet() const;
private:
/**
* 数据库类型,取值范围:
<li> MYSQL </li>
*/
std::string m_dbType;
bool m_dbTypeHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_CYNOSDB_V20190107_MODEL_DESCRIBEINSTANCESPECSREQUEST_H_
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
499d30be1805422f424aeed9c3c06bb92534a9af | 18488c64ea8073545133e78a884cac4d6669ccf0 | /code-cua-Thuan/duong di theo BFS tren do thi co huong.cpp | 25bf19981aede67f59d458953edf9f0c894ce680 | [] | no_license | manhtung001/Datastructure-Algorithm-PTIT | f6b1c3bbc2476af3989b8796696dbbb7750e91fe | c41a344d4fbfd92bf587eac14861568d2029321b | refs/heads/master | 2023-06-24T07:19:33.970580 | 2021-07-21T13:44:54 | 2021-07-21T13:44:54 | 344,992,505 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 894 | cpp | #include<bits/stdc++.h>
#define max 1001
using namespace std;
int v,e,d,c,chuaxet[max],truoc[max];
vector<int> ke[max];
void BFS(int s){
queue<int> q;
q.push(s);
chuaxet[s]=0;
while (!q.empty()){
int u=q.front();
q.pop();
for (int i=0;i<ke[u].size();i++){
if (chuaxet[ke[u][i]]){
q.push(ke[u][i]);
truoc[ke[u][i]]=u;
chuaxet[ke[u][i]]=0;
}
}
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;cin>>t;
while (t--){
cin>>v>>e>>d>>c;
for (int i=1;i<=v;i++) ke[i].clear();
memset(chuaxet,1,sizeof(chuaxet));
memset(truoc,0 ,sizeof(truoc));
while (e--){
int a,b;
cin>>a>>b;
ke[a].push_back(b);
}
BFS(d);
if (truoc[c]==0) cout<<-1<<endl;
else {
vector<int>res;
while (c!=d){
res.push_back(c);
c=truoc[c];
}
res.push_back(d);
for (int i=res.size()-1;i>=0;i--) cout<<res[i]<<" ";
cout<<endl;
}
}
}
| [
"khongtung001@gmail.com"
] | khongtung001@gmail.com |
227ea874d16f443c0be2e938866aa5f0a0d31a18 | 2b50b9aa2bdf2a95e20bb1002b983517fc8e9798 | /ProjektZaliczeniowy/StateMachine.cpp | d6f4d928a715e4cf7ab4e4713a68184d34f4db46 | [] | no_license | KonradChecinski/ProjektZaliczeniowy | ea7ccd6d592f0fd1fef5b87ff121aa21b2cd7556 | 95bf541a6e9c5ad5b509aff8fe1c1a065a7671fc | refs/heads/master | 2023-06-04T04:26:07.115799 | 2021-06-24T10:03:23 | 2021-06-24T10:03:23 | 376,624,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | cpp | #include "StateMachine.h"
namespace BreakOut
{
void StateMachine::AddState(StateRef newState, bool isReplacing)
{
this -> _isAdding = true;
this->_isReplacing = isReplacing;
this-> _newState = move(newState);
}
void StateMachine::RemState()
{
this->_isRemoving = true;
}
void StateMachine::ProcessStateChange()
{
if (this->_isRemoving && !this->_states.empty())
{
this->_states.pop();
if (!this->_states.empty())
{
this->_states.top()->Resume();
}
this->_isRemoving = false;
}
if (this->_isAdding)
{
if (!this->_states.empty())
{
if (this->_isReplacing)
{
this->_states.pop();
}
else
{
this->_states.top()->Pause();
}
}
this->_states.push(move(this->_newState));
this->_states.top()->Init();
this->_isAdding = false;
}
}
StateRef& StateMachine::GetActiveState()
{
return this->_states.top();
}
}
| [
"konradchecinski2012@gmail.com"
] | konradchecinski2012@gmail.com |
a0361b47b97db7943c3721f7e1ddba186d111c5f | 3f21831c350aac5b79a554ba1cec295c6c71779d | /Chapter6/4_Canvas/src/Engine.h | df00c4f5694a40b860c77db8b376bf637b889a73 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | voff4eg/Android-NDK-Game-Development-Cookbook | f3a9d560a422c1a66cf1c7536bcc41aef9239f14 | 61857a1f73273bee4d16514dd4098dc9a64dabe9 | refs/heads/master | 2021-01-18T13:12:28.048871 | 2013-11-19T10:46:56 | 2013-11-19T10:46:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,683 | h | /*
* Copyright (C) 2013 Sergey Kosarevsky (sk@linderdaum.com)
* Copyright (C) 2013 Viktor Latypov (vl@linderdaum.com)
* Based on Linderdaum Engine http://www.linderdaum.com
* 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 display the names 'Sergey Kosarevsky' and
* 'Viktor Latypov'in the credits of the application, if such credits exist.
* The authors of this work must be notified via email (sk@linderdaum.com) in
* this case of redistribution.
*
* 3. Neither the name of copyright holders 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 COPYRIGHT HOLDERS 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.
*/
#include "Platform.h"
#include "Wrapper_Callbacks.h"
#if defined( _WIN32 )
# include "Wrapper_Windows.h"
#else
# include "Wrapper_Android.h"
#endif
#include "LGL.h"
#include "LGLAPI.h"
#include "GeomServ.h"
#include "GLSL.h"
#include "GLVertexArray.h"
#include "GLTexture.h"
#include "VertexAttribs.h"
#include "Canvas.h"
#include "FileSystem.h"
#include <string>
inline void Str_AddTrailingChar( std::string* Str, char Ch )
{
bool HasLastChar = ( !Str->empty() ) && ( Str->data()[Str->length() - 1] == Ch );
if ( !HasLastChar ) Str->push_back( Ch );
}
inline std::string Str_ReplaceAllSubStr( const std::string& Str, const std::string& OldSubStr, const std::string& NewSubStr )
{
std::string Result = Str;
for ( size_t Pos = Result.find( OldSubStr ); Pos != std::string::npos; Pos = Result.find( OldSubStr ) )
{
Result.replace( Pos, OldSubStr.length(), NewSubStr );
}
return Result;
}
| [
"sk@linderdaum.com"
] | sk@linderdaum.com |
360174e8c895a9b19fb820d85ff07c5cd912b1c9 | 65025edce8120ec0c601bd5e6485553697c5c132 | /Engine/foundation/messaging/handler.h | 4bda7f7242c45e6b6c37e96f5adee3649cc034db | [
"MIT"
] | permissive | stonejiang/genesis-3d | babfc99cfc9085527dff35c7c8662d931fbb1780 | df5741e7003ba8e21d21557d42f637cfe0f6133c | refs/heads/master | 2020-12-25T18:22:32.752912 | 2013-12-13T07:45:17 | 2013-12-13T07:45:17 | 15,157,071 | 4 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,328 | h | #pragma once
/****************************************************************************
Copyright (c) 2006, Radon Labs GmbH
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
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.
****************************************************************************/
#include "core/refcounted.h"
#include "messaging/message.h"
//-----------------------------------------------------------------------------
namespace Messaging
{
class Handler : public Core::RefCounted
{
__DeclareSubClass(Handler, Core::RefCounted);
public:
/// constructor
Handler();
/// destructor
virtual ~Handler();
/// called once on startup
virtual void Open();
/// called once before shutdown
virtual void Close();
/// return true if open
bool IsOpen() const;
/// handle a message, return true if handled
virtual bool HandleMessage(const GPtr<Message>& msg);
/// optional "per-frame" DoWork method for continuous handlers
virtual void DoWork();
protected:
bool isOpen;
};
//-----------------------------------------------------------------------------
/**
*/
inline bool
Handler::IsOpen() const
{
return this->isOpen;
}
} // namespace Messaging
//-----------------------------------------------------------------------------
| [
"jiangtao@tao-studio.net"
] | jiangtao@tao-studio.net |
debef238527c1e578e72ccdcce42cd932a73c31f | be88d809dd71c9736ca4e4e56f4194814a62ad8c | /Uppdrag v.2/Tretorn/torngrafik.cpp | 926b2a1f10964fe98da623ce681ce71de66a4464 | [] | no_license | alflinusjonsson/DALGO-RecursiveBinarySearch | 69087432c9ed6400e53a99355ca997344093154b | 97a7fe0cc7fa99836b12afae66749a4bd49eb8d8 | refs/heads/master | 2022-04-24T04:09:48.103668 | 2020-04-28T18:32:46 | 2020-04-28T18:32:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,528 | cpp | #include "torngrafik.h"
#include <QPainter>
#include <QPaintEvent>
#include <algorithm>
#include <QPoint>
#include <QDebug>
#include <QApplication>
#include <QThread>
#include <assert.h>
Torngrafik::Torngrafik(QWidget *parent) : QWidget(parent), _pTowers(nullptr){
setMouseTracking(true);
}
void Torngrafik::setTowers(Towers *pTowers)
{
assert( _pTowers==nullptr );
_pTowers = pTowers;
connect(pTowers, &Towers::discLifted, this, &Torngrafik::animateLifted);
connect(pTowers, &Towers::discDropped, this, &Torngrafik::animateDropped );
}
void Torngrafik::setMetrics(){
_height = rect().height();
_width = rect().width();
const int nbrDiscs = _pTowers->nbrDiscs();
_heightOfDisk = _height/(nbrDiscs+2+1+2);
_yTopOfBoard = _height-2*_heightOfDisk;
_yTopOfPin = _yTopOfBoard - _heightOfDisk*(1+nbrDiscs);
_diameterOfLargestDisc = int(_width/3*0.9);
_widthOfPin = _diameterOfLargestDisc/20;
_diameterOfSmallestDisc = 3*_widthOfPin;
_xOfPin[0] = int(_width/6);
_xOfPin[2] = int( _width - _xOfPin[0] );
_xOfPin[1] = (_xOfPin[0]+_xOfPin[2])/2;
}
QRect Torngrafik::rectOfDiscSize(int size){ // size = 0..._nbrOfDiscs-1
int diameter = _diameterOfSmallestDisc + size*(_diameterOfLargestDisc-_diameterOfSmallestDisc)/(_pTowers->nbrDiscs()-1);
QRect rect(-diameter/2, -_heightOfDisk/2, diameter, _heightOfDisk);
return rect;
}
void Torngrafik::drawTowers(QPainter& painter){
painter.setBrush( Qt::black );
for (int pin=0;pin<3;pin+=1){
painter.drawRoundedRect(rectOfPin(pin), 5,5);
}
if (_pTowers->isLifted()){
painter.setBrush( Qt::blue );
for (int pin=0;pin<3;pin+=1)
if (pin!=_pinSelectedSource)
painter.drawRoundedRect(rectOfPin(pin), 5,5);
}
QRect rectOfBoard(0, _yTopOfBoard, _width, _height-_yTopOfBoard);
painter.setBrush( Qt::black );
painter.drawRoundedRect(rectOfBoard, 5,5);
}
void Torngrafik::paintEvent(QPaintEvent *event)
{
QPainter painter( this );
painter.fillRect( event->rect(), Qt::white);
setMetrics();
drawTowers(painter);
painter.setBrush( Qt::yellow );
for (int pin=0;pin<3; pin+=1){
const int nbrPosToPaint = _pTowers->nbrDiscsAtPin(pin) - (pin==_pinDontPaintLastDisc ? 1:0);
for (int pos=0;pos<nbrPosToPaint; pos+=1){
QRect rectDisc = rectOfPinAndPos(pin, pos);
painter.drawRoundedRect(rectDisc, 5,5);
}
}
if (_isMooving){
QRect rectDisc = rectOfDiscSize(_sizeOfMooving).translated(_centerOfMoving);
painter.drawRoundedRect(rectDisc,5,5);
}
}
QPoint Torngrafik::centerOfPinAndPos(int pin, int pos){
QPoint center(_xOfPin[pin], _yTopOfBoard - _heightOfDisk/2 - _heightOfDisk*pos);
return center;
}
QRect Torngrafik::rectOfPinAndPos(int pin, int pos){
int size = _pTowers->discsizeAtPinAndPos(pin, pos);
QRect rect = rectOfDiscSize(size);
QPoint center = centerOfPinAndPos(pin,pos);
return rect.translated(center);
}
QRect Torngrafik::rectOfPin(int pin){
QRect rectOfPinAtZero = QRect(-_widthOfPin/2, _yTopOfPin, _widthOfPin, _height-_yTopOfPin);
return rectOfPinAtZero.translated(_xOfPin[pin],0);
}
void Torngrafik::animateLifted(int pinSource){
_isMooving = true;
_sizeOfMooving = _pTowers->discsizeLifted();
int timeFrame = 20; // ms
int distanceOneFrame = (_height+_width)*20/1000;
if (_speed == 0) distanceOneFrame = (distanceOneFrame/4)+1;
if (_speed == 1) distanceOneFrame = distanceOneFrame + 1;
if (_speed == 2) distanceOneFrame = distanceOneFrame*10 + 1;
int posSource = _pTowers->nbrDiscsAtPin(pinSource);
QPoint c0 = centerOfPinAndPos(pinSource, posSource);
QPoint c1 = QPoint(c0.x(), _yTopOfPin -_heightOfDisk/2);
_centerOfMoving = c0;
while (_centerOfMoving.y() > c1.y()){
_centerOfMoving.setY( _centerOfMoving.y()-distanceOneFrame );
if (_centerOfMoving.y()<c1.y())
_centerOfMoving = c1;
update();
QApplication::processEvents();
QThread::msleep(timeFrame);
}
_centerOfMoving = c1;
update();
QApplication::processEvents();
}
void Torngrafik::animateDropped(int pinSource, int pinDestination){
qDebug() << "animateDroped( "<< pinSource << ", " << pinDestination << " )";
_pinDontPaintLastDisc = pinDestination;
int timeFrame = 20; // ms
int distanceOneFrame = (_height+_width)*20/1000;
if (_speed == 0) distanceOneFrame = (distanceOneFrame/4)+1;
if (_speed == 1) distanceOneFrame = distanceOneFrame + 1;
if (_speed == 2) distanceOneFrame = distanceOneFrame*10 + 1;
int posDestination = _pTowers->nbrDiscsAtPin(pinDestination)-1;
QPoint c3 = centerOfPinAndPos(pinDestination, posDestination);
QPoint c2 = QPoint( c3.x(), _centerOfMoving.y());
if (_centerOfMoving.x()<c2.x()){
while (_centerOfMoving.x()<c2.x()){
_centerOfMoving += QPoint(distanceOneFrame,0);
if (_centerOfMoving.x()>c2.x())
_centerOfMoving = c2;
update();
QApplication::processEvents();
QThread::msleep(timeFrame);
}
}
else
if (_centerOfMoving.x()>c2.x()){
while (_centerOfMoving.x()>c2.x()) {
_centerOfMoving -= QPoint(distanceOneFrame,0);
if (_centerOfMoving.x()<c2.x())
_centerOfMoving = c2;
update();
QApplication::processEvents();
QThread::msleep(timeFrame);
}
}
_centerOfMoving = c2;
int d = distanceOneFrame/2 + 1;
while (_centerOfMoving.y()<c3.y()) {
_centerOfMoving += QPoint(0,d);
if (_centerOfMoving.y()>c3.y())
_centerOfMoving = c3;
d = d + 0.5*d;
update();
QApplication::processEvents();
QThread::msleep(timeFrame);
}
_centerOfMoving = c3;
_isMooving = false;
_pinDontPaintLastDisc = -1;
update();
}
int Torngrafik::pinOfTopdiscContainingPoint(QPoint pos){
for (int pin=0;pin<3; pin+=1){
int posOfTop = _pTowers->nbrDiscsAtPin(pin)-1;
if (posOfTop>=0){
QRect rectTop = rectOfPinAndPos(pin, posOfTop);
if (rectTop.contains(pos)){
return pin;
}
}
}
return -1;
}
int Torngrafik::pinContainingPoint(QPoint pos){
for (int pin=0; pin<3 ; pin+=1){
if (rectOfPin(pin).contains(pos))
return pin;
}
return -1;
}
void Torngrafik::mousePressEvent(QMouseEvent *event)
{
if (!_pTowers->isLifted()){
int pin = pinOfTopdiscContainingPoint(event->pos());
if (pin>=0){
_pinSelectedSource = pin;
_pTowers->liftDisc(pin);
unsetCursor();
update();
}
}
else {
int pin = pinContainingPoint(event->pos());
if (pin>=0){
_pTowers->placeLiftedDisc(pin);
update();
}
}
}
void Torngrafik::mouseMoveEvent(QMouseEvent *event)
{
if (!_pTowers->isLifted()){
int pin = pinOfTopdiscContainingPoint(event->pos());
if (pin>=0){
setCursor( Qt::PointingHandCursor );
return;
}
}
else {
if (pinContainingPoint(event->pos())>=0){
setCursor(Qt::PointingHandCursor);
return;
}
}
unsetCursor();
}
| [
"alflinusjonsson@gmail.com"
] | alflinusjonsson@gmail.com |
803c79c71ce3e9ab0ab74f4274fc82b67037f79c | 470fae08316b55246ab01675ac5013febfb13eee | /src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp | 4265f5e1228175d5628f32578fa5606152a00d01 | [] | no_license | adde13372/shadowcore | 8db6fb6ccc99821e6bd40237a0c284ce7cf543c2 | aa87944193ce02f6e99f7b35eceac5023abfca1b | refs/heads/main | 2023-04-01T07:38:39.359558 | 2021-04-03T07:54:17 | 2021-04-03T07:54:17 | 354,320,611 | 4 | 8 | null | 2021-04-03T15:02:49 | 2021-04-03T15:02:49 | null | UTF-8 | C++ | false | false | 4,324 | cpp | /*
* Copyright 2021 ShadowCore
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "AreaBoundary.h"
#include "ScriptMgr.h"
#include "Creature.h"
#include "forge_of_souls.h"
#include "InstanceScript.h"
#include "Map.h"
#include "Player.h"
BossBoundaryData const boundaries =
{
{ DATA_BRONJAHM, new CircleBoundary(Position(5297.3f, 2506.45f), 100.96) },
{ DATA_DEVOURER_OF_SOULS, new ParallelogramBoundary(Position(5663.56f, 2570.53f), Position(5724.39f, 2520.45f), Position(5570.36f, 2461.42f)) }
};
class instance_forge_of_souls : public InstanceMapScript
{
public:
instance_forge_of_souls() : InstanceMapScript(FoSScriptName, 632) { }
struct instance_forge_of_souls_InstanceScript : public InstanceScript
{
instance_forge_of_souls_InstanceScript(InstanceMap* map) : InstanceScript(map)
{
SetHeaders(DataHeader);
SetBossNumber(EncounterCount);
LoadBossBoundaries(boundaries);
teamInInstance = 0;
}
void OnPlayerEnter(Player* player) override
{
if (!teamInInstance)
teamInInstance = player->GetTeam();
}
void OnCreatureCreate(Creature* creature) override
{
if (!teamInInstance)
{
Map::PlayerList const& players = instance->GetPlayers();
if (!players.isEmpty())
if (Player* player = players.begin()->GetSource())
teamInInstance = player->GetTeam();
}
switch (creature->GetEntry())
{
case NPC_BRONJAHM:
bronjahm = creature->GetGUID();
break;
case NPC_DEVOURER:
devourerOfSouls = creature->GetGUID();
break;
case NPC_SYLVANAS_PART1:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_JAINA_PART1);
break;
case NPC_LORALEN:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_ELANDRA);
break;
case NPC_KALIRA:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_KORELN);
break;
}
}
uint32 GetData(uint32 type) const override
{
switch (type)
{
case DATA_TEAM_IN_INSTANCE:
return teamInInstance;
default:
break;
}
return 0;
}
ObjectGuid GetGuidData(uint32 type) const override
{
switch (type)
{
case DATA_BRONJAHM:
return bronjahm;
case DATA_DEVOURER_OF_SOULS:
return devourerOfSouls;
default:
break;
}
return ObjectGuid::Empty;
}
private:
ObjectGuid bronjahm;
ObjectGuid devourerOfSouls;
uint32 teamInInstance;
};
InstanceScript* GetInstanceScript(InstanceMap* map) const override
{
return new instance_forge_of_souls_InstanceScript(map);
}
};
void AddSC_instance_forge_of_souls()
{
new instance_forge_of_souls();
}
| [
"81566364+NemoPRM@users.noreply.github.com"
] | 81566364+NemoPRM@users.noreply.github.com |
0c49b8523f175e2db7f9923002e11324cb388792 | dad7de43b3b83d66e696394d3dea775e0afc78ad | /Phase10Dice.cpp | 2f8d43c3d265fc885678c95b423650659cb8b174 | [] | no_license | jlewixdev/Phase10Dice | 7ed2cea74463f4716d054a72964b0e84bc0efb58 | cf0b12eec2e831bedb5471ad14bee217962995d2 | refs/heads/main | 2022-12-25T23:01:09.813693 | 2020-10-04T18:57:01 | 2020-10-04T18:57:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,689 | cpp | /* Program name: Phase10DiceFINAL.cpp
* Author: Jonathon Lewis
* Date last updated: 12/11/2018
* Purpose: Final project. Implementation of Phase 10 Dice.
*/
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <string>
using namespace std;
//We actually ran into some issues with this somehow in this project. Apparently cstdlib sometimes has issues with cout and cin.
//I had to manually access cout and cin with std::cout and std::cin respectively to fix it.
enum DiceColors { ORANGE, RED, BLUE, GREEN };
//DiceColors enum. Used in dice generation.
struct Face {
int value;
DiceColors color;
};
//Face struct. Holds the value and color for each die face.
/*I'll note here that I chose to generate dice dynamically at the start of each game, as opposed to randomly
every single time a roll was needed. This allows for consistency of the die for each phase of the game, and allows the user
to play more stratigically in phase 8 specifically, because on any 6 faced die that pulls from 4 potential colors, there will be die
that are advantageous to a particular color.
The generation of the die are still random, so it should fulfill the requirements of the project. More specifics are in the generateDice function.*/
struct Die {
Face faces[6];
};
//Die struct. Each Die has exactly 6 faces, so there is an array of 6 faces to represent that.
struct Player {
int turnOrder;
int number;
int currentPhase;
int score;
int currentTurn;
int failedPhases[10];
bool turnFiveBonus = true;
};
//Player struct. Holds onto pertinent information for playing the game and displaying score.
void rollDice(Die[], Face[], int);
void generateDice(Die[]);
void playPhase(Player&, Die[]);
int passedPhase(Player, Face[]);
string colorToText(DiceColors);
void displayDice(Face[]);
bool confirmDie(bool[]);
int highestValue(int[], int);
int checkForSet(int[], int);
int checkForSet(DiceColors[], int[], int size);
int checkForRun(int[], int);
void sortArray(int[], int);
void enterDieValues(string, int[], bool[], Face[], int);
void sortPlayersByTurnOrder(Player[], int);
void showFullDice(Die[], int);
string displayRules(int);
void displayRoundInfo(Player[], int, int);
//We use a lot of functions in this program. They're all described in their bodies.
int main()
{
srand(time(NULL)); //seed the random number generator.
Die allDice[10]; //make Dice Array.
while (true) { //loop forever (until we break it later)
int playerCount;
std::cout << "Enter the number of players for this game (1-4): ";
while (!(std::cin >> playerCount) || playerCount < 1 || playerCount > 4) {
std::cout << "Invalid input. Try again";
if (!cin) {
cin.clear();
cin.ignore(INT_MAX, '\n');
}
std::cout << "\nEnter the number of players for this game (1-4): ";
}
//above code prompts the user for a number of players between 1 and 4 (yes, we do have a working solitaire mode!)
Player players[4];
for (int i = 0; i < playerCount; i++) {
players[i].number = i + 1;
players[i].currentPhase = 1;
players[i].score = 0;
players[i].currentTurn = 0;
for (int x = 0; x < 10; x++) {
players[i].failedPhases[x] = 0;
}
}//initialize all players that are playing.
if (playerCount > 1) {
bool hasBeenRolled[6] = { false };
cout << "\nAll players will roll a high dice to determine turn order";
int randomTurn;
bool looped = false;
int turnOrder[4] = { 0 }; //declare an int array that will determine turn orders for players.
for (int i = 0; i < playerCount; i++) {
do {
if (!looped) cout << "\nPlayer " << i + 1 << " must press enter to roll a die: ";
if (looped) cout << "\nThat value has already been rolled. Player " << i + 1 << " must roll again.";
char tmp;
cin.get(tmp);
randomTurn = (rand() % 6) + 5;
cout << "Player " << i + 1 << " has rolled a " << randomTurn;
//generate a random number between 5 and 10 to simulate a high dice.
if (hasBeenRolled[randomTurn - 5]) looped = true;
else looped = false;
} while (hasBeenRolled[randomTurn - 5]);
players[i].turnOrder = randomTurn;
hasBeenRolled[randomTurn - 5] = true;
}
}
else {
players[0].turnOrder = 1;
}
sortPlayersByTurnOrder(players, playerCount);
//this will sort the players array by turn order so we can simplify the execution of the game.
int playerTurn = 0; //this is the starting index of the players array. this keeps track of which player's turn it is.
std::cout << "\n\nTurn order for players: ";
for (int i = 0; i < playerCount; i++) {
std::cout << "\nPlayer " << players[i].number;
}
std::cout << endl << endl;
//display turn order for all players.
//then press a key to generate dice, and show the dice.
std::cout << "Dice will be randomly generated. Press enter to generate them: ";
char tmp;
tmp = std::cin.get();
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
//input cleanup.
generateDice(allDice);
std::cout << endl;
showFullDice(allDice, 10);
//generate random dice and display the specifics to the game. This is mostly useful for phase 8 where certain dice are more likely to get specific colors.
bool gameRunning = true;
int finalTurn = -1;
int firstFinish = 0;
int round = -1;
//declare and initialize some variables we need. finalTurn and firstFinish are for the extra credit
//of allowing users to take a final turn after a player has completed phase 10, and the first to finish phase 10 bonus, respectively.
//round is there to help us with displaying the scores between each... round.
while (gameRunning) {
//as long is the game is running, we'll keep taking turns.
if (playerTurn == finalTurn) gameRunning = false;
//we set finalTurn equal to the player who first completes phase 10 down below. When it reaches their turn
//AGAIN, it tells the game to stop.
else {
if (finalTurn != -1) cout << "\nThis is Player " << players[playerTurn].number << "'s final turn!\n";
//display a prompt if this is the player's final allowed turn.
if (players[playerTurn].currentTurn > round) {
round++;
displayRoundInfo(players, round, playerCount);
}//this if statement is round maintinence, basically. It checks to see if we've encountered a new round, and increments and displays accordingly.
playPhase(players[playerTurn], allDice);
//this function actually plays the phase. More information in the function itself.
if (players[playerTurn].currentPhase == 6) { //if they completed phase 5.
if (players[playerTurn].score >= 220 && players[playerTurn].turnFiveBonus == true) { //and if their score is high enough (and this check hasn't been done before)
players[playerTurn].score += 40; //give them bonus score, prompt them, and make it so they can't get the bonus again.
cout << "Player " << players[playerTurn].number << " has earned 40 points for completing phase 5 with over 220 score!\n";
players[playerTurn].turnFiveBonus = false;
}
else players[playerTurn].turnFiveBonus = false; //eliminate the possibility of them getting the bonus later
}
//The above if block all serves as the finishing phase 5 extra credit.
if (players[playerTurn].currentPhase > 10) { //if they completed the game
if (finalTurn == -1) { //and nobody else has.
finalTurn = playerTurn; //set finalTurn equal to the current playerTurn (so we can end the game when we get back to them)
if (playerCount > 1) { //and in a multiplayer game...
firstFinish = players[playerTurn].currentTurn; //we set the firstFinish "turn" equal to the player's current turn. So other players who finish on the same turn can get the bonus.
std::cout << "First Finish Bonus! Player " << players[playerTurn].number << " gets 40 bonus points!\n";
players[playerTurn].score += 40;
}//then we simply tell the user they got bonus points and increment accordingly.
}
else {
if (players[playerTurn].currentTurn <= firstFinish) { //if another player finishes the game on the same turn as the first finish user...
std::cout << "Matched the First Finish Bonus! Player " << players[playerTurn].number << " also gets 40 bonus points!\n";
players[playerTurn].score += 40;
}//they will also get bonus points! This works because a player who had gone before the first finish player will have a higher currentTurn than the firstFinish variable
//by the time their next turn comes around, making them ineligible for the bonus.
}
}
playerTurn++; //finally, we increment the current player's turn.
}
if (playerTurn > playerCount - 1) playerTurn = 0;
//and make sure we don't go outside the bounds of the players we are playing with.
}
//And that's the main game loop.
//After game display/cleanup.
if (playerCount > 1) {
int highestIndex = 0;
for (int i = 1; i < playerCount; i++) {
if (players[i].score > players[highestIndex].score) highestIndex = i;
}
std::cout << "Player " << players[highestIndex].number << " wins!";
std::cout << "\nTotal Scores:\n";
for (int i = 0; i < playerCount; i++) {
std::cout << "Player " << players[i].number << " score: " << players[i].score << endl;
}
}//The above block determines who won the game, and tells the user(s) who won in a multiplayer game.
else { //This else covers the end of a solitaire game.
int phasesFailed = 0;
for (int i = 0; i < 10; i++) {
phasesFailed += players[0].failedPhases[i];
}//this for loop will find every phase the player had failed and store it in a counter variable.
if (players[0].failedPhases[9] == 0) {
players[0].score += 40;
cout << "Player 1 earned 40 bonus points for completing phase 10 in one try!\n\n";
}//we also check to see if they had ever failed phase 10. In order to give them bonus score for finishing it in one try.
players[0].score -= phasesFailed * 5;
cout << "Player 1 has completed solitaire mode with a score of " << players[0].score << " and failed " << phasesFailed << " phases";
//we decrement the score by the amount of phases failed multiplied by 5, and tell the user how they did.
}
cin.clear();
cin.ignore(INT_MAX, '\n');
//input cleanup. Otherwise it had some issues.
std::cout << "\nWould you like to play again? (Y/N) ";
while (true) {
tmp = std::cin.get();
if (tmp == 'Y' || tmp == 'y') break;
else if (tmp == 'N' || tmp == 'n') return 0;
else {
std::cout << "Invalid Input. Try again.";
cin.clear();
cin.ignore(INT_MAX, '\n');
std::cout << "\nWould you like to play again ? (Y/N) ";
}
}//prompt the user if they would like to play again, and if not end the game.
}
return 0;
}
void rollDice(Die diceArray[], Face faceArray[], int index) {
//this will roll one of the dies in the dice array.
//and it stores the information of the rolled die in a faceArray.
//This is where the random factor of each die comes into play. When die are used,
//we actually roll from their 6 potential faces and use that information.
int randomFace = rand() % 6;
faceArray[index].value = diceArray[index].faces[randomFace].value;
faceArray[index].color = diceArray[index].faces[randomFace].color;
return;
}
void generateDice(Die dieArray[]) {
//this function assumes the rules of phase 10. therefore knowing what values to assign to each face.
int availableColors[4] = { 5,5,5,5 };
//This array keeps track of which "extra" colors have and haven't been used. This way we keep an equal color distribution
//across all die.
int d;
for (d = 0; d < 4; d++) { //generate low dice
int position = rand() % GREEN;
for (int i = 0; i < 4; i++) {
dieArray[d].faces[i].color = static_cast<DiceColors>(position);
if (position == GREEN) position = ORANGE;
else position++;
}//generates a random "position" to start the first 4 face colors. and then goes through each one, assigning it
//to each face.
int colorIndex = rand() % 4;
while (availableColors[colorIndex] != highestValue(availableColors, 4)) {
if (colorIndex == 3) colorIndex = 0;
else colorIndex++;
}//we determine a new random color for face 5. we also make sure it's
//pulled from one of the colors that have been used least from the "bonus" colors.
//this is to ensure equal color distribution and no repeats.
dieArray[d].faces[4].color = static_cast<DiceColors>(colorIndex);
availableColors[colorIndex]--;
//Assigns the color to the face, and decrements the part of availableColors that corresponds to that color by 1.
//This color generation is done several times so I won't comment it every time.
colorIndex = rand() % 4;
while (availableColors[colorIndex] != highestValue(availableColors, 4)) {
if (colorIndex == 3) colorIndex = 0;
else colorIndex++;
}
dieArray[d].faces[5].color = static_cast<DiceColors>(colorIndex);
availableColors[colorIndex]--;
for (int i = 0; i < 6; i++) { //loop through face of each dice.
if (i > 3) {
dieArray[d].faces[i].value = 0; //set to be a WILD face.
}
else {
dieArray[d].faces[i].value = i + 1;
//set the face value of each low dice.
}
}//this for loop sets the values of each of the low faces on each low dice.
//and ensures we get our wild values generated in the right amount.
}
for (d; d < 10; d++) { //generate high dice
int position = rand() % GREEN;
for (int i = 0; i < 4; i++) {
dieArray[d].faces[i].color = static_cast<DiceColors>(position);
if (position == GREEN) position = ORANGE;
else position++;
}
int colorIndex = rand() % 4;
while (availableColors[colorIndex] != highestValue(availableColors, 4)) {
if (colorIndex == 3) colorIndex = 0;
else colorIndex++;
}
dieArray[d].faces[4].color = static_cast<DiceColors>(colorIndex);
availableColors[colorIndex]--;
colorIndex = rand() % 4;
while (availableColors[colorIndex] != highestValue(availableColors, 4)) {
if (colorIndex == 3) {
colorIndex = 0;
}
else {
colorIndex++;
}
}
dieArray[d].faces[5].color = static_cast<DiceColors>(colorIndex);
availableColors[colorIndex]--;
//All of the above code generates colors identically to how they were done on the low dice. Except for the high dice.
//the colors are generated randomly.
for (int i = 0; i < 6; i++) {
dieArray[d].faces[i].value = i + 5;
}//this for loop sets the actual value of each face of the high dice.
}
return;
}
void playPhase(Player& currentPlayer, Die dieArray[]) {
//This is called from the main function to actually play a phase. We are sent the current player by reference
//so we can make modifications to their turn, phase, and score.
//We also are sent the entire die array so we can use it to determine rolls.
std::cout << "Player " << currentPlayer.number << "'s turn" << " Phase " << currentPlayer.currentPhase << ":" << endl << endl;
std::cout << "Player " << currentPlayer.number << " " << displayRules(currentPlayer.currentPhase) << endl << endl;
//Tell the user whose turn and phase it is, as well as display the rules of the phase.
std::cout << "Press Enter to roll dice: ";
char tmp;
tmp = std::cin.get();
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
//input cleanup.
//The above code prompts the user to hit enter to roll the dice.
Face rolledFaces[10];
for (int i = 0; i < 10; i++) {
rollDice(dieArray, rolledFaces, i);
}
//We declare an array of 10 faces, which will correspond to each die being rolled to exactly one face.
//Then we loop through and roll each die to a face randomly.
displayDice(rolledFaces); //Shows the rolled die for the user.
for (int i = 0; i < 2; i++) {
//This is a for loop that will ask the user to re-roll up to 2 times.
std::cout << "\nEnter values equal to the Die you would like to reroll. Enter 0 to stop: ";
bool rerollArray[10] = { false };
//We use a boolean array to keep track of which die we will be rerolling.
while (!confirmDie(rerollArray)) {
std::cout << "Invalid input. Try again" << endl;
std::cout << "Enter values equal to the Die you would like to reroll. Enter to stop: ";
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
}
//Input validation. The function called in the while condition also keeps track of which die are being rerolled.
bool testForBreak = true;
//determines whether there are die to be rerolled. We assume there are not.
for (int i = 0; i < 10; i++) {
if (rerollArray[i] == true) {
rollDice(dieArray, rolledFaces, i);
testForBreak = false;
//If there are die to be rerolled, we reroll them and set the testForBreak flag to false.
}
}
if (testForBreak) break; //if no die were found to be rerolled, we end this for loop prematurely (so it doesn't prompt them to reroll again)
std::cout << "\nRerolled Die" << endl;
displayDice(rolledFaces);
//then we display the die as they are rerolled.
}
int phaseScore = passedPhase(currentPlayer, rolledFaces);
//we call the passedPhase function to determine whether the user passes the phase or not.
//it returns a score that we can simultaneously use to determine whether the phase was passed,
//and if it was it also is an accurate score to increment.
if (phaseScore == -1) { //If the phase returns a score of negative one, that is our fail state for the phase.
std::cout << "Player " << currentPlayer.number << " did not pass this phase.\n\n";
currentPlayer.currentTurn++;
currentPlayer.failedPhases[currentPlayer.currentPhase - 1]++;
return;
//Tell the user that they did not pass, increment their turn, and increment that they have failed the phase.
}
else {//If the phase was passed...
std::cout << "Player " << currentPlayer.number << " earned " << phaseScore << " score for this phase!\n\n";
currentPlayer.score += phaseScore;
currentPlayer.currentPhase++;
currentPlayer.currentTurn++;
return;
//Tell the user what they scored for the phase, and increment their score, phase, and turn.
}
}
string colorToText(DiceColors color) {
if (color == ORANGE) return "Orange";
else if (color == RED) return "Red";
else if (color == BLUE) return "Blue";
else return "Green";
//This function just returns a textual representation of the colors enum.
}
void displayDice(Face rolledFaces[]) {
for (int i = 0; i < 10; i++) {
int value = rolledFaces[i].value;
if (value == 0) std::cout << "Die " << i + 1 << " value: " << "W" << " Color: " << colorToText(rolledFaces[i].color) << endl;
else std::cout << "Die " << i + 1 << " value: " << value << " Color: " << colorToText(rolledFaces[i].color) << endl;
}
return;
//This displays a textual representation of rolled die. It also shows the value for wild faces as "W" instead of 0.
}
bool confirmDie(bool boolArray[]) {
//Sets the boolean array to true when the input is valid.
//This is used to keep track of which die are being re-rolled in the playPhase function.
//Important note: this function returns false if the input is wrong.
//Otherwise it will continue to get information about which die to reroll until the user enters 0.
int currentInput;
while (std::cin >> currentInput) {
if (currentInput > 10) return false;
else if (currentInput == 0) return true;
else if(currentInput > 0 && currentInput <= 10) boolArray[currentInput - 1] = true;
else if (currentInput < 0) return false;
}
return false;
}
int highestValue(int intArray[], int size) {
int highValue = intArray[0];
for (int i = 1; i < size; i++) {
if (highValue < intArray[i]) highValue = intArray[i];
}
return highValue;
//this searches an array of ints of size... size and returns the highest value it finds.
}
int passedPhase(Player currentPlayer, Face rolledArray[]) {
//This is where the main logic of each phase is held. Most of these are very similar, so I won't be commenting
//too heavily on repeated portions of code.
if (currentPlayer.currentPhase == 1) { //If the phase is phase 1...
int chosenDiceOne[3];
bool indexChosen[10] = { false };
//We make two arrays, an int array of the chosen dice for the first set of phase 1
//and a boolean array of which indexes have been chosen (so they can't be chosen more than once).
enterDieValues("\nEnter the Die Index of the Die you would like to submit for set 1", chosenDiceOne, indexChosen, rolledArray, 3);
//This function will determine which die the player will be using for this set.
int setOne = checkForSet(chosenDiceOne, 3);
//We store the result of this set in the setOne variable, calling our checkForSet function to determine whether it's a set or not.
if (setOne == -1) return -1;
//if it's not a set, we return a "score" of -1. Implicating that the phase was failed.
int chosenDiceTwo[3];
//We have another array of size 3 for the second set of phase 1.
enterDieValues("\nEnter the Die Index of the Die you would like to submit for set 2", chosenDiceTwo, indexChosen, rolledArray, 3);
//And we get those values from the enterDieValues function (this was originally a block of code but I used it so much it became a function).
int setTwo = checkForSet(chosenDiceTwo, 3);
//we check whether setTwo is indeed a set.
if (setTwo == -1) return -1;
return setOne + setTwo; //and provided both of these sets were valid, we return the combined score of them.
}
//END OF PHASE 1 LOGIC.
/*Most of these phases are pretty identical. I'll go into new details for each phase.*/
if (currentPlayer.currentPhase == 2) {
int chosenDice[3];
bool indexChosen[10] = { false };
enterDieValues("\nEnter the Die Index of the Die you would like to submit for the set", chosenDice, indexChosen, rolledArray, 3);
int set = checkForSet(chosenDice, 3);
if (set == -1) return -1; //return a value indicating failure.
//end of checking for a set.
int chosenDiceRun[4]; //Here we use an array of size 4 to represent the values we'll be using for our run.
enterDieValues("\nEnter the Die Index of the Die you would like to submit for the run", chosenDiceRun, indexChosen, rolledArray, 4);
int run = checkForRun(chosenDiceRun, 4); //Check for run works similarly to checkForSet. Except it was harder to code and debug.
if (run == -1) return -1;
return set + run;
}
//END OF PHASE 2 LOGIC.
if (currentPlayer.currentPhase == 3) {
int chosenDiceSet[4];
bool indexChosen[10] = { false };
enterDieValues("\nEnter the Die Index of the Die you would like to submit for the set", chosenDiceSet, indexChosen, rolledArray, 4);
int set = checkForSet(chosenDiceSet, 4);
if (set == -1) return -1;
int chosenDiceRun[4];
enterDieValues("\nEnter the Die Index of the Die you would like to submit for the run", chosenDiceRun, indexChosen, rolledArray, 4);
int run = checkForRun(chosenDiceRun, 4);
if (run == -1) return -1;
return set + run;
}
//END OF PHASE 3 LOGIC.
if (currentPlayer.currentPhase == 4) {
int chosenDice[7];
bool indexChosen[10] = { false };
enterDieValues("\nEnter the Die Index of the Die you would like to submit for the run", chosenDice, indexChosen, rolledArray, 7);
return checkForRun(chosenDice, 7);
}
//END OF PHASE 4 LOGIC.
if (currentPlayer.currentPhase == 5) {
int chosenDice[8];
bool indexChosen[10] = { false };
enterDieValues("\nEnter the Die Index of the Die you would like to submit for the run", chosenDice, indexChosen, rolledArray, 8);
return checkForRun(chosenDice, 8);
}
//END OF PHASE 5 LOGIC.
if (currentPlayer.currentPhase == 6) {
int chosenDice[9];
bool indexChosen[10] = { false };
enterDieValues("\nEnter the Die Index of the Die you would like to submit for the run", chosenDice, indexChosen, rolledArray, 9);
return checkForRun(chosenDice, 9);
}
//END OF PHASE 6 LOGIC.
if (currentPlayer.currentPhase == 7) {
int chosenDiceOne[4];
bool indexChosen[10] = { false };
enterDieValues("\nEnter the Die Index of the Die you would like to submit for set 1", chosenDiceOne, indexChosen, rolledArray, 4);
int setOne = checkForSet(chosenDiceOne, 4);
if (setOne == -1) return -1;
int chosenDiceTwo[4];
enterDieValues("\nEnter the Die Index of the Die you would like to submit for set 2", chosenDiceTwo, indexChosen, rolledArray, 4);
int setTwo = checkForSet(chosenDiceTwo, 4);
if (setTwo == -1) return -1;
return setOne + setTwo;
}
//END OF PHASE 7 LOGIC
if (currentPlayer.currentPhase == 8) {
int chosenDice[7];
bool indexChosen[10] = { false };
enterDieValues("\nEnter the Die Index of the Die you would like to submit for the set", chosenDice, indexChosen, rolledArray, 7);
DiceColors chosenColors[7]; //we need to see which colors we have.
int count = 0;
for (int i = 0; count < 7; i++) { //unconventional for loop but it does exactly what we need
if (indexChosen[i]) chosenColors[count++] = rolledArray[i].color;
//will get the same color of the indexes chosen. order doesn't matter because they all need to be the same anyway so it doesn't need to be perfectly parallel
//with the chosen colors array.
}
return checkForSet(chosenColors, chosenDice, 7); //uses the overloaded function for colors.
}
//END OF PHASE 8 LOGIC
if (currentPlayer.currentPhase == 9) {
int chosenDiceOne[5];
bool indexChosen[10];
enterDieValues("\nEnter the Die Index of the Die you would like to submit for set one", chosenDiceOne, indexChosen, rolledArray, 5);
int setOne = checkForSet(chosenDiceOne, 5);
if (setOne == -1) return -1;
int chosenDiceTwo[2];
enterDieValues("\nEnter the Die Index of the Die you would like to submit for set two", chosenDiceTwo, indexChosen, rolledArray, 2);
int setTwo = checkForSet(chosenDiceTwo, 2);
if (setTwo == -1) return -1;
return setOne + setTwo;
}
//END OF PHASE 9 LOGIC
if (currentPlayer.currentPhase == 10) {
int chosenDiceOne[5];
bool indexChosen[10];
enterDieValues("\nEnter the Die Index of the Die you would like to submit for set one", chosenDiceOne, indexChosen, rolledArray, 5);
int setOne = checkForSet(chosenDiceOne, 5);
if (setOne == -1) return -1;
int chosenDiceTwo[3];
enterDieValues("\nEnter the Die Index of the Die you would like to submit for set two", chosenDiceTwo, indexChosen, rolledArray, 3);
int setTwo = checkForSet(chosenDiceTwo, 3);
if (setTwo == -1) return -1;
return setOne + setTwo;
}
//END OF PHASE 10 LOGIC
return -1; //return the fail state if you get some weird phase somehow.
}
int checkForSet(int setArray[], int size) {
//This function takes an array of ints of size... size and determines
//whether or not they make up a set of numbers. (Factoring in wildcards.)
int setValue = 0;
int total = 0;
//initializes some variables we need.
for (int i = 0; i < size; i++) {
if (setArray[i]) {
setValue = setArray[i];
break;
}
}//this for loop loops through the array and determines what the set
//will actually be comprised of.
for (int i = 0; i < size; i++) {
if (setArray[i] != 0 && setArray[i] != setValue) {
return -1;
}
else total += setArray[i];
}//If this loop finds a number that isn't a wildcard or the same number as the set value, it returns the fail state.
//Otherwise it increments the total.
return total;
//and we return the total down here if everything went well!
}
int checkForSet(DiceColors setArray[], int valueArray[], int size) {
//This is an overloaded version of checkForSet that checks for colors.
//We don't worry about wild faces here because they don't affect colors,
//but we do need to know the value of each face to increment the score.
int colorValue = setArray[0];
int total = valueArray[0];
for (int i = 1; i < size; i++) {
if (setArray[i] == colorValue) total += valueArray[i];
else return -1;
}//checks if all colors are the same, and if so it'll increment the total accordingly.
return total;
//returns the total found.
}
int checkForRun(int runArray[], int size) {
//This function checks an int array of size... size for a run of numbers.
//Was definitely more complicated to code than checkForSet.
int setStart = 0;
int total = 0;
sortArray(runArray, size);
//we sort the array so we can calculate a run from the largest number.
setStart = runArray[size - 1];
//The largest number is now in a predictable spot. So we assign the setStart to that number.
int count = 1;
total += setStart;
//We use a count variable to determine whether a set has been found later. And we increment the total
//By the first value found.
int totalWildCards = 0;
for (int i = 0; i < size; i++) {
if (runArray[i] == 0) totalWildCards++;
}
//We store the total number of wild cards available to us so our logic can work correctly later on.
int wildCardsUsed = 0;
int runMin = (setStart - size) + 1;
//We'll also need to know how many wild cards have been used, as well as the smallest possible
//value our run could have (there were bugs otherwise).
bool valuesUsed[11] = { false };
//Because we can't have repeats, we store a boolean array of
//which values are used.
valuesUsed[setStart] = true;
for (int i = size - 2; i >= 0 + wildCardsUsed; i--) {
//We start looping from the second highest index, and loop downward.
//We don't end up looping through wild faces we use.
if (runArray[i] != 0 && runArray[i] < runMin) {
total = -1;
break;
}//if we find a smaller number than the minimum and it's not a wild face, we return the fail state.
if (runArray[i] == setStart - (count + wildCardsUsed)) {
if (runArray[i] != 0) {
if (!valuesUsed[runArray[i]]) {
count++;
total += runArray[i];
valuesUsed[runArray[i]] = true;
}
else {
total = -1;
break;
}
}//determines whether a nonzero value has been used before. If not, we allow this to happen
//and set the check to true that it has been used before.
//If it has been used before, we return the fail state. This was a hard bug to track down.
else {
count++;
total += runArray[i];
}
}//If we find the next value that we need for the run, we increment the count
//and the total.
//This works because it's looking for setStart - (count + wildCardsUsed). Every time we find a new number
//it will look for a lower number. And if we used a wild face to "be" another number, it accounts for that.
else if (totalWildCards > 0) {
//If we don't quite find the number we are looking for, but have wildcards to spare...
totalWildCards--;
wildCardsUsed++;
count++;
total += runArray[i];
}//we pretend like we found a decent number, and increment (and decrement) necessary variables.
//this is structured in a way that is preserves the main logic.
else {
total = -1;
break;
} //If we find a number that isn't what we're looking for and no more wildcards exist, return the fail state.
}
return total;
}
void sortArray(int intArray[], int size) {
//these are relatively small so we'll just do a selection sort.
for (int i = 0; i < size - 1; i++) {
int smallestIndex = i;
for (int x = i + 1; x < size; x++) {
if (intArray[x] < intArray[smallestIndex]) smallestIndex = x;
}//find the smallest value and store the index of it.
int tmp = intArray[i];
intArray[i] = intArray[smallestIndex];
intArray[smallestIndex] = tmp;
}//does the swap for us.
}
void enterDieValues(string prompt, int storedArray[], bool chosenIndexes[], Face dieArray[], int size) {
//I ended up doing this a whole lot. So I made it into a function so it wouldn't clog the passedPhase function (it's so much more readible now.)
std::cout << prompt << " (" << size << " dice): ";
//Prompts the user for what we need. Depends on the function call.
for (int i = 0; i < size; i++) {
int selectedIndex;
while (!(std::cin >> selectedIndex) || selectedIndex > 10 || selectedIndex < 1 || chosenIndexes[selectedIndex - 1] == true) {
std::cout << "Invalid input. Try again" << endl;
std::cout << prompt << " (" << size - i << " dice): ";
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
}
storedArray[i] = dieArray[selectedIndex - 1].value;
chosenIndexes[selectedIndex - 1] = true;
}
//And stores the integers we need from the user, provided they get passed the input validation.
}
void sortPlayersByTurnOrder(Player players[], int numberOfPlayers) {
//This is the same as the selection sort array but by a different name.
//I thought of overloading the other function but thought this would be more clear to myself.
for (int i = 0; i < numberOfPlayers; i++) {
int highestIndex = i;
for (int x = i + 1; x < numberOfPlayers; x++) {
if (players[x].turnOrder > players[highestIndex].turnOrder) highestIndex = x;
}
Player tmp = players[i];
players[i] = players[highestIndex];
players[highestIndex] = tmp;
}
//This function changes the order of the players array based on their turn order.
}
void showFullDice(Die diceArray[], int size) {
for (int i = 0; i < size; i++) {
std::cout << "Die " << i + 1 << endl;
for (int x = 0; x < 6; x++) {
if (diceArray[i].faces[x].value == 0) std::cout << "Face " << x + 1 << " Value: " << "W" << " Color: " << colorToText(diceArray[i].faces[x].color) << endl;
else std::cout << "Face " << x + 1 << " Value: " << diceArray[i].faces[x].value << " Color: " << colorToText(diceArray[i].faces[x].color) << endl;
}
std::cout << endl;
}
//Displays the full information when dice are generated. So you can know which values correspond to which colors, and which colors are more prevalent on certain dice.
}
string displayRules(int phase) {
if (phase == 1) return "must roll 2 sets of 3";
if (phase == 2) return "must roll 1 set of 3 and 1 run of 4";
if (phase == 3) return "must roll 1 set of 4 and 1 run of 4";
if (phase == 4) return "must roll 1 run of 7";
if (phase == 5) return "must roll 1 run of 8";
if (phase == 6) return "must roll 1 run of 9";
if (phase == 7) return "must roll 2 sets of 4";
if (phase == 8) return "must roll 7 of all one color";
if (phase == 9) return "must roll 1 set of 5 and 1 set of 2";
if (phase == 10) return "1 set of 5 and 1 set of 3";
return "error";
//Returns the rules as a string for each phase.
}
void displayRoundInfo(Player players[], int round, int numberOfPlayers) {
std::cout << "----------------------------------------------";
std::cout << "\nRound " << round + 1 << " begins! Current Player Scores and Phases: " << endl;
for (int i = 0; i < numberOfPlayers; i++) {
std::cout << "Player " << players[i].number << " Current Phase: " << players[i].currentPhase << " Score: " << players[i].score << endl;
}
std::cout << "----------------------------------------------";
std::cout << endl;
//Displays player scores, the current round, and the phase of each player every round.
}
| [
"jlewis170@ivytech.edu"
] | jlewis170@ivytech.edu |
e246e8f5b98c155b814c51a2bed2087d0618fd6c | 7e2ea3df623b1610adbef1b7d54456ebe2b67762 | /work/Dec16/Bi3_2.hpp | 85fd49e5c545ca74dbb501777fa3dcefe46602b3 | [] | no_license | sallop/Bachelor | 364f21771e66c4e0e9b01f15dc4a7aaa63ecc427 | 162dc5f8020a9b25795a35cfad3973b7314a8c45 | refs/heads/master | 2020-12-24T13:21:34.640298 | 2012-12-22T02:02:36 | 2012-12-22T02:02:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 319 | hpp | #ifndef BI3_2_H_
#define BI3_2_H_
class Bspline2d
{
public:
double px[3], py[3], pz[3];
double X(double t);
double Y(double t);
double Z(double t);
Bspline2d();
Bspline2d(double x0, double y0, double z0,
double x1, double y1, double z1,
double x2, double y2, double z2 );
};
#endif // BI3_2_H_
| [
"akitaka@neccomputer.(none)"
] | akitaka@neccomputer.(none) |
82219cebb30a401f0c1b6d9e0b886b64f722a323 | d2d6aae454fd2042c39127e65fce4362aba67d97 | /build/Android/Preview/app/src/main/include/Basic.Switch.h | b019c7a52d2dec6bbd6f28c7ba2e7e19a1e2b93f | [] | no_license | Medbeji/Eventy | de88386ff9826b411b243d7719b22ff5493f18f5 | 521261bca5b00ba879e14a2992e6980b225c50d4 | refs/heads/master | 2021-01-23T00:34:16.273411 | 2017-09-24T21:16:34 | 2017-09-24T21:16:34 | 92,812,809 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,889 | h | // This file was generated based on '/Users/medbeji/Library/Application Support/Fusetools/Packages/Fuse.BasicTheme/0.47.7/.uno/ux11/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Controls.Native.-ba5282a0.h>
#include <Fuse.Controls.ToggleControl.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Fuse.Triggers.Actions-b5190bae.h>
#include <Fuse.Triggers.Actions-ea70af1f.h>
#include <Fuse.Triggers.IValue-1.h>
#include <Uno.Bool.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.Float4.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{namespace Basic{struct Switch;}}
namespace g{namespace Fuse{namespace Controls{struct Circle;}}}
namespace g{namespace Fuse{namespace Controls{struct Panel;}}}
namespace g{namespace Fuse{namespace Drawing{struct SolidColor;}}}
namespace g{namespace Fuse{namespace Drawing{struct Stroke;}}}
namespace g{namespace Fuse{namespace Effects{struct DropShadow;}}}
namespace g{namespace Uno{namespace UX{struct NameTable;}}}
namespace g{namespace Uno{namespace UX{struct Property1;}}}
namespace g{namespace Uno{namespace UX{struct Selector;}}}
namespace g{
namespace Basic{
// public partial sealed class Switch :492
// {
::g::Fuse::Controls::ToggleControl_type* Switch_typeof();
void Switch__ctor_8_fn(Switch* __this);
void Switch__InitializeUX_fn(Switch* __this);
void Switch__New5_fn(Switch** __retval);
struct Switch : ::g::Fuse::Controls::ToggleControl
{
uStrong< ::g::Uno::UX::NameTable*> __g_nametable1;
static uSStrong<uArray*> __g_static_nametable1_;
static uSStrong<uArray*>& __g_static_nametable1() { return Switch_typeof()->Init(), __g_static_nametable1_; }
static ::g::Uno::UX::Selector __selector0_;
static ::g::Uno::UX::Selector& __selector0() { return Switch_typeof()->Init(), __selector0_; }
static ::g::Uno::UX::Selector __selector1_;
static ::g::Uno::UX::Selector& __selector1() { return Switch_typeof()->Init(), __selector1_; }
static ::g::Uno::UX::Selector __selector2_;
static ::g::Uno::UX::Selector& __selector2() { return Switch_typeof()->Init(), __selector2_; }
static ::g::Uno::UX::Selector __selector3_;
static ::g::Uno::UX::Selector& __selector3() { return Switch_typeof()->Init(), __selector3_; }
static ::g::Uno::UX::Selector __selector4_;
static ::g::Uno::UX::Selector& __selector4() { return Switch_typeof()->Init(), __selector4_; }
static ::g::Uno::UX::Selector __selector5_;
static ::g::Uno::UX::Selector& __selector5() { return Switch_typeof()->Init(), __selector5_; }
uStrong< ::g::Fuse::Controls::Panel*> _switchBounds;
uStrong< ::g::Fuse::Drawing::Stroke*> _switchStroke;
uStrong< ::g::Uno::UX::Property1*> _switchStroke_Width_inst;
uStrong< ::g::Fuse::Drawing::SolidColor*> _switchStrokeColor;
uStrong< ::g::Uno::UX::Property1*> _switchStrokeColor_Color_inst;
uStrong< ::g::Fuse::Controls::Circle*> _switchThumb;
uStrong< ::g::Fuse::Drawing::SolidColor*> _switchThumbColor;
uStrong< ::g::Uno::UX::Property1*> _switchThumbColor_Color_inst;
uStrong< ::g::Fuse::Drawing::Stroke*> _switchThumbStroke;
uStrong< ::g::Uno::UX::Property1*> _switchThumbStroke_Width_inst;
uStrong< ::g::Fuse::Effects::DropShadow*> switchShadow;
uStrong< ::g::Uno::UX::Property1*> switchShadow_Color_inst;
uStrong< ::g::Uno::UX::Property1*> temp_Value_inst;
uStrong< ::g::Uno::UX::Property1*> temp1_Value_inst;
void ctor_8();
void InitializeUX();
static Switch* New5();
};
// }
}} // ::g::Basic
| [
"medbeji@MacBook-Pro-de-MedBeji.local"
] | medbeji@MacBook-Pro-de-MedBeji.local |
c19e973dd988b1dd61e92160bc5f348ea8e53a15 | cde9104f5503f480fa14ea4af840cfb85ad9a59b | /include/fastdds/rtps/attributes/RTPSParticipantAllocationAttributes.hpp | 28aa0cda3824eae832d4e08c90bed40ace173635 | [
"Apache-2.0"
] | permissive | xyyeh/Fast-DDS | 4761cd34b002e19a47379ccad9790059fdc5d569 | a36650b19ff21519d188af78081074c2f0d952c4 | refs/heads/master | 2023-03-05T23:58:17.494401 | 2021-02-17T14:43:52 | 2021-02-17T14:43:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,779 | hpp | // Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file RTPSParticipantAllocationAttributes.hpp
*/
#ifndef _FASTDDS_RTPS_RTPSPARTICIPANTALLOCATIONATTRIBUTES_HPP_
#define _FASTDDS_RTPS_RTPSPARTICIPANTALLOCATIONATTRIBUTES_HPP_
#include <fastrtps/utils/collections/ResourceLimitedContainerConfig.hpp>
namespace eprosima {
namespace fastrtps {
namespace rtps {
/**
* @brief Holds limits for collections of remote locators.
*/
struct RemoteLocatorsAllocationAttributes
{
bool operator ==(
const RemoteLocatorsAllocationAttributes& b) const
{
return (this->max_unicast_locators == b.max_unicast_locators) &&
(this->max_multicast_locators == b.max_multicast_locators);
}
/** Maximum number of unicast locators per remote entity.
*
* This attribute controls the maximum number of unicast locators to keep for
* each discovered remote entity (be it a participant, reader of writer). It is
* recommended to use the highest number of local addresses found on all the systems
* belonging to the same domain as this participant.
*/
size_t max_unicast_locators = 4u;
/** Maximum number of multicast locators per remote entity.
*
* This attribute controls the maximum number of multicast locators to keep for
* each discovered remote entity (be it a participant, reader of writer). The
* default value of 1 is usually enough, as it doesn't make sense to add more
* than one multicast locator per entity.
*/
size_t max_multicast_locators = 1u;
};
/**
* @brief Holds limits for send buffers allocations.
*/
struct SendBuffersAllocationAttributes
{
bool operator ==(
const SendBuffersAllocationAttributes& b) const
{
return (this->preallocated_number == b.preallocated_number) &&
(this->dynamic == b.dynamic);
}
/** Initial number of send buffers to allocate.
*
* This attribute controls the initial number of send buffers to be allocated.
* The default value of 0 will perform an initial guess of the number of buffers
* required, based on the number of threads from which a send operation could be
* started.
*/
size_t preallocated_number = 0u;
/** Whether the number of send buffers is allowed to grow.
*
* This attribute controls how the buffer manager behaves when a send buffer is not
* available. When true, a new buffer will be created. When false, it will wait for a
* buffer to be returned. This is a tradeoff between latency and dynamic allocations.
*/
bool dynamic = false;
};
/**
* @brief Holds limits for variable-length data.
*/
struct VariableLengthDataLimits
{
bool operator ==(
const VariableLengthDataLimits& b) const
{
return (this->max_properties == b.max_properties) &&
(this->max_user_data == b.max_user_data) &&
(this->max_partitions == b.max_partitions) &&
(this->max_datasharing_domains == b.max_datasharing_domains);
}
//! Defines the maximum size (in octets) of properties data in the local or remote participant
size_t max_properties = 0;
//! Defines the maximum size (in octets) of user data in the local or remote participant
size_t max_user_data = 0;
//! Defines the maximum size (in octets) of partitions data
size_t max_partitions = 0;
//! Defines the maximum size (in elements) of the list of data sharing domain IDs
size_t max_datasharing_domains = 0;
};
/**
* @brief Holds allocation limits affecting collections managed by a participant.
*/
struct RTPSParticipantAllocationAttributes
{
//! Holds limits for collections of remote locators.
RemoteLocatorsAllocationAttributes locators;
//! Defines the allocation behaviour for collections dependent on the total number of participants.
ResourceLimitedContainerConfig participants;
//! Defines the allocation behaviour for collections dependent on the total number of readers per participant.
ResourceLimitedContainerConfig readers;
//! Defines the allocation behaviour for collections dependent on the total number of writers per participant.
ResourceLimitedContainerConfig writers;
//! Defines the allocation behaviour for the send buffer manager.
SendBuffersAllocationAttributes send_buffers;
//! Holds limits for variable-length data
VariableLengthDataLimits data_limits;
//! @return the allocation config for the total of readers in the system (participants * readers)
ResourceLimitedContainerConfig total_readers() const
{
return total_endpoints(readers);
}
//! @return the allocation config for the total of writers in the system (participants * writers)
ResourceLimitedContainerConfig total_writers() const
{
return total_endpoints(writers);
}
bool operator ==(
const RTPSParticipantAllocationAttributes& b) const
{
return (this->locators == b.locators) &&
(this->participants == b.participants) &&
(this->readers == b.readers) &&
(this->writers == b.writers) &&
(this->send_buffers == b.send_buffers) &&
(this->data_limits == b.data_limits);
}
private:
ResourceLimitedContainerConfig total_endpoints(
const ResourceLimitedContainerConfig& endpoints) const
{
constexpr size_t max = std::numeric_limits<size_t>::max();
size_t initial;
size_t maximum;
size_t increment;
initial = participants.initial * endpoints.initial;
maximum = (participants.maximum == max || endpoints.maximum == max)
? max : participants.maximum * endpoints.maximum;
increment = std::max(participants.increment, endpoints.increment);
return { initial, maximum, increment };
}
};
const RTPSParticipantAllocationAttributes c_default_RTPSParticipantAllocationAttributes
= RTPSParticipantAllocationAttributes();
} /* namespace rtps */
} /* namespace fastrtps */
} /* namespace eprosima */
#endif /* _FASTDDS_RTPS_RTPSPARTICIPANTALLOCATIONATTRIBUTES_HPP_ */
| [
"noreply@github.com"
] | noreply@github.com |
aa7759d1a6e28d211de54036c13fc4d0ff27f092 | dc814e7323ce2584512d9148af2da54d090d7a18 | /JazInterpreter/JazInterpreter/Functions.h | b06058c7de5eb9cc50b5549758ffd7414032b7e3 | [] | no_license | ellycediver/JazInterpreter | 9027805a138d67f970df91df496975736d99ff9f | 4527c07dea5901b65bdde5e9f372563c2fa1367d | refs/heads/master | 2021-04-06T20:28:32.647994 | 2018-03-15T23:04:53 | 2018-03-15T23:04:53 | 125,436,351 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,825 | h | #pragma once
////////////////////////////////////////////////////////////////
// Description:This file contains the implementation of the
// functions performed by the jaz machine
////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <vector>
using namespace std;
////////////////////////////////
///////STACK MANIPULATION///////
////////////////////////////////
//Pushes value to stack
void push(string value);
//Pushes the value of the passed variable on the machine stack.
//Searches for the variable in the list of variables within the scope and
//if found pushes its value into the machine stack
void rvalue(string variable);
//Pushes the address of the variable indicated into the machine stack.
//Searches for the variable in the list of variables available in the
//scope and pushes it if found, or it creates a new variable if not
void lvalue(string variable);
//Pops the top value of the stack
void pop();
//Takes the value on top of the stack and places it into the location placed below it.
//It also pops both values from the stack
void colEquals();
//Pushes a copy of the top value on machine stack.
void copy();
////////////////////////////////
//////////CONTROL FLOW//////////
////////////////////////////////
//Looks for a label with the name indicated
//and if not found it creates one with the current program
//counter as the line number
void label(string label, int programCounter);
//Jumps to the location indicated by the label.
void goTo(string label, int &programCounter);
//Jumps if the top value in the machine stack is 0
void goFalse(string label, int &programCounter);
//Jumps if the top value in the machine stack is nonzero
void goTrue(string label, int &programCounter);
//stops the program execution
void halt(int &programCounter);
//////////////////////////////////
///////ARITHMETIC OPERATORS///////
//////////////////////////////////
//Adds top two values on the machine stack and places result beck on the stack.
void plusOp();
//Subtracts top two values on the mahcine stack and places result back on the stack.
void minusOp();
//Multiplies top two values on the machine stack and places result back on the stack.
void multiOp();
//Divides the top two values on the machine stack and places result back on the stack.
void divOp();
//Mods the top two values on the machine stack and places result back on the stack.
void modOp();
////////////////////////////////
///////LOGICAL OPERATORS////////
////////////////////////////////
//Logical AND the top two values on the machine stack and places result back on the stack.
void and();
//Logical NOT the top value on the machine stack and places result back on the stack.
void not();
//Logical OR the top two values on the machine stack and places result back on the stack.
void or ();
//////////////////////////////////
///////RELATIONAL OPERATORS///////
//////////////////////////////////
//Checks if the top to values of the machine stack are different.
//Pushes 1 to the stack if the values are different, 0 otherwise
void different();
//Checks if the top minus one of the machine stack is less or equal than the top
//Pushes 1 to the stack if less or equal, 0 otherwise
void lessThanEq();
//Checks if the top minus one of the machine stack is greater or equal than the top
//Pushes 1 to the stack if greater or equal, 0 otherwise
void greaterThanEq();
//Checks if the top minus one of the machine stack is less than the top
//Pushes 1 to the stack if less, 0 otherwise
void lessThan();
//Checks if the top minus one of the machine stack is greater than the top
//Pushes 1 to the stack if greater, 0 otherwise
void greaterThan();
//Checks if the top two values of the machine stack are equal.
//Pushes 1 to the stack if the values are equal, 0 otherwise
void equalTo();
////////////////////////////////
/////////////OUTPUT/////////////
////////////////////////////////
//Prints the value from the top of the machine stack.
void print();
//Prints the string passed with the instruction
void show(vector<string>);
////////////////////////////////
///////SUBPROGRAM CONTROL///////
////////////////////////////////
//Starts the parameter passing block.
//Increases the stack for writing variables
void begin();
//Ends parameter passing block.
//Decreases the stack for reading variables
void end();
//Ends the function call, gets the top value from the jump stack,
//pops the machine stack and lowers the variable writing stack
void Return(int &programCounter);
//Starts the function call. Sets the instruction counter
//to the location of the passed label, pushes the old instruction
//pointer value to the jump stack, pushes a new list to the
//machine stack and increases the read variable pointer
void call(string label, int &programCounter); | [
"ediver@rockets.utoledo.edu"
] | ediver@rockets.utoledo.edu |
4396efa47011ecce9e21d5747c8217eb269f765f | 5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e | /main/source/src/core/scoring/methods/SymmetricLigandEnergy.hh | 394664f966379c3dbda3517b83eae092ab762b55 | [] | no_license | MedicaicloudLink/Rosetta | 3ee2d79d48b31bd8ca898036ad32fe910c9a7a28 | 01affdf77abb773ed375b83cdbbf58439edd8719 | refs/heads/master | 2020-12-07T17:52:01.350906 | 2020-01-10T08:24:09 | 2020-01-10T08:24:09 | 232,757,729 | 2 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 2,428 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file core/scoring/methods/SymmetricLigandEnergy.hh
/// @brief score for implicit ligand interactions from symmetric geometry
/// @author Will Sheffler
#ifndef INCLUDED_core_scoring_methods_SymmetricLigandEnergy_hh
#define INCLUDED_core_scoring_methods_SymmetricLigandEnergy_hh
// Unit headers
#include <core/scoring/methods/SymmetricLigandEnergy.fwd.hh>
// Package headers
#include <core/scoring/methods/ContextIndependentOneBodyEnergy.hh>
#include <core/scoring/ScoreFunction.fwd.hh>
// Project headers
#include <core/pose/Pose.fwd.hh>
#include <core/kinematics/DomainMap.fwd.hh>
#include <core/types.hh>
#include <utility/vector1.hh>
namespace core {
namespace scoring {
namespace methods {
class SymmetricLigandEnergy : public ContextIndependentOneBodyEnergy {
public:
typedef ContextIndependentOneBodyEnergy parent;
/// @brief ctor
SymmetricLigandEnergy();
/// @brief dtor
virtual ~SymmetricLigandEnergy();
/// clone
virtual
EnergyMethodOP
clone() const;
/////////////////////////////////////////////////////////////////////////////
// methods for ContextIndependentOneBodyEnergies
/////////////////////////////////////////////////////////////////////////////
virtual
void
residue_energy(
conformation::Residue const & rsd,
pose::Pose const & pose,
EnergyMap & emap
) const;
virtual
void
eval_atom_derivative(
id::AtomID const & id,
pose::Pose const & pose,
kinematics::DomainMap const & domain_map,
ScoreFunction const & sfxn,
EnergyMap const & emap,
Vector & F1,
Vector & F2
) const;
/// @brief SymmetricLigandEnergy is context independent; indicates that no
/// context graphs are required
virtual
void indicate_required_context_graphs( utility::vector1< bool > & ) const;
virtual
core::Size version() const;
};
} // methods
} // scoring
} // core
#endif // INCLUDED_core_scoring_SymmetricLigandEnergy_HH
| [
"36790013+MedicaicloudLink@users.noreply.github.com"
] | 36790013+MedicaicloudLink@users.noreply.github.com |
b37ec4167ed73e787d14378d7aed9e1b355f1770 | 665443052fa3c17f94c945f08b6378016d5a1dae | /0152/src/mame/includes/spdodgeb.h | ec47eee5ac3bd766bc80ff2cb90c59fa4394d24c | [] | no_license | dezi/mame-libretro-odroid | a6f3e0fd87e00fe8beda936f1cd3cf2fe508fcf0 | 31b588c088928f967b9fb9cf903b7a3f18a91eaa | refs/heads/master | 2020-04-18T07:49:09.588326 | 2014-02-11T14:27:40 | 2014-02-11T14:27:40 | 16,698,177 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,992 | h | #include "sound/msm5205.h"
class spdodgeb_state : public driver_device
{
public:
spdodgeb_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag),
m_videoram(*this, "videoram"),
m_spriteram(*this, "spriteram"),
m_maincpu(*this,"maincpu"),
m_audiocpu(*this, "audiocpu"),
m_msm1(*this, "msm1"),
m_msm2(*this, "msm2"){ }
int m_toggle;
int m_adpcm_pos[2];
int m_adpcm_end[2];
int m_adpcm_idle[2];
int m_adpcm_data[2];
int m_mcu63701_command;
int m_inputs[4];
UINT8 m_tapc[4];
UINT8 m_last_port[2];
UINT8 m_last_dash[2];
#if 0
int m_running[2];
int m_jumped[2];
int m_prev[2][2];
int m_countup[2][2];
int m_countdown[2][2];
int m_prev[2];
#endif
required_shared_ptr<UINT8> m_videoram;
int m_tile_palbank;
int m_sprite_palbank;
tilemap_t *m_bg_tilemap;
int m_lastscroll;
required_shared_ptr<UINT8> m_spriteram;
required_device<cpu_device> m_maincpu;
DECLARE_WRITE8_MEMBER(sound_command_w);
DECLARE_WRITE8_MEMBER(spd_adpcm_w);
DECLARE_READ8_MEMBER(mcu63701_r);
DECLARE_WRITE8_MEMBER(mcu63701_w);
DECLARE_READ8_MEMBER(port_0_r);
DECLARE_WRITE8_MEMBER(spdodgeb_scrollx_lo_w);
DECLARE_WRITE8_MEMBER(spdodgeb_ctrl_w);
DECLARE_WRITE8_MEMBER(spdodgeb_videoram_w);
TILEMAP_MAPPER_MEMBER(background_scan);
TILE_GET_INFO_MEMBER(get_bg_tile_info);
virtual void machine_reset();
virtual void video_start();
virtual void palette_init();
UINT32 screen_update_spdodgeb(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
TIMER_DEVICE_CALLBACK_MEMBER(spdodgeb_interrupt);
void draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect );
void mcu63705_update_inputs();
DECLARE_WRITE_LINE_MEMBER(irqhandler);
void spd_adpcm_int(msm5205_device *device, int chip);
DECLARE_WRITE_LINE_MEMBER(spd_adpcm_int_1);
DECLARE_WRITE_LINE_MEMBER(spd_adpcm_int_2);
required_device<cpu_device> m_audiocpu;
required_device<msm5205_device> m_msm1;
required_device<msm5205_device> m_msm2;
};
| [
"dezi@kappa-mm.de"
] | dezi@kappa-mm.de |
7a35f08f6dbe6ed6efa14ec850a70bb588cc4b21 | 923aef6b500dd66e1b598008030b483eaa481734 | /GeneratedFiles/ui_newmachinewidget.h | bb06fb55ec46db454ee26d1a4b04cba4a472e351 | [] | no_license | yangbohust/cellImaging | ead59f1edacb4aa956c49c25a31a96eb7c951d61 | dc5e2b2a45d1be0ad51b921831f6dc3a36250b1a | refs/heads/master | 2021-04-09T14:18:21.443044 | 2018-03-24T07:43:52 | 2018-03-24T07:43:52 | 125,692,773 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,605 | h | /********************************************************************************
** Form generated from reading UI file 'newmachinewidget.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_NEWMACHINEWIDGET_H
#define UI_NEWMACHINEWIDGET_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTableView>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_NewMachineWidget
{
public:
QTableView *tableView;
QPushButton *pushButton;
QLabel *label;
QLineEdit *lineEdit;
QLabel *label_2;
QLineEdit *lineEdit_2;
QLabel *label_3;
QLineEdit *lineEdit_3;
void setupUi(QWidget *NewMachineWidget)
{
if (NewMachineWidget->objectName().isEmpty())
NewMachineWidget->setObjectName(QStringLiteral("NewMachineWidget"));
NewMachineWidget->resize(776, 612);
tableView = new QTableView(NewMachineWidget);
tableView->setObjectName(QStringLiteral("tableView"));
tableView->setGeometry(QRect(10, 10, 751, 501));
pushButton = new QPushButton(NewMachineWidget);
pushButton->setObjectName(QStringLiteral("pushButton"));
pushButton->setGeometry(QRect(660, 570, 104, 32));
label = new QLabel(NewMachineWidget);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(30, 540, 111, 17));
lineEdit = new QLineEdit(NewMachineWidget);
lineEdit->setObjectName(QStringLiteral("lineEdit"));
lineEdit->setGeometry(QRect(160, 540, 113, 23));
label_2 = new QLabel(NewMachineWidget);
label_2->setObjectName(QStringLiteral("label_2"));
label_2->setGeometry(QRect(30, 580, 81, 17));
lineEdit_2 = new QLineEdit(NewMachineWidget);
lineEdit_2->setObjectName(QStringLiteral("lineEdit_2"));
lineEdit_2->setGeometry(QRect(90, 580, 113, 23));
label_3 = new QLabel(NewMachineWidget);
label_3->setObjectName(QStringLiteral("label_3"));
label_3->setGeometry(QRect(370, 540, 81, 17));
lineEdit_3 = new QLineEdit(NewMachineWidget);
lineEdit_3->setObjectName(QStringLiteral("lineEdit_3"));
lineEdit_3->setGeometry(QRect(450, 540, 113, 23));
retranslateUi(NewMachineWidget);
QMetaObject::connectSlotsByName(NewMachineWidget);
} // setupUi
void retranslateUi(QWidget *NewMachineWidget)
{
NewMachineWidget->setWindowTitle(QApplication::translate("NewMachineWidget", "NewMachineWidget", Q_NULLPTR));
pushButton->setText(QApplication::translate("NewMachineWidget", "\346\267\273\345\212\240\350\256\260\345\275\225", Q_NULLPTR));
label->setText(QApplication::translate("NewMachineWidget", "\345\256\236\351\252\214\350\256\276\345\244\207\347\274\226\345\217\267\357\274\232", Q_NULLPTR));
label_2->setText(QApplication::translate("NewMachineWidget", "\345\205\211\346\272\220\357\274\232", Q_NULLPTR));
label_3->setText(QApplication::translate("NewMachineWidget", "\346\216\242\346\265\213\345\231\250\357\274\232", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class NewMachineWidget: public Ui_NewMachineWidget {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_NEWMACHINEWIDGET_H
| [
"772800726@qq.com"
] | 772800726@qq.com |
89ad5d10ecda5d723641692344eb849e8d591cb0 | 82183b83df150adc10695ca8ee2df0fa4e2253b3 | /hphp/runtime/base/bespoke-array.cpp | c885d15ac8c71414d90c9a083a41fb8e5e1ed913 | [
"PHP-3.01",
"Zend-2.0",
"MIT"
] | permissive | Mostafa-At-GitHub/hhvm | 5f80066c3c5cb5435983ebfc523b2d65117fd085 | a987547f303d32411c5a826d88120a64a8beca94 | refs/heads/master | 2023-04-01T09:44:24.761453 | 2021-04-10T06:20:21 | 2021-04-10T06:21:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,317 | cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/apc-stats.h"
#include "hphp/runtime/base/array-data-defs.h"
#include "hphp/runtime/base/bespoke-array.h"
#include "hphp/runtime/base/bespoke/layout.h"
#include "hphp/runtime/base/bespoke/logging-array.h"
#include "hphp/runtime/base/mixed-array-defs.h"
#include "hphp/runtime/base/sort-flags.h"
#include "hphp/runtime/base/tv-refcount.h"
namespace HPHP {
//////////////////////////////////////////////////////////////////////////////
namespace {
using bespoke::g_layout_funcs;
uint8_t getLayoutByte(const ArrayData* ad) {
auto const result = BespokeArray::asBespoke(ad)->layoutIndex().byte();
assertx(g_layout_funcs.fnRelease[result] != nullptr);
return result;
}
}
BespokeArray* BespokeArray::asBespoke(ArrayData* ad) {
auto ret = reinterpret_cast<BespokeArray*>(ad);
assertx(ret->checkInvariants());
return ret;
}
const BespokeArray* BespokeArray::asBespoke(const ArrayData* ad) {
return asBespoke(const_cast<ArrayData*>(ad));
}
bespoke::LayoutIndex BespokeArray::layoutIndex() const {
return {m_extra_hi16};
}
const bespoke::LayoutFunctions* BespokeArray::vtable() const {
return bespoke::ConcreteLayout::FromConcreteIndex(layoutIndex())->vtable();
}
void BespokeArray::setLayoutIndex(bespoke::LayoutIndex index) {
m_extra_hi16 = index.raw;
}
NO_PROFILING
size_t BespokeArray::heapSize() const {
return g_layout_funcs.fnHeapSize[getLayoutByte(this)](this);
}
NO_PROFILING
void BespokeArray::scan(type_scan::Scanner& scan) const {
return g_layout_funcs.fnScan[getLayoutByte(this)](this, scan);
}
NO_PROFILING
ArrayData* BespokeArray::ToVanilla(const ArrayData* ad, const char* reason) {
return g_layout_funcs.fnEscalateToVanilla[getLayoutByte(ad)](ad, reason);
}
bool BespokeArray::checkInvariants() const {
assertx(!isVanilla());
assertx(kindIsValid());
assertx(!isSampledArray());
static_assert(ArrayData::kDefaultVanillaArrayExtra == uint32_t(-1));
DEBUG_ONLY auto constexpr kVanillaLayoutIndex = uint16_t(-1);
assertx(m_extra_hi16 != kVanillaLayoutIndex);
return true;
}
//////////////////////////////////////////////////////////////////////////////
ArrayData* BespokeArray::MakeUncounted(ArrayData* ad, bool hasApcTv,
DataWalker::PointerMap* seen) {
assertx(ad->isRefCounted());
auto const vad = ToVanilla(ad, "BespokeArray::MakeUncounted");
SCOPE_EXIT { decRefArr(vad); };
if (seen) {
auto const mark = [&](TypedValue tv) {
if (isRefcountedType(type(tv)) && val(tv).pcnt->hasMultipleRefs()) {
seen->insert({val(tv).pcnt, nullptr});
}
};
if (vad->hasMultipleRefs()) seen->insert({vad, nullptr});
IterateKV(vad, [&](auto k, auto v) { mark(k); mark(v); });
}
if (vad->isVanillaVec()) {
return PackedArray::MakeUncounted(vad, hasApcTv, seen);
} else if (vad->isVanillaDict()) {
return MixedArray::MakeUncounted(vad, hasApcTv, seen);
}
return SetArray::MakeUncounted(vad, hasApcTv, seen);
}
void BespokeArray::ReleaseUncounted(ArrayData* ad) {
if (!ad->uncountedDecRef()) return;
auto const byte = getLayoutByte(ad);
g_layout_funcs.fnReleaseUncounted[byte](ad);
if (APCStats::IsCreated()) {
APCStats::getAPCStats().removeAPCUncountedBlock();
}
auto const bytes = g_layout_funcs.fnHeapSize[byte](ad);
auto const extra = uncountedAllocExtra(ad, ad->hasApcTv());
uncounted_sized_free(reinterpret_cast<char*>(ad) - extra, bytes + extra);
}
//////////////////////////////////////////////////////////////////////////////
// ArrayData interface
NO_PROFILING
void BespokeArray::Release(ArrayData* ad) {
g_layout_funcs.fnRelease[getLayoutByte(ad)](ad);
}
NO_PROFILING
bool BespokeArray::IsVectorData(const ArrayData* ad) {
return g_layout_funcs.fnIsVectorData[getLayoutByte(ad)](ad);
}
// RO access
NO_PROFILING
TypedValue BespokeArray::NvGetInt(const ArrayData* ad, int64_t key) {
return g_layout_funcs.fnNvGetInt[getLayoutByte(ad)](ad, key);
}
NO_PROFILING
TypedValue BespokeArray::NvGetStr(const ArrayData* ad, const StringData* key) {
return g_layout_funcs.fnNvGetStr[getLayoutByte(ad)](ad, key);
}
NO_PROFILING
TypedValue BespokeArray::NvGetIntThrow(const ArrayData* ad, int64_t key) {
return g_layout_funcs.fnNvGetIntThrow[getLayoutByte(ad)](ad, key);
}
NO_PROFILING
TypedValue BespokeArray::NvGetStrThrow(const ArrayData* ad, const StringData* key) {
return g_layout_funcs.fnNvGetStrThrow[getLayoutByte(ad)](ad, key);
}
TypedValue BespokeArray::GetPosKey(const ArrayData* ad, ssize_t pos) {
return g_layout_funcs.fnGetPosKey[getLayoutByte(ad)](ad, pos);
}
NO_PROFILING
TypedValue BespokeArray::GetPosVal(const ArrayData* ad, ssize_t pos) {
return g_layout_funcs.fnGetPosVal[getLayoutByte(ad)](ad, pos);
}
NO_PROFILING
bool BespokeArray::ExistsInt(const ArrayData* ad, int64_t key) {
return NvGetInt(ad, key).is_init();
}
NO_PROFILING
bool BespokeArray::ExistsStr(const ArrayData* ad, const StringData* key) {
return NvGetStr(ad, key).is_init();
}
// iteration
NO_PROFILING
ssize_t BespokeArray::IterBegin(const ArrayData* ad) {
return g_layout_funcs.fnIterBegin[getLayoutByte(ad)](ad);
}
NO_PROFILING
ssize_t BespokeArray::IterLast(const ArrayData* ad) {
return g_layout_funcs.fnIterLast[getLayoutByte(ad)](ad);
}
NO_PROFILING
ssize_t BespokeArray::IterEnd(const ArrayData* ad) {
return g_layout_funcs.fnIterEnd[getLayoutByte(ad)](ad);
}
NO_PROFILING
ssize_t BespokeArray::IterAdvance(const ArrayData* ad, ssize_t pos) {
return g_layout_funcs.fnIterAdvance[getLayoutByte(ad)](ad, pos);
}
NO_PROFILING
ssize_t BespokeArray::IterRewind(const ArrayData* ad, ssize_t pos) {
return g_layout_funcs.fnIterRewind[getLayoutByte(ad)](ad, pos);
}
// RW access
NO_PROFILING
arr_lval BespokeArray::LvalInt(ArrayData* ad, int64_t key) {
return g_layout_funcs.fnLvalInt[getLayoutByte(ad)](ad, key);
}
NO_PROFILING
arr_lval BespokeArray::LvalStr(ArrayData* ad, StringData* key) {
return g_layout_funcs.fnLvalStr[getLayoutByte(ad)](ad, key);
}
NO_PROFILING
tv_lval BespokeArray::ElemInt(
tv_lval lval, int64_t key, bool throwOnMissing) {
auto const ad = lval.val().parr;
return g_layout_funcs.fnElemInt[getLayoutByte(ad)](lval, key, throwOnMissing);
}
NO_PROFILING
tv_lval BespokeArray::ElemStr(
tv_lval lval, StringData* key, bool throwOnMissing) {
auto const ad = lval.val().parr;
return g_layout_funcs.fnElemStr[getLayoutByte(ad)](lval, key, throwOnMissing);
}
// insertion
NO_PROFILING
ArrayData* BespokeArray::SetIntMove(ArrayData* ad, int64_t key, TypedValue v) {
return g_layout_funcs.fnSetIntMove[getLayoutByte(ad)](ad, key, v);
}
NO_PROFILING
ArrayData* BespokeArray::SetStrMove(ArrayData* ad, StringData* key, TypedValue v) {
return g_layout_funcs.fnSetStrMove[getLayoutByte(ad)](ad, key, v);
}
// deletion
NO_PROFILING
ArrayData* BespokeArray::RemoveInt(ArrayData* ad, int64_t key) {
return g_layout_funcs.fnRemoveInt[getLayoutByte(ad)](ad, key);
}
NO_PROFILING
ArrayData* BespokeArray::RemoveStr(ArrayData* ad, const StringData* key) {
return g_layout_funcs.fnRemoveStr[getLayoutByte(ad)](ad, key);
}
// sorting
NO_PROFILING
ArrayData* BespokeArray::EscalateForSort(ArrayData* ad, SortFunction sf) {
if (!isSortFamily(sf) && ad->isVecType()) return ad->toDict(true);
assertx(!ad->empty());
return g_layout_funcs.fnPreSort[getLayoutByte(ad)](ad, sf);
}
NO_PROFILING
ArrayData* BespokeArray::PostSort(ArrayData* ad, ArrayData* vad) {
assertx(vad->isVanilla());
if (ad->toDataType() != vad->toDataType()) return vad;
assertx(vad->hasExactlyOneRef());
return g_layout_funcs.fnPostSort[getLayoutByte(ad)](ad, vad);
}
// high-level ops
NO_PROFILING
ArrayData* BespokeArray::AppendMove(ArrayData* ad, TypedValue v) {
return g_layout_funcs.fnAppendMove[getLayoutByte(ad)](ad, v);
}
NO_PROFILING
ArrayData* BespokeArray::Pop(ArrayData* ad, Variant& out) {
return g_layout_funcs.fnPop[getLayoutByte(ad)](ad, out);
}
void BespokeArray::OnSetEvalScalar(ArrayData*) {
always_assert(false);
}
// copies and conversions
ArrayData* BespokeArray::CopyStatic(const ArrayData*) {
always_assert(false);
}
NO_PROFILING
ArrayData* BespokeArray::SetLegacyArray(ArrayData* ad, bool copy, bool legacy) {
return g_layout_funcs.fnSetLegacyArray[getLayoutByte(ad)](ad, copy, legacy);
}
//////////////////////////////////////////////////////////////////////////////
}
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
c9a0b764b318c22ce06fae5e9eae6a93f2ed8c72 | 6f6b7e46ed58557b3a585c5e747e472ff2e94a16 | /arduino/main.ino | 2a9fe627daac5eed35a787786be39382a708dc8a | [] | no_license | Dan-Shields/RocketLeagueIRL | c849d65137d53dbf6c1f5b7a5d894c4a67eb724e | af9e8b543cb8b08c93688164788df2487ab52df8 | refs/heads/master | 2021-01-20T10:46:24.701818 | 2017-10-21T18:08:42 | 2018-01-16T13:40:29 | 85,079,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,001 | ino | const int In1 = 3;
const int In2 = 4;
const int In3 = 5;
const int In4 = 6;
const int enableRight = 10;
const int enableLeft = 9;
int turnSpeed = 255, globalSpeed = 0, move, L, R, F_B, enable, controlByte;
double speedRatio = 1;
bool connectionActive = false;
#define MAX_MILLIS_TO_WAIT 1000
unsigned long starttime;
void forwardLeft()
{
analogWrite(enableLeft, (int) (turnSpeed * speedRatio));
analogWrite(enableRight, globalSpeed);
digitalWrite (In1, LOW);
digitalWrite (In2, HIGH);
digitalWrite (In3, HIGH);
digitalWrite (In4, LOW);
}
void forwardRight()
{
analogWrite(enableLeft, globalSpeed);
analogWrite(enableRight, (int) (turnSpeed * speedRatio));
digitalWrite (In1, LOW);
digitalWrite (In2, HIGH);
digitalWrite (In3, HIGH);
digitalWrite (In4, LOW);
}
void backwardLeft()
{
analogWrite(enableLeft, globalSpeed);
analogWrite(enableRight, (int) (turnSpeed * speedRatio));
digitalWrite (In1, HIGH);
digitalWrite (In2, LOW);
digitalWrite (In3, LOW);
digitalWrite (In4, HIGH);
}
void backwardRight()
{
analogWrite(enableLeft, (int) (turnSpeed * speedRatio));
analogWrite(enableRight, globalSpeed);
digitalWrite (In1, HIGH);
digitalWrite (In2, LOW);
digitalWrite (In3, LOW);
digitalWrite (In4, HIGH);
}
void forward()
{
analogWrite(enableLeft, globalSpeed);
analogWrite(enableRight, globalSpeed);
digitalWrite (In1, LOW);
digitalWrite (In2, HIGH);
digitalWrite (In3, HIGH);
digitalWrite (In4, LOW);
}
void backward()
{
analogWrite(enableLeft, globalSpeed);
analogWrite(enableRight, globalSpeed);
digitalWrite (In1, HIGH);
digitalWrite (In2, LOW);
digitalWrite (In3, LOW);
digitalWrite (In4, HIGH);
}
void stationary()
{
digitalWrite (In1, LOW);
digitalWrite (In2, LOW);
digitalWrite (In3, LOW);
digitalWrite (In4, LOW);
}
void setup()
{
pinMode(In1, OUTPUT);
pinMode(In2, OUTPUT);
pinMode(In3, OUTPUT);
pinMode(In4, OUTPUT);
pinMode(enableRight, OUTPUT);
pinMode(enableLeft, OUTPUT);
Serial.begin(9600);
}
void loop(){
starttime = millis();
if (!connectionActive && Serial.available()) {
if (Serial.read() == 127) {
// acknowledge handshake...
connectionActive = true;
Serial.write(127);
} else {
// ...or flush
while(Serial.available()){Serial.read();}
}
} else if (connectionActive) {
while ((Serial.available()<3) && ((millis() - starttime) < MAX_MILLIS_TO_WAIT)) {} // wait for data/timeout
if(Serial.available() < 3)
{
// connection lost - request reconnect and stay put
Serial.write(63);
connectionActive = false;
while(Serial.available()){Serial.read();}
stationary();
}
else
{
// data was received
controlByte = Serial.read();
turnSpeed = Serial.read();
globalSpeed = Serial.read();
enable = bitRead(controlByte, 7);
move = bitRead(controlByte, 6);
F_B = bitRead(controlByte, 5);
L = bitRead(controlByte, 4);
R = bitRead(controlByte, 3);
if(move == 1) {
if(F_B == 1) {
if(L == 1) {
if(R == 1) {
stationary();
}
if(R == 0) {
forwardLeft();
}
}
if(L == 0) {
if(R == 1) {
forwardRight();
}
if(R == 0) {
forward();
}
}
}
if(F_B == 0) {
if(L == 1 && R == 1) {
backward();
}
else if(L == 0) {
if(R == 1) {
backwardRight();
}
if(R == 0) {
backward();
}
}
else {
backwardLeft();
}
}
}
else {
stationary();
}
}
}
} | [
"d.shieldsuk@gmail.com"
] | d.shieldsuk@gmail.com |
ce4ee9ab9552654fc3e6f217a2c7457dc215b6c0 | 9ff8e317e7293033e3983c5e6660adc4eff75762 | /Gamecore/configuration/SGF_SysVarsyyy.h | 48c4f827616c0a94acc229f93dbdf6c9ab5082bb | [] | no_license | rasputtim/SGF | b26fd29487b93c8e67c73f866635830796970116 | d8af92216bf4e86aeb452fda841c73932de09b65 | refs/heads/master | 2020-03-28T21:55:14.668643 | 2018-11-03T21:15:32 | 2018-11-03T21:15:32 | 147,579,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,046 | h | /*
SGF - Salvat Game Fabric (https://sourceforge.net/projects/sgfabric/)
Copyright (C) 2010-2011 Salvatore Giannotta Filho <a_materasu@hotmail.com>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __SGF_SYS_SYSVAR_H__
#define __SGF_SYS_SYSVAR_H__
#include "../SGF_Config.h"
#include "SGF_ConfigSystem.h"
namespace SGF {
} //end SGF
#endif /* !__SGF_SYS_SYSVAR_H__ */
| [
"rasputtim@hotmail.com"
] | rasputtim@hotmail.com |
ae0692c8f6e503f1c3c2cc51d171e14f78695aec | 393125abdafa8288e155780b3101263bfcd2e0c0 | /class and object 1.cpp | b790d9e8b85aa42884895417a442b82fbb08d209 | [] | no_license | SraboniIbnatAddri/Basic-problem-solve-in-cpp | 6aa9490230f267f7e9fe798d2d94966fb371043b | be96afdca475a173cd39478337baa9f018f28fb5 | refs/heads/master | 2021-05-25T16:57:34.296694 | 2020-04-15T06:47:57 | 2020-04-15T06:47:57 | 253,830,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | cpp | #include<iostream>
#include<conio.h>
using namespace std;
class box
{
public:
double height;
double length;
double breadth;
};
int main()
{
box box1;
box box2;
double volume = 0.0;
box1.height=5.0;
box1.length=6.0;
box1.breadth=7.0;
box2.height=10.0;
box2.length=12.0;
box2.breadth=13.0;
volume= box1.height*box1.length*box1.breadth;
cout<<"Volume of box1 = "<<volume<<endl;
volume= box2.height*box2.length*box2.breadth;
cout<<"Volume of box1 = "<<volume<<endl;
return 0;
}
| [
"SraboniibnatAddri.com"
] | SraboniibnatAddri.com |
cee153ef9cea8c054ed516017408437d483a8e3b | fde28d5498de061393d6785e90ed01c436b4ef1b | /Leetcode/155MinStack/main.cpp | 2f8ff0f5b5616cd0713c2f02a6f772e1a31b42e4 | [] | no_license | yuxiandeng/CodingPractice | bf1279304f64cf35c10d1df44ecf70a9432261f6 | c07d5b1f9c604c4b8c803f510241db64ba014e01 | refs/heads/master | 2021-09-21T04:39:42.134144 | 2018-08-20T16:26:25 | 2018-08-20T16:26:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,581 | cpp | #include <algorithm>
struct ListNode
{
ListNode* next;
ListNode* last;
ListNode* pointer;
int value;
ListNode(int val, ListNode* iNext, ListNode* iLast, ListNode* iPoiner)
{
value = val;
next = iNext;
last = iLast;
pointer = iPoiner;
}
};
class MinStack
{
public:
MinStack()
{
headList = new ListNode(0, NULL, NULL, NULL);
headStack = new ListNode(0, NULL, NULL, NULL);
tailStack = headStack;
}
void push(int x)
{
ListNode* newListNode = new ListNode(x, NULL, NULL, NULL);
ListNode* newStackNode = new ListNode(x, NULL, NULL, NULL);
newStackNode->pointer = newListNode;
newListNode->pointer = newStackNode;
// link stack node
newStackNode->last = tailStack;
tailStack->next = newStackNode;
tailStack = newStackNode;
// link list node
if (!headList->next)
{
headList->next = newListNode;
newListNode->last = headList;
}
else if (x < headList->next->value)
{
newListNode->next = headList->next;
headList->next = newListNode;
newListNode->last = headList;
}
else
{
delete newListNode;
newStackNode->pointer = NULL;
}
}
void pop()
{
ListNode* node = tailStack;
if (node->pointer)
{
ListNode* pointer = node->pointer;
pointer->last->next = pointer->next;
delete pointer;
}
tailStack = node->last;
tailStack->next = NULL;
delete node;
}
int top()
{
if (tailStack)
return tailStack->value;
else
return 0;
}
int getMin()
{
if (headList->next)
return headList->next->value;
}
private:
ListNode* headList;
ListNode* headStack, *tailStack;
}; | [
"u1166596@utah.edu"
] | u1166596@utah.edu |
996c0b9b45916f6eb2c7e0174f388c89a929fef1 | d0ae9c70e8dc2eaceef29a6e0f0c1691dce3cf7d | /calculating area of a circle Project/Area of a circle.cpp | b5301b55f4b26c2a27400c4967daee62e57d8574 | [] | no_license | DominicSykes/CircleArea | a6d21aa85ae11bb05181d16c632708c7cd8d2797 | 4caed76a0fcb6a75ca527e5ab626b772a1355d8a | refs/heads/master | 2022-12-10T04:02:20.753806 | 2020-09-21T02:15:30 | 2020-09-21T02:15:30 | 297,205,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | cpp | #include <iostream>
int main() {
std::cout << "How do you calculate the area of a circle \n";
std::cout << " Well you would Pi r^(2)";
return 0;
} // calculating the area of a circle | [
"noreply@github.com"
] | noreply@github.com |
5246a4fa5f45ebbbaf73e5dfcbd766ceae9d297c | 819875a388d7caf6795941db8104f4bf72677b90 | /content/browser/gpu/.svn/text-base/gpu_process_host.cc.svn-base | 66f152b6f88477bb8fb2a86e324b005280444892 | [
"BSD-3-Clause"
] | permissive | gx1997/chrome-loongson | 07b763eb1d0724bf0d2e0a3c2b0eb274e9a2fb4c | 1cb7e00e627422577e8b7085c2d2892eda8590ae | refs/heads/master | 2020-04-28T02:04:13.872019 | 2012-08-16T10:09:25 | 2012-08-16T10:09:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,569 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/gpu/gpu_process_host.h"
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram.h"
#include "base/process_util.h"
#include "base/string_piece.h"
#include "base/threading/thread.h"
#include "content/browser/browser_child_process_host_impl.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/gpu/gpu_process_host_ui_shim.h"
#include "content/browser/gpu/gpu_surface_tracker.h"
#include "content/browser/renderer_host/render_widget_helper.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/child_process_host_impl.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/common/view_messages.h"
#include "content/gpu/gpu_child_thread.h"
#include "content/gpu/gpu_process.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.h"
#include "gpu/command_buffer/service/gpu_switches.h"
#include "ipc/ipc_channel_handle.h"
#include "ipc/ipc_switches.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_switches.h"
#if defined(TOOLKIT_GTK)
#include "ui/gfx/gtk_native_view_id_manager.h"
#endif
#if defined(OS_WIN) && !defined(USE_AURA)
#include "ui/gfx/surface/accelerated_surface_win.h"
#endif
using content::BrowserThread;
using content::ChildProcessHost;
bool GpuProcessHost::gpu_enabled_ = true;
bool GpuProcessHost::hardware_gpu_enabled_ = true;
namespace {
enum GPUProcessLifetimeEvent {
LAUNCHED,
DIED_FIRST_TIME,
DIED_SECOND_TIME,
DIED_THIRD_TIME,
DIED_FOURTH_TIME,
GPU_PROCESS_LIFETIME_EVENT_MAX
};
// Indexed by GpuProcessKind. There is one of each kind maximum. This array may
// only be accessed from the IO thread.
static GpuProcessHost *g_gpu_process_hosts[
GpuProcessHost::GPU_PROCESS_KIND_COUNT];
// Number of times the gpu process has crashed in the current browser session.
static int g_gpu_crash_count = 0;
static int g_gpu_software_crash_count = 0;
// Maximum number of times the gpu process is allowed to crash in a session.
// Once this limit is reached, any request to launch the gpu process will fail.
static const int kGpuMaxCrashCount = 3;
int g_last_host_id = 0;
#if defined(TOOLKIT_GTK)
void ReleasePermanentXIDDispatcher(gfx::PluginWindowHandle surface) {
GtkNativeViewManager* manager = GtkNativeViewManager::GetInstance();
manager->ReleasePermanentXID(surface);
}
#endif
void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind,
content::CauseForGpuLaunch cause,
IPC::Message* message) {
GpuProcessHost* host = GpuProcessHost::Get(kind, cause);
if (host) {
host->Send(message);
} else {
delete message;
}
}
void AcceleratedSurfaceBuffersSwappedCompleted(int host_id,
int route_id,
bool alive) {
if (BrowserThread::CurrentlyOn(BrowserThread::IO)) {
GpuProcessHost* host = GpuProcessHost::FromID(host_id);
if (host) {
if (alive)
host->Send(new AcceleratedSurfaceMsg_BuffersSwappedACK(route_id));
else {
host->ForceShutdown();
}
}
} else {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id,
route_id,
alive));
}
}
} // anonymous namespace
#if defined(TOOLKIT_GTK)
// Used to put a lock on surfaces so that the window to which the GPU
// process is drawing to doesn't disappear while it is drawing when
// a WebContents is closed.
class GpuProcessHost::SurfaceRef {
public:
explicit SurfaceRef(gfx::PluginWindowHandle surface);
~SurfaceRef();
private:
gfx::PluginWindowHandle surface_;
};
GpuProcessHost::SurfaceRef::SurfaceRef(gfx::PluginWindowHandle surface)
: surface_(surface) {
GtkNativeViewManager* manager = GtkNativeViewManager::GetInstance();
if (!manager->AddRefPermanentXID(surface_)) {
LOG(ERROR) << "Surface " << surface << " cannot be referenced.";
}
}
GpuProcessHost::SurfaceRef::~SurfaceRef() {
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
base::Bind(&ReleasePermanentXIDDispatcher, surface_));
}
#endif // defined(TOOLKIT_GTK)
// This class creates a GPU thread (instead of a GPU process), when running
// with --in-process-gpu or --single-process.
class GpuMainThread : public base::Thread {
public:
explicit GpuMainThread(const std::string& channel_id)
: base::Thread("Chrome_InProcGpuThread"),
channel_id_(channel_id),
gpu_process_(NULL),
child_thread_(NULL) {
}
~GpuMainThread() {
Stop();
}
protected:
virtual void Init() {
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) {
child_thread_ = new GpuChildThread(channel_id_);
} else {
gpu_process_ = new GpuProcess();
// The process object takes ownership of the thread object, so do not
// save and delete the pointer.
gpu_process_->set_main_thread(new GpuChildThread(channel_id_));
}
}
virtual void CleanUp() {
delete gpu_process_;
if (child_thread_)
delete child_thread_;
}
private:
std::string channel_id_;
// Deleted in CleanUp() on the gpu thread, so don't use smart pointers.
GpuProcess* gpu_process_;
GpuChildThread* child_thread_;
DISALLOW_COPY_AND_ASSIGN(GpuMainThread);
};
// static
bool GpuProcessHost::HostIsValid(GpuProcessHost* host) {
if (!host)
return false;
// Check if the GPU process has died and the host is about to be destroyed.
if (host->process_->disconnect_was_alive())
return false;
// The Gpu process is invalid if it's not using software, the card is
// blacklisted, and we can kill it and start over.
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) ||
CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU) ||
host->software_rendering() ||
!GpuDataManagerImpl::GetInstance()->ShouldUseSoftwareRendering()) {
return true;
}
host->ForceShutdown();
return false;
}
// static
GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind,
content::CauseForGpuLaunch cause) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Don't grant further access to GPU if it is not allowed.
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
if (gpu_data_manager != NULL && !gpu_data_manager->GpuAccessAllowed())
return NULL;
if (g_gpu_process_hosts[kind] && HostIsValid(g_gpu_process_hosts[kind]))
return g_gpu_process_hosts[kind];
if (cause == content::CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH)
return NULL;
int host_id;
host_id = ++g_last_host_id;
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
cause,
content::CAUSE_FOR_GPU_LAUNCH_MAX_ENUM);
GpuProcessHost* host = new GpuProcessHost(host_id, kind);
if (host->Init())
return host;
delete host;
return NULL;
}
// static
void GpuProcessHost::SendOnIO(GpuProcessKind kind,
content::CauseForGpuLaunch cause,
IPC::Message* message) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(
&SendGpuProcessMessage, kind, cause, message));
}
// static
GpuProcessHost* GpuProcessHost::FromID(int host_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
for (int i = 0; i < GPU_PROCESS_KIND_COUNT; ++i) {
GpuProcessHost* host = g_gpu_process_hosts[i];
if (host && host->host_id_ == host_id && HostIsValid(host))
return host;
}
return NULL;
}
GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
: host_id_(host_id),
in_process_(false),
software_rendering_(false),
kind_(kind),
process_launched_(false) {
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) ||
CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU))
in_process_ = true;
// If the 'single GPU process' policy ever changes, we still want to maintain
// it for 'gpu thread' mode and only create one instance of host and thread.
DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL);
g_gpu_process_hosts[kind] = this;
// Post a task to create the corresponding GpuProcessHostUIShim. The
// GpuProcessHostUIShim will be destroyed if either the browser exits,
// in which case it calls GpuProcessHostUIShim::DestroyAll, or the
// GpuProcessHost is destroyed, which happens when the corresponding GPU
// process terminates or fails to launch.
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id));
process_.reset(
new BrowserChildProcessHostImpl(content::PROCESS_TYPE_GPU, this));
}
GpuProcessHost::~GpuProcessHost() {
DCHECK(CalledOnValidThread());
SendOutstandingReplies();
// Ending only acts as a failure if the GPU process was actually started and
// was intended for actual rendering (and not just checking caps or other
// options).
if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
if (software_rendering_) {
if (++g_gpu_software_crash_count >= kGpuMaxCrashCount) {
// The software renderer is too unstable to use. Disable it for current
// session.
gpu_enabled_ = false;
}
} else {
if (++g_gpu_crash_count >= kGpuMaxCrashCount) {
#if !defined(OS_CHROMEOS)
// The gpu process is too unstable to use. Disable it for current
// session.
hardware_gpu_enabled_ = false;
GpuDataManagerImpl::GetInstance()->BlacklistCard();
#endif
}
}
}
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
DIED_FIRST_TIME + g_gpu_crash_count,
GPU_PROCESS_LIFETIME_EVENT_MAX);
int exit_code;
base::TerminationStatus status = process_->GetTerminationStatus(&exit_code);
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
status,
base::TERMINATION_STATUS_MAX_ENUM);
if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
exit_code,
content::RESULT_CODE_LAST_CODE);
}
// In case we never started, clean up.
while (!queued_messages_.empty()) {
delete queued_messages_.front();
queued_messages_.pop();
}
// This is only called on the IO thread so no race against the constructor
// for another GpuProcessHost.
if (g_gpu_process_hosts[kind_] == this)
g_gpu_process_hosts[kind_] = NULL;
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
base::Bind(&GpuProcessHostUIShim::Destroy, host_id_));
}
bool GpuProcessHost::Init() {
init_start_time_ = base::TimeTicks::Now();
std::string channel_id = process_->GetHost()->CreateChannel();
if (channel_id.empty())
return false;
if (in_process_) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisableGpuWatchdog);
in_process_gpu_thread_.reset(new GpuMainThread(channel_id));
base::Thread::Options options;
#if defined(OS_WIN)
// On Windows the GPU thread needs to pump the compositor child window's
// message loop. TODO(apatrick): make this an IO thread if / when we get rid
// of this child window. Unfortunately it might always be necessary for
// Windows XP because we cannot share the backing store textures between
// processes.
options.message_loop_type = MessageLoop::TYPE_UI;
#else
options.message_loop_type = MessageLoop::TYPE_IO;
#endif
in_process_gpu_thread_->StartWithOptions(options);
OnProcessLaunched(); // Fake a callback that the process is ready.
} else if (!LaunchGpuProcess(channel_id)) {
return false;
}
return Send(new GpuMsg_Initialize());
}
void GpuProcessHost::RouteOnUIThread(const IPC::Message& message) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&RouteToGpuProcessHostUIShimTask, host_id_, message));
}
bool GpuProcessHost::Send(IPC::Message* msg) {
DCHECK(CalledOnValidThread());
if (process_->GetHost()->IsChannelOpening()) {
queued_messages_.push(msg);
return true;
}
return process_->Send(msg);
}
bool GpuProcessHost::OnMessageReceived(const IPC::Message& message) {
DCHECK(CalledOnValidThread());
IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message)
IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished)
IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated, OnCommandBufferCreated)
IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer, OnDestroyCommandBuffer)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
OnAcceleratedSurfaceBuffersSwapped)
#endif
#if defined(OS_WIN) && !defined(USE_AURA)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
OnAcceleratedSurfaceBuffersSwapped)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfacePostSubBuffer,
OnAcceleratedSurfacePostSubBuffer)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceSuspend,
OnAcceleratedSurfaceSuspend)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceRelease,
OnAcceleratedSurfaceRelease)
#endif
IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message))
IPC_END_MESSAGE_MAP()
return true;
}
void GpuProcessHost::OnChannelConnected(int32 peer_pid) {
while (!queued_messages_.empty()) {
Send(queued_messages_.front());
queued_messages_.pop();
}
}
void GpuProcessHost::EstablishGpuChannel(
int client_id,
bool share_context,
const EstablishChannelCallback& callback) {
DCHECK(CalledOnValidThread());
TRACE_EVENT0("gpu", "GpuProcessHostUIShim::EstablishGpuChannel");
// If GPU features are already blacklisted, no need to establish the channel.
if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed()) {
EstablishChannelError(
callback, IPC::ChannelHandle(),
base::kNullProcessHandle, content::GPUInfo());
return;
}
if (Send(new GpuMsg_EstablishChannel(client_id, share_context))) {
channel_requests_.push(callback);
} else {
EstablishChannelError(
callback, IPC::ChannelHandle(),
base::kNullProcessHandle, content::GPUInfo());
}
}
void GpuProcessHost::CreateViewCommandBuffer(
const gfx::GLSurfaceHandle& compositing_surface,
int surface_id,
int client_id,
const GPUCreateCommandBufferConfig& init_params,
const CreateCommandBufferCallback& callback) {
DCHECK(CalledOnValidThread());
#if defined(TOOLKIT_GTK)
// There should only be one such command buffer (for the compositor). In
// practice, if the GPU process lost a context, GraphicsContext3D with
// associated command buffer and view surface will not be gone until new
// one is in place and all layers are reattached.
linked_ptr<SurfaceRef> surface_ref;
SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
if (it != surface_refs_.end())
surface_ref = (*it).second;
else
surface_ref.reset(new SurfaceRef(compositing_surface.handle));
#endif // defined(TOOLKIT_GTK)
if (!compositing_surface.is_null() &&
Send(new GpuMsg_CreateViewCommandBuffer(
compositing_surface, surface_id, client_id, init_params))) {
create_command_buffer_requests_.push(callback);
#if defined(TOOLKIT_GTK)
surface_refs_.insert(std::make_pair(surface_id, surface_ref));
#endif
} else {
CreateCommandBufferError(callback, MSG_ROUTING_NONE);
}
}
void GpuProcessHost::OnChannelEstablished(
const IPC::ChannelHandle& channel_handle) {
EstablishChannelCallback callback = channel_requests_.front();
channel_requests_.pop();
// Currently if any of the GPU features are blacklisted, we don't establish a
// GPU channel.
if (!channel_handle.name.empty() &&
!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed()) {
Send(new GpuMsg_CloseChannel(channel_handle));
EstablishChannelError(callback,
IPC::ChannelHandle(),
base::kNullProcessHandle,
content::GPUInfo());
RouteOnUIThread(GpuHostMsg_OnLogMessage(
logging::LOG_WARNING,
"WARNING",
"Hardware acceleration is unavailable."));
return;
}
callback.Run(channel_handle,
GpuDataManagerImpl::GetInstance()->GetGPUInfo());
}
void GpuProcessHost::OnCommandBufferCreated(const int32 route_id) {
if (!create_command_buffer_requests_.empty()) {
CreateCommandBufferCallback callback =
create_command_buffer_requests_.front();
create_command_buffer_requests_.pop();
if (route_id == MSG_ROUTING_NONE)
CreateCommandBufferError(callback, route_id);
else
callback.Run(route_id);
}
}
void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id) {
#if defined(TOOLKIT_GTK)
SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
if (it != surface_refs_.end())
surface_refs_.erase(it);
#endif // defined(TOOLKIT_GTK)
}
#if defined(OS_MACOSX)
void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
// Compositor window is always gfx::kNullPluginWindow.
// TODO(jbates) http://crbug.com/105344 This will be removed when there are no
// plugin windows.
if (handle != gfx::kNullPluginWindow) {
RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
return;
}
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_, params.route_id, true));
int render_process_id = 0;
int render_widget_id = 0;
if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface(
params.surface_id, &render_process_id, &render_widget_id)) {
return;
}
RenderWidgetHelper* helper =
RenderWidgetHelper::FromProcessHostID(render_process_id);
if (!helper)
return;
// Pass the SwapBuffers on to the RenderWidgetHelper to wake up the UI thread
// if the browser is waiting for a new frame. Otherwise the RenderWidgetHelper
// will forward to the RenderWidgetHostView via RenderProcessHostImpl and
// RenderWidgetHostImpl.
scoped_completion_runner.Release();
helper->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped(
render_widget_id,
params.surface_id,
params.surface_handle,
params.route_id,
host_id_));
}
#endif // OS_MACOSX
#if defined(OS_WIN) && !defined(USE_AURA)
void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_,
params.route_id,
true));
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
if (!handle)
return;
scoped_refptr<AcceleratedPresenter> presenter(
AcceleratedPresenter::GetForWindow(handle));
if (!presenter)
return;
scoped_completion_runner.Release();
presenter->AsyncPresentAndAcknowledge(
params.size,
params.surface_handle,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_,
params.route_id));
}
void GpuProcessHost::OnAcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHost::OnAcceleratedSurfacePostSubBuffer");
NOTIMPLEMENTED();
}
void GpuProcessHost::OnAcceleratedSurfaceSuspend(int32 surface_id) {
TRACE_EVENT0("renderer",
"GpuProcessHost::OnAcceleratedSurfaceSuspend");
gfx::GLSurfaceHandle handle = GpuSurfaceTracker::Get()->GetSurfaceHandle(
surface_id);
if (!handle.handle)
return;
scoped_refptr<AcceleratedPresenter> presenter(
AcceleratedPresenter::GetForWindow(handle.handle));
if (!presenter)
return;
presenter->Suspend();
}
void GpuProcessHost::OnAcceleratedSurfaceRelease(
const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHost::OnAcceleratedSurfaceRelease");
gfx::GLSurfaceHandle handle = GpuSurfaceTracker::Get()->GetSurfaceHandle(
params.surface_id);
if (!handle.handle)
return;
scoped_refptr<AcceleratedPresenter> presenter(
AcceleratedPresenter::GetForWindow(handle.handle));
if (!presenter)
return;
presenter->ReleaseSurface();
}
#endif // OS_WIN && !USE_AURA
void GpuProcessHost::OnProcessLaunched() {
UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
base::TimeTicks::Now() - init_start_time_);
}
void GpuProcessHost::OnProcessCrashed(int exit_code) {
SendOutstandingReplies();
}
bool GpuProcessHost::software_rendering() {
return software_rendering_;
}
GpuProcessHost::GpuProcessKind GpuProcessHost::kind() {
return kind_;
}
void GpuProcessHost::ForceShutdown() {
// This is only called on the IO thread so no race against the constructor
// for another GpuProcessHost.
if (g_gpu_process_hosts[kind_] == this)
g_gpu_process_hosts[kind_] = NULL;
process_->ForceShutdown();
}
bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) {
if (!(gpu_enabled_ &&
GpuDataManagerImpl::GetInstance()->ShouldUseSoftwareRendering()) &&
!hardware_gpu_enabled_) {
SendOutstandingReplies();
return false;
}
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
CommandLine::StringType gpu_launcher =
browser_command_line.GetSwitchValueNative(switches::kGpuLauncher);
#if defined(OS_LINUX)
int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
ChildProcessHost::CHILD_NORMAL;
#else
int child_flags = ChildProcessHost::CHILD_NORMAL;
#endif
FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
if (exe_path.empty())
return false;
CommandLine* cmd_line = new CommandLine(exe_path);
cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED)
cmd_line->AppendSwitch(switches::kDisableGpuSandbox);
// Propagate relevant command line switches.
static const char* const kSwitchNames[] = {
switches::kDisableBreakpad,
switches::kDisableGLMultisampling,
switches::kDisableGpuDriverBugWorkarounds,
switches::kDisableGpuSandbox,
switches::kReduceGpuSandbox,
switches::kDisableSeccompFilterSandbox,
switches::kDisableGpuVsync,
switches::kDisableGpuWatchdog,
switches::kDisableImageTransportSurface,
switches::kDisableLogging,
switches::kEnableGPUServiceLogging,
switches::kEnableLogging,
#if defined(OS_MACOSX)
switches::kEnableSandboxLogging,
#endif
switches::kGpuNoContextLost,
switches::kGpuStartupDialog,
switches::kLoggingLevel,
switches::kNoSandbox,
switches::kTestGLLib,
switches::kTraceStartup,
switches::kV,
switches::kVModule,
};
cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
arraysize(kSwitchNames));
cmd_line->CopySwitchesFrom(
browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches);
content::GetContentClient()->browser()->AppendExtraCommandLineSwitches(
cmd_line, process_->GetData().id);
GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line);
if (cmd_line->HasSwitch(switches::kUseGL))
software_rendering_ =
(cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader");
UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessSoftwareRendering", software_rendering_);
// If specified, prepend a launcher program to the command line.
if (!gpu_launcher.empty())
cmd_line->PrependWrapper(gpu_launcher);
process_->Launch(
#if defined(OS_WIN)
FilePath(),
#elif defined(OS_POSIX)
false, // Never use the zygote (GPU plugin can't be sandboxed).
base::EnvironmentVector(),
#endif
cmd_line);
process_launched_ = true;
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX);
return true;
}
void GpuProcessHost::SendOutstandingReplies() {
// First send empty channel handles for all EstablishChannel requests.
while (!channel_requests_.empty()) {
EstablishChannelCallback callback = channel_requests_.front();
channel_requests_.pop();
EstablishChannelError(callback,
IPC::ChannelHandle(),
base::kNullProcessHandle,
content::GPUInfo());
}
}
void GpuProcessHost::EstablishChannelError(
const EstablishChannelCallback& callback,
const IPC::ChannelHandle& channel_handle,
base::ProcessHandle renderer_process_for_gpu,
const content::GPUInfo& gpu_info) {
callback.Run(channel_handle, gpu_info);
}
void GpuProcessHost::CreateCommandBufferError(
const CreateCommandBufferCallback& callback, int32 route_id) {
callback.Run(route_id);
}
| [
"loongson@Loong.(none)"
] | loongson@Loong.(none) | |
44e2098710dbfa9a862ede5b5b7137995c82819e | 493ebc48f2458b7820e73dc745359c517b8b4a32 | /src/undirected_graph.cpp | 4dcb36c4d9f463a699d9a7c31b03d8be36897dfc | [] | no_license | adiraman/depth-first-search | 9727aeed5e1a869b9896e016a10b5df11b22a38a | 475a6d44ba9aeb03eabf9421e5f78bdadd21e6cd | refs/heads/master | 2020-03-22T19:37:20.331827 | 2018-06-27T11:12:29 | 2018-06-27T11:12:29 | 140,540,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,676 | cpp | #include "../include/undirected_graph.h"
undirected_graph::undirected_graph(int vertices)
{
for (int i = 0; i < vertices; ++i) {
m_adjList[i] = std::set<int>();
}
}
void undirected_graph::addVertex(int vertex)
{
// If the list is empty no need to check for the vertex, simply
// add it to the list.
if (m_adjList.empty()) {
m_adjList.emplace(vertex, std::set<int>());
return;
}
// check to see if the vertex is already in the adjacency list.
// If not, add it to the list.
if (m_adjList.find(vertex) == m_adjList.end()) {
m_adjList.emplace(vertex, std::set<int>());
}
return;
}
void undirected_graph::removeVertex(int vertex)
{
// first delete the vertex
m_adjList.erase(vertex);
// remove all entries connected to the removed vertex
for (auto i : m_adjList) {
i.second.erase(vertex);
}
return;
}
void undirected_graph::addEdge(int source, int dest)
{
// Always have the source to be less than the destination for
// clarity of implementation
int start = source < dest ? source : dest;
int end = source < dest ? dest : source;
// check if both the vertices exist in the graph
// this is already done in the addVertex call
addVertex(start);
addVertex(end);
// create connections between the source and destination
// vertices
m_adjList[start].emplace(end);
m_adjList[end].emplace(start);
return;
}
void undirected_graph::removeEdge(int source, int dest)
{
// Note: each edge is represented only once in the adjacency list
// The representation is such that the source vertex always has
// a lower value than the destination vertex. Thus use the min of
// provided source and dest to remove an edge.
int start = source < dest ? source : dest;
int end = source < dest ? dest : source;
// remove the connections between source and destination
if (m_adjList.find(start) != m_adjList.end()) {
m_adjList[start].erase(end);
m_adjList[end].erase(start);
}
return;
}
int undirected_graph::countVertices()
{
return m_adjList.size();
}
int undirected_graph::countEdges()
{
// iterate through the map and sum up the set sizes.
int edges = 0;
for (auto i : m_adjList) {
edges += i.second.size();
}
return edges/2;
}
bool undirected_graph::writeDot(std::string filename)
{
std::ofstream file;
file.open(filename, std::ios::out);
if (file.is_open()) {
file << "strict graph {" << std::endl;
for (auto i : m_adjList) {
for (auto j : i.second) {
file << " " << i.first << " -- " << j << ";" << std::endl;
}
}
file << "}" << std::endl;
file.close();
return true;
}
return false;
}
std::vector<std::pair<int, int>> undirected_graph::getEdges() const
{
std::vector<std::pair<int, int>> edges;
for (auto it : m_adjList) {
for (auto di : it.second) {
edges.push_back(std::make_pair(it.first, di));
}
}
return edges;
}
std::vector<int> undirected_graph::getVertices() const
{
std::vector<int> vertices;
for (auto it : m_adjList) {
vertices.push_back(it.first);
}
return vertices;
}
std::map<int, std::set<int>> undirected_graph::getAdjacencyList() const
{
return m_adjList;
}
std::ostream& operator<<(std::ostream& oss, const undirected_graph& graph)
{
for (auto it : graph.m_adjList) {
oss << it.first << " :: ";
for (auto di : it.second) {
oss << " => " << di;
}
oss << std::endl;
}
return oss;
}
| [
"raman.aditya@mavs.uta.edu"
] | raman.aditya@mavs.uta.edu |
4e6ffa338469d3fab1b9f79aed306f6dd37795d3 | a0fd5cb6a3499432456a404d6faf148702c79609 | /RegArchLib/Headers/cAbstResiduals.h | 2d6a80609edf2746496ae4bcd54ef813e636d02e | [] | no_license | raquya/RegArch | 5ab2f76ac464b7e51e9a900dfe703856d48c067d | 8cf1b762f1ac8770f3a9f3fb68dfe78404865059 | refs/heads/master | 2021-01-13T04:47:21.066811 | 2017-01-12T17:17:10 | 2017-01-12T17:17:10 | 78,768,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,579 | h | #pragma once
#ifndef _CABSTRESIDUALS_H_
#define _CABSTRESIDUALS_H_
/*!
\file cAbstResiduals.h
\brief Definition of the abstract class to implement a distribution for residuals
\author Jean-Baptiste DURAND, Ollivier TARAMASCO
\date dec-18-2006 - last change feb-18-2011
*/
#include "RegArchDef.h"
#include <gsl/gsl_randist.h>
#include <ctime>
#include <cmath>
#include "cRegArchValue.h"
#include "cRegArchGradient.h"
namespace RegArchLib {
/*!
* \class cAbstResiduals
* \brief Abstract class to implement a conditional distribution model
*/
class _DLLEXPORT_ cAbstResiduals {
private:
eDistrTypeEnum mvDistr; ///< Code for distribution type
protected:
gsl_rng* mtR; ///< random generator
public:
cDVector mDistrParameter; ///< Parameters of the distribution (if any)
public:
cAbstResiduals(eDistrTypeEnum theDistr, cDVector* theDistrParam = NULL, bool theSimulFlag = true); ///< A simple constructor
virtual ~cAbstResiduals(); ///< A simple destructor
virtual cAbstResiduals* PtrCopy() const = 0; /// < Return a copy of *this
void Delete(void); ///< Delete
eDistrTypeEnum GetDistrType(void) const; ///< Return the distribution type
void SetSimul(void); ///< Change for simulation
double Get(uint theIndex = 0);
void Set(double theValue, uint theIndex = 0);
virtual void Print(ostream& theOut = cout) const = 0; ///< Print the distribution type
friend ostream& operator<<(ostream& theOut, const cAbstResiduals& theAbstResisuals); ///< Print the distribution type
virtual void Generate(uint theNSample, cDVector& theYt) const = 0; ///< Draw a sample from residual distribution
virtual double LogDensity(double theX) const = 0; ///< log density function
/** Return the number of parameters in distribution */
virtual uint GetNParam(void) const = 0;
/** Compute the derivative of log density with respect to the random variable (theGradData[0]) \e and the gradient
of log density with respect to the model parameters (other components in theGradData) */
virtual void ComputeGrad(uint theDate, const cRegArchValue& theData, cRegArchGradient& theGradData) const = 0;
virtual void RegArchParamToVector(cDVector& theDestVect, uint theIndex) const = 0;
virtual void VectorToRegArchParam(const cDVector& theSrcVect, uint theIndex = 0) = 0;
};
}
#endif //_CABSTRESIDUALS_H_
| [
"anas.raquy@ensimag.grenoble-inp.fr"
] | anas.raquy@ensimag.grenoble-inp.fr |
89c50911ba8264428fa95ecbb378f87cd49d5a07 | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /ash/magnifier/docked_magnifier_controller_impl.cc | 8ecec7d78faba1edabd0e492fc621000ac274b60 | [
"BSD-3-Clause"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 29,219 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/magnifier/docked_magnifier_controller_impl.h"
#include <algorithm>
#include "ash/accessibility/accessibility_controller_impl.h"
#include "ash/host/ash_window_tree_host.h"
#include "ash/magnifier/magnifier_utils.h"
#include "ash/public/cpp/ash_pref_names.h"
#include "ash/public/cpp/shell_window_ids.h"
#include "ash/root_window_controller.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shell.h"
#include "ash/wm/overview/overview_controller.h"
#include "ash/wm/splitview/split_view_controller.h"
#include "ash/wm/work_area_insets.h"
#include "base/bind.h"
#include "base/numerics/ranges.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/ime/ime_bridge.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/display/screen.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/coordinate_conversion.h"
namespace ash {
namespace {
constexpr float kDefaultMagnifierScale = 4.0f;
constexpr float kMinMagnifierScale = 1.0f;
constexpr float kMaxMagnifierScale = 20.0f;
// The factor by which the offset of scroll events are scaled.
constexpr float kScrollScaleFactor = 0.0125f;
constexpr char kDockedMagnifierViewportWindowName[] =
"DockedMagnifierViewportWindow";
// Returns the current cursor location in screen coordinates.
inline gfx::Point GetCursorScreenPoint() {
return display::Screen::GetScreen()->GetCursorScreenPoint();
}
// Updates the workarea of the display associated with |window| such that the
// given magnifier viewport |height| is allocated at the top of the screen.
void SetViewportHeightInWorkArea(aura::Window* window, int height) {
DCHECK(window);
WorkAreaInsets::ForWindow(window->GetRootWindow())
->SetDockedMagnifierHeight(height);
}
// Gets the bounds of the Docked Magnifier viewport widget when placed in the
// display whose root window is |root|. The bounds returned correspond to the
// top quarter portion of the screen.
gfx::Rect GetViewportWidgetBoundsInRoot(aura::Window* root) {
DCHECK(root);
DCHECK(root->IsRootWindow());
auto root_bounds = root->GetBoundsInRootWindow();
root_bounds.set_height(root_bounds.height() /
DockedMagnifierControllerImpl::kScreenHeightDivisor);
return root_bounds;
}
// Returns the separator layer bounds from the given |viewport_bounds|. The
// separator layer is to be placed right below the viewport.
inline gfx::Rect SeparatorBoundsFromViewportBounds(
const gfx::Rect& viewport_bounds) {
return gfx::Rect(viewport_bounds.x(), viewport_bounds.bottom(),
viewport_bounds.width(),
DockedMagnifierControllerImpl::kSeparatorHeight);
}
// Returns the child container in |root| that should be used as the parent of
// viewport widget and the separator layer.
aura::Window* GetViewportParentContainerForRoot(aura::Window* root) {
return root->GetChildById(kShellWindowId_DockedMagnifierContainer);
}
} // namespace
// static
DockedMagnifierController* DockedMagnifierController::Get() {
return Shell::Get()->docked_magnifier_controller();
}
DockedMagnifierControllerImpl::DockedMagnifierControllerImpl() {
Shell::Get()->session_controller()->AddObserver(this);
if (ui::IMEBridge::Get())
ui::IMEBridge::Get()->AddObserver(this);
}
DockedMagnifierControllerImpl::~DockedMagnifierControllerImpl() {
if (input_method_)
input_method_->RemoveObserver(this);
input_method_ = nullptr;
if (ui::IMEBridge::Get())
ui::IMEBridge::Get()->RemoveObserver(this);
Shell* shell = Shell::Get();
shell->session_controller()->RemoveObserver(this);
if (GetEnabled()) {
shell->window_tree_host_manager()->RemoveObserver(this);
shell->RemovePreTargetHandler(this);
}
}
// static
void DockedMagnifierControllerImpl::RegisterProfilePrefs(
PrefRegistrySimple* registry) {
registry->RegisterBooleanPref(prefs::kDockedMagnifierEnabled, false);
registry->RegisterDoublePref(prefs::kDockedMagnifierScale,
kDefaultMagnifierScale);
}
bool DockedMagnifierControllerImpl::GetEnabled() const {
return active_user_pref_service_ &&
active_user_pref_service_->GetBoolean(prefs::kDockedMagnifierEnabled);
}
float DockedMagnifierControllerImpl::GetScale() const {
if (active_user_pref_service_)
return active_user_pref_service_->GetDouble(prefs::kDockedMagnifierScale);
return kDefaultMagnifierScale;
}
void DockedMagnifierControllerImpl::SetEnabled(bool enabled) {
if (active_user_pref_service_) {
active_user_pref_service_->SetBoolean(prefs::kDockedMagnifierEnabled,
enabled);
}
}
void DockedMagnifierControllerImpl::SetScale(float scale) {
if (active_user_pref_service_) {
active_user_pref_service_->SetDouble(
prefs::kDockedMagnifierScale,
base::ClampToRange(scale, kMinMagnifierScale, kMaxMagnifierScale));
}
}
void DockedMagnifierControllerImpl::StepToNextScaleValue(int delta_index) {
SetScale(magnifier_utils::GetNextMagnifierScaleValue(
delta_index, GetScale(), kMinMagnifierScale, kMaxMagnifierScale));
}
void DockedMagnifierControllerImpl::CenterOnPoint(
const gfx::Point& point_in_screen) {
if (!GetEnabled())
return;
auto* screen = display::Screen::GetScreen();
auto* window = screen->GetWindowAtScreenPoint(point_in_screen);
if (!window) {
// In tests and sometimes initially on signin screen, |point_in_screen|
// maybe invalid and doesn't belong to any existing root window. However, we
// are here because the Docked Magnifier is enabled. We need to create the
// viewport widget somewhere, so we'll use the primary root window until we
// get a valid cursor event.
window = Shell::GetPrimaryRootWindow();
}
auto* root_window = window->GetRootWindow();
DCHECK(root_window);
SwitchCurrentSourceRootWindowIfNeeded(root_window,
true /* update_old_root_workarea */);
auto* host = root_window->GetHost();
DCHECK(host);
MaybeCachePointOfInterestMinimumHeight(host);
gfx::Point point_of_interest(point_in_screen);
::wm::ConvertPointFromScreen(root_window, &point_of_interest);
// The point of interest in pixels.
gfx::PointF point_in_pixels(point_of_interest);
// Before transforming to pixels, make sure its y-coordinate doesn't go below
// the minimum height. Do it here for this PointF since the
// |minimum_point_of_interest_height_| is a float, in order to avoid rounding
// in the transform to be able to reliably verify it in tests.
if (point_in_pixels.y() < minimum_point_of_interest_height_)
point_in_pixels.set_y(minimum_point_of_interest_height_);
// The pixel space is the magnified space.
const float scale = GetScale();
point_in_pixels.Scale(scale);
// Transform steps: (Note that the transform is applied in the opposite
// order)
// 1- Scale the layer by |scale|.
// 2- Translate the point of interest to the center point of the viewport
// widget.
const gfx::Point viewport_center_point =
GetViewportWidgetBoundsInRoot(current_source_root_window_).CenterPoint();
gfx::Transform transform;
transform.Translate(viewport_center_point.x() - point_in_pixels.x(),
viewport_center_point.y() - point_in_pixels.y());
transform.Scale(scale, scale);
// When updating the transform, we don't want any animation, otherwise the
// movement of the mouse won't be very smooth. We want the magnifier layer to
// update immediately with the movement of the mouse (or the change in the
// point of interest due to input caret bounds changes ... etc.).
ui::ScopedLayerAnimationSettings settings(
viewport_magnifier_layer_->GetAnimator());
settings.SetTransitionDuration(base::TimeDelta::FromMilliseconds(0));
settings.SetTweenType(gfx::Tween::ZERO);
settings.SetPreemptionStrategy(ui::LayerAnimator::IMMEDIATELY_SET_NEW_TARGET);
viewport_magnifier_layer_->SetTransform(transform);
}
int DockedMagnifierControllerImpl::GetMagnifierHeightForTesting() const {
return GetTotalMagnifierHeight();
}
void DockedMagnifierControllerImpl::OnActiveUserPrefServiceChanged(
PrefService* pref_service) {
active_user_pref_service_ = pref_service;
InitFromUserPrefs();
}
void DockedMagnifierControllerImpl::OnSigninScreenPrefServiceInitialized(
PrefService* prefs) {
OnActiveUserPrefServiceChanged(prefs);
}
void DockedMagnifierControllerImpl::OnMouseEvent(ui::MouseEvent* event) {
DCHECK(GetEnabled());
CenterOnPoint(GetCursorScreenPoint());
}
void DockedMagnifierControllerImpl::OnScrollEvent(ui::ScrollEvent* event) {
DCHECK(GetEnabled());
if (!event->IsAltDown() || !event->IsControlDown())
return;
if (event->type() == ui::ET_SCROLL_FLING_START ||
event->type() == ui::ET_SCROLL_FLING_CANCEL) {
event->StopPropagation();
return;
}
if (event->type() == ui::ET_SCROLL) {
// Notes: - Clamping of the new scale value happens inside SetScale().
// - Refreshing the viewport happens in the handler of the scale pref
// changes.
SetScale(magnifier_utils::GetScaleFromScroll(
event->y_offset() * kScrollScaleFactor, GetScale(), kMaxMagnifierScale,
kMinMagnifierScale));
event->StopPropagation();
}
}
void DockedMagnifierControllerImpl::OnTouchEvent(ui::TouchEvent* event) {
DCHECK(GetEnabled());
aura::Window* target = static_cast<aura::Window*>(event->target());
aura::Window* event_root = target->GetRootWindow();
gfx::Point event_screen_point = event->root_location();
::wm::ConvertPointToScreen(event_root, &event_screen_point);
CenterOnPoint(event_screen_point);
}
void DockedMagnifierControllerImpl::OnInputContextHandlerChanged() {
if (!GetEnabled())
return;
auto* new_input_method =
magnifier_utils::GetInputMethod(current_source_root_window_);
if (new_input_method == input_method_)
return;
if (input_method_)
input_method_->RemoveObserver(this);
input_method_ = new_input_method;
if (input_method_)
input_method_->AddObserver(this);
}
void DockedMagnifierControllerImpl::OnInputMethodDestroyed(
const ui::InputMethod* input_method) {
DCHECK_EQ(input_method, input_method_);
input_method_->RemoveObserver(this);
input_method_ = nullptr;
}
void DockedMagnifierControllerImpl::OnCaretBoundsChanged(
const ui::TextInputClient* client) {
if (!GetEnabled()) {
// There is a small window between the time the "enabled" pref is updated to
// false, and the time we're notified with this change, upon which we remove
// the magnifier's viewport widget and stop observing the input method.
// During this short interval, if focus is in an editable element, the input
// method can notify us here. In this case, we should just return.
return;
}
aura::client::DragDropClient* drag_drop_client =
aura::client::GetDragDropClient(current_source_root_window_);
if (drag_drop_client && drag_drop_client->IsDragDropInProgress()) {
// Ignore caret bounds change events when they result from changes in window
// bounds due to dragging. This is to leave the viewport centered around the
// cursor.
return;
}
const gfx::Rect caret_screen_bounds = client->GetCaretBounds();
// In many cases, espcially text input events coming from webpages, the caret
// screen width is 0. Hence we can't check IsEmpty() since it returns true if
// either of the width or height is 0. We want to abort if only both are 0s.
if (!caret_screen_bounds.width() && !caret_screen_bounds.height())
return;
CenterOnPoint(caret_screen_bounds.CenterPoint());
}
void DockedMagnifierControllerImpl::OnWidgetDestroying(views::Widget* widget) {
DCHECK_EQ(widget, viewport_widget_);
SwitchCurrentSourceRootWindowIfNeeded(nullptr,
false /* update_old_root_workarea */);
}
void DockedMagnifierControllerImpl::OnDisplayConfigurationChanged() {
DCHECK(GetEnabled());
// The viewport might have been on a display that just got removed, and hence
// the viewport widget and its associated layers are already destroyed. In
// that case we also cleared the |current_source_root_window_|.
if (current_source_root_window_) {
// Resolution may have changed. Update all bounds.
const auto viewport_bounds =
GetViewportWidgetBoundsInRoot(current_source_root_window_);
viewport_widget_->SetBounds(viewport_bounds);
viewport_background_layer_->SetBounds(viewport_bounds);
separator_layer_->SetBounds(
SeparatorBoundsFromViewportBounds(viewport_bounds));
SetViewportHeightInWorkArea(current_source_root_window_,
GetTotalMagnifierHeight());
// Resolution changes, screen rotation, etc. can reset the host to confine
// the mouse cursor inside the root window. We want to make sure the cursor
// is confined properly outside the viewport.
ConfineMouseCursorOutsideViewport();
}
// A change in display configuration, such as resolution, rotation, ... etc.
// invalidates the currently cached minimum height of the point of interest.
is_minimum_point_of_interest_height_valid_ = false;
// Update the viewport magnifier layer transform.
CenterOnPoint(GetCursorScreenPoint());
}
bool DockedMagnifierControllerImpl::GetFullscreenMagnifierEnabled() const {
return active_user_pref_service_ &&
active_user_pref_service_->GetBoolean(
prefs::kAccessibilityScreenMagnifierEnabled);
}
void DockedMagnifierControllerImpl::SetFullscreenMagnifierEnabled(
bool enabled) {
if (active_user_pref_service_) {
active_user_pref_service_->SetBoolean(
prefs::kAccessibilityScreenMagnifierEnabled, enabled);
}
}
int DockedMagnifierControllerImpl::GetTotalMagnifierHeight() const {
if (separator_layer_)
return separator_layer_->bounds().bottom();
return 0;
}
const views::Widget*
DockedMagnifierControllerImpl::GetViewportWidgetForTesting() const {
return viewport_widget_;
}
const ui::Layer*
DockedMagnifierControllerImpl::GetViewportMagnifierLayerForTesting() const {
return viewport_magnifier_layer_.get();
}
float DockedMagnifierControllerImpl::GetMinimumPointOfInterestHeightForTesting()
const {
return minimum_point_of_interest_height_;
}
void DockedMagnifierControllerImpl::SwitchCurrentSourceRootWindowIfNeeded(
aura::Window* new_root_window,
bool update_old_root_workarea) {
if (current_source_root_window_ == new_root_window)
return;
aura::Window* old_root_window = current_source_root_window_;
current_source_root_window_ = new_root_window;
// Current window changes means the minimum height of the point of interest is
// no longer valid.
is_minimum_point_of_interest_height_valid_ = false;
if (old_root_window) {
// Order here matters. We should stop observing caret bounds changes before
// updating the work area bounds of the old root window. Otherwise, work
// area bounds changes will lead to caret bounds changes that recurses back
// here unnecessarily. https://crbug.com/1000903.
if (input_method_)
input_method_->RemoveObserver(this);
input_method_ = nullptr;
if (update_old_root_workarea)
SetViewportHeightInWorkArea(old_root_window, 0);
// Reset mouse cursor confinement to default.
RootWindowController::ForWindow(old_root_window)
->ash_host()
->ConfineCursorToRootWindow();
}
separator_layer_ = nullptr;
if (viewport_widget_) {
viewport_widget_->RemoveObserver(this);
viewport_widget_->Close();
viewport_widget_ = nullptr;
}
viewport_background_layer_ = nullptr;
viewport_magnifier_layer_ = nullptr;
if (!current_source_root_window_) {
// No need to create a new magnifier viewport.
return;
}
CreateMagnifierViewport();
input_method_ = magnifier_utils::GetInputMethod(current_source_root_window_);
if (input_method_)
input_method_->AddObserver(this);
auto* magnified_container = current_source_root_window_->GetChildById(
kShellWindowId_MagnifiedContainer);
viewport_magnifier_layer_->SetShowReflectedLayerSubtree(
magnified_container->layer());
}
void DockedMagnifierControllerImpl::InitFromUserPrefs() {
DCHECK(active_user_pref_service_);
pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>();
pref_change_registrar_->Init(active_user_pref_service_);
pref_change_registrar_->Add(
prefs::kDockedMagnifierEnabled,
base::BindRepeating(&DockedMagnifierControllerImpl::OnEnabledPrefChanged,
base::Unretained(this)));
pref_change_registrar_->Add(
prefs::kDockedMagnifierScale,
base::BindRepeating(&DockedMagnifierControllerImpl::OnScalePrefChanged,
base::Unretained(this)));
pref_change_registrar_->Add(
prefs::kAccessibilityScreenMagnifierEnabled,
base::BindRepeating(&DockedMagnifierControllerImpl::
OnFullscreenMagnifierEnabledPrefChanged,
base::Unretained(this)));
OnEnabledPrefChanged();
}
void DockedMagnifierControllerImpl::OnEnabledPrefChanged() {
// When switching from the signin screen to a newly created profile while the
// Docked Magnifier is enabled, the prefs will be copied from the signin
// profile to the user profile, and the Docked Magnifier will remain enabled.
// We don't want to redo the below operations if the status doesn't change,
// for example readding the same observer to the WindowTreeHostManager will
// cause a crash on DCHECK on debug builds.
const bool current_enabled = !!current_source_root_window_;
const bool new_enabled = GetEnabled();
if (current_enabled == new_enabled)
return;
// Toggling the status of the docked magnifier, changes the display's work
// area. However, display's work area changes are not allowed while overview
// mode is active (See https://crbug.com/834400). For this reason, we exit
// overview mode, before we actually update the state of docked magnifier
// below. https://crbug.com/894256.
Shell* shell = Shell::Get();
auto* overview_controller = shell->overview_controller();
if (overview_controller->InOverviewSession()) {
// |OverviewController::EndOverview| fails (returning false) in certain
// cases involving tablet split view mode. We can guarantee success by
// ensuring that tablet split view mode is not in session.
auto* split_view_controller =
SplitViewController::Get(Shell::GetPrimaryRootWindow());
if (split_view_controller->InTabletSplitViewMode()) {
split_view_controller->EndSplitView(
SplitViewController::EndReason::kNormal);
}
overview_controller->EndOverview();
}
if (new_enabled) {
// Enabling the Docked Magnifier disables the Fullscreen Magnifier.
SetFullscreenMagnifierEnabled(false);
// Calling refresh will result in the creation of the magnifier viewport and
// its associated layers.
Refresh();
// Make sure we are in front of the fullscreen magnifier which also handles
// scroll events.
shell->AddPreTargetHandler(this, ui::EventTarget::Priority::kSystem);
shell->window_tree_host_manager()->AddObserver(this);
} else {
shell->window_tree_host_manager()->RemoveObserver(this);
shell->RemovePreTargetHandler(this);
// Setting the current root window to |nullptr| will remove the viewport and
// all its associated layers.
SwitchCurrentSourceRootWindowIfNeeded(nullptr,
true /* update_old_root_workarea */);
}
// Update the green checkmark status in the accessibility menu in the system
// tray.
shell->accessibility_controller()->NotifyAccessibilityStatusChanged();
// We use software composited mouse cursor so that it can be mirrored into the
// magnifier viewport.
shell->UpdateCursorCompositingEnabled();
}
void DockedMagnifierControllerImpl::OnScalePrefChanged() {
if (GetEnabled()) {
// Invalidate the cached minimum height of the point of interest since the
// change in scale changes that height.
is_minimum_point_of_interest_height_valid_ = false;
Refresh();
}
}
void DockedMagnifierControllerImpl::OnFullscreenMagnifierEnabledPrefChanged() {
// Enabling the Fullscreen Magnifier disables the Docked Magnifier.
if (GetFullscreenMagnifierEnabled())
SetEnabled(false);
}
void DockedMagnifierControllerImpl::Refresh() {
DCHECK(GetEnabled());
CenterOnPoint(GetCursorScreenPoint());
}
void DockedMagnifierControllerImpl::CreateMagnifierViewport() {
DCHECK(GetEnabled());
DCHECK(current_source_root_window_);
const auto viewport_bounds =
GetViewportWidgetBoundsInRoot(current_source_root_window_);
// 1- Create the viewport widget.
viewport_widget_ = new views::Widget;
views::Widget::InitParams params(
views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.activatable = views::Widget::InitParams::ACTIVATABLE_NO;
params.accept_events = false;
params.bounds = viewport_bounds;
params.opacity = views::Widget::InitParams::WindowOpacity::kOpaque;
params.parent =
GetViewportParentContainerForRoot(current_source_root_window_);
params.name = kDockedMagnifierViewportWindowName;
viewport_widget_->Init(std::move(params));
// 2- Create the separator layer right below the viwport widget, parented to
// the layer of the root window.
separator_layer_ = std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR);
separator_layer_->SetColor(SK_ColorBLACK);
separator_layer_->SetBounds(
SeparatorBoundsFromViewportBounds(viewport_bounds));
params.parent->layer()->Add(separator_layer_.get());
// 3- Create a background layer that will show a dark gray color behind the
// magnifier layer. It has the same bounds as the viewport.
viewport_background_layer_ =
std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR);
viewport_background_layer_->SetColor(SK_ColorDKGRAY);
viewport_background_layer_->SetBounds(viewport_bounds);
aura::Window* viewport_window = viewport_widget_->GetNativeView();
ui::Layer* viewport_layer = viewport_window->layer();
viewport_layer->Add(viewport_background_layer_.get());
// 4- Create the layer in which the contents of the screen will be mirrored
// and magnified.
viewport_magnifier_layer_ =
std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR);
// There are situations that the content rect for the magnified container gets
// larger than its bounds (e.g. shelf stretches beyond the screen to allow it
// being dragged up, or contents of mouse pointer might go beyond screen when
// the pointer is at the edges of the screen). To avoid this extra content
// becoming visible in the magnifier, magnifier layer should clip its contents
// to its bounds.
viewport_magnifier_layer_->SetMasksToBounds(true);
viewport_layer->Add(viewport_magnifier_layer_.get());
viewport_layer->SetMasksToBounds(true);
// 5- Update the workarea of the current screen such that an area enough to
// contain the viewport and the separator is allocated at the top of the
// screen.
SetViewportHeightInWorkArea(current_source_root_window_,
GetTotalMagnifierHeight());
// 6- Confine the mouse cursor within the remaining part of the display.
ConfineMouseCursorOutsideViewport();
// 7- Show the widget, which can trigger events to request movement of the
// viewport now that all internal state has been created.
viewport_widget_->AddObserver(this);
viewport_widget_->Show();
}
void DockedMagnifierControllerImpl::MaybeCachePointOfInterestMinimumHeight(
aura::WindowTreeHost* host) {
DCHECK(GetEnabled());
DCHECK(current_source_root_window_);
DCHECK(host);
if (is_minimum_point_of_interest_height_valid_)
return;
// Adjust the point of interest so that we don't end up magnifying the
// magnifier. This means we don't allow the point of interest to go beyond a
// minimum y-coordinate value. Here's how we find that minimum value:
//
// +-----------------+ +-----------------------------------+
// | Viewport | | |
// +====separator====+ | Magnified Viewport |
// | (+) b | |
// | | +==============separator===========(+) A
// | | | Distance (D) --> |
// | | | (+) B
// +-----------------+ | |
// Screen in Non | |
// Magnified Space | |
// | |
// | |
// +-----------------------------------+
// Screen in Magnified Space
// (the contents of |viewport_magnifier_layer_|)
//
// Problem: Find the height of the point of interest (b) in the non-magnified
// coordinates space, which corresponds to the height of point (B) in
// the magnified coordinates space, such that when point (A) is
// translated from the magnified coordinates space to the non-
// magnified coordinates space, its y coordinate is 0 (i.e. aligns
// with the top of the magnifier viewport).
//
// 1- The height of Point (A) in the magnified space is the bottom of the
// entire magnifier (which is actually the bottom of the separator) in the
// magnified coordinates space.
// Note that the magnified space is in pixels. This point should be
// translated such that its y-coordiante is not greater than 0 (in the non-
// magnified coordinates space), otherwise the magnifier will magnify and
// mirror itself.
// 2- Point (B) is the scaled point of interest in the magnified space. The
// point of interest is always translated to the center point of the
// viewport. Hence, if point (A) goes to y = 0, and point (B) goes to a
// height equals to the height of the center point of the viewport,
// therefore means distance (D) = viewport_center_point.y().
// 3- Now that we found the height of point (B) in the magnified space,
// find the the height of point (b) which is the corresponding height in
// the non-magnified space. This height is the minimum height below which
// the point of interest may not go.
const gfx::Rect viewport_bounds =
GetViewportWidgetBoundsInRoot(current_source_root_window_);
// 1- Point (A)'s height.
// Note we use a Vector3dF to actually represent a 2D point. The reason is
// Vector3dF provides an API to get the Length() of the vector without
// converting the object to another temporary object. We need to get the
// Length() rather than y() because screen rotation transform can make the
// height we are interested in either x() or y() depending on the rotation
// angle, so we just simply use Length().
// Note: Why transform the point to the magnified scale and back? The reason
// is that we need to go through the root window transform to go to the pixel
// space. This will account for device scale factors, screen rotations, and
// any other transforms that we cannot anticipate ourselves.
gfx::Vector3dF scaled_magnifier_bottom_in_pixels(
0.0f, viewport_bounds.bottom() + kSeparatorHeight, 0.0f);
const float scale = GetScale();
scaled_magnifier_bottom_in_pixels.Scale(scale);
// 2- Point (B)'s height.
const gfx::PointF viewport_center_point(viewport_bounds.CenterPoint());
gfx::Vector3dF minimum_height_vector(
0.0f,
viewport_center_point.y() + scaled_magnifier_bottom_in_pixels.Length(),
0.0f);
// 3- Back to non-magnified space to get point (b)'s height.
minimum_height_vector.Scale(1 / scale);
minimum_point_of_interest_height_ = minimum_height_vector.Length();
is_minimum_point_of_interest_height_valid_ = true;
}
void DockedMagnifierControllerImpl::ConfineMouseCursorOutsideViewport() {
DCHECK(current_source_root_window_);
gfx::Rect confine_bounds =
current_source_root_window_->GetBoundsInRootWindow();
const int docked_height = separator_layer_->bounds().bottom();
confine_bounds.Offset(0, docked_height);
confine_bounds.set_height(confine_bounds.height() - docked_height);
RootWindowController::ForWindow(current_source_root_window_)
->ash_host()
->ConfineCursorToBoundsInRoot(confine_bounds);
}
} // namespace ash
| [
"pcding@ucdavis.edu"
] | pcding@ucdavis.edu |
0da22c268c2d6257258e8450f8cc2086cba29ad5 | cac53490027280b43f14ab30178edb336a92a0a5 | /ACA/Clear.h | 64f3a164cf8f79e9661e2c2d7e1f41207487081c | [] | no_license | nekko1119/ACA | 79270eaada099b9264da50e0f6feeea39b7759c4 | 079d5170327fcffdcb76a396c0f5dc7a3b7285c3 | refs/heads/master | 2020-05-18T17:49:15.824075 | 2013-07-30T17:10:24 | 2013-07-30T18:14:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | h | #ifndef ACA_SCENE_GAME_CLEAR_H
#define ACA_SCENE_GAME_CLEAR_H
#include "GameScene.h"
#include "Image.hpp"
namespace aca { namespace scene { namespace game {
class Clear : public GameScene
{
public:
Clear();
~Clear();
void update(Game* g);
private:
resource::DefaultImage image;
int count;
};
}}}
#endif | [
"taku5050@mail.goo.ne.jp"
] | taku5050@mail.goo.ne.jp |
9ca0fdc739a0a12f5a1dafb804ca07d47f97ef7d | 842307fcb7954fbf3d8471d08619a09cf8a8be23 | /ui/ozone/platform/wayland/test/test_zaura_output_manager.h | 51520d790c18a3a5247aa4b50d577482947a25ea | [
"BSD-3-Clause"
] | permissive | wahello/chromium | 3e2ecac308f746c1ee36562776506c2ea991d606 | 4b228fefd9c51cc19978f023b96d9858e7d1da95 | refs/heads/main | 2023-04-06T02:10:37.393447 | 2023-03-25T04:12:57 | 2023-03-25T04:12:57 | 131,737,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 722 | h | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_OZONE_PLATFORM_WAYLAND_TEST_TEST_ZAURA_OUTPUT_MANAGER_H_
#define UI_OZONE_PLATFORM_WAYLAND_TEST_TEST_ZAURA_OUTPUT_MANAGER_H_
#include "ui/ozone/platform/wayland/test/global_object.h"
namespace wl {
class TestZAuraOutputManager : public GlobalObject {
public:
TestZAuraOutputManager();
TestZAuraOutputManager(const TestZAuraOutputManager&) = delete;
TestZAuraOutputManager& operator=(const TestZAuraOutputManager&) = delete;
~TestZAuraOutputManager() override;
};
} // namespace wl
#endif // UI_OZONE_PLATFORM_WAYLAND_TEST_TEST_ZAURA_OUTPUT_MANAGER_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
270b4d4cba818a106cee0a41e98713354bfdf2f8 | fc1ad05e4e9593bf315dcc29306437f26ba17c9c | /include/YoloNet.h | 0afa00693a4c44d21deafd1efc751bd6513339ce | [
"MIT"
] | permissive | VasuGoel/object-detection-yolov3 | e62d8f1bf8b3357b2a711555e492cdeeece165d9 | 949884a2981dc61fc0ebae6b1e851a24e05a326c | refs/heads/master | 2022-09-07T16:32:32.294130 | 2020-05-23T11:01:15 | 2020-05-23T11:01:15 | 266,207,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,102 | h | #ifndef YOLONET_H
#define YOLONET_H
#include <string>
#include <vector>
#include <opencv2/dnn.hpp>
using namespace cv;
using namespace cv::dnn;
class YoloNet
{
public:
// Initialize YOLO network with specified model configurations and model weights
YoloNet(std::string modelConfiguration, std::string modelWeights) : modelConfiguration_(modelConfiguration), modelWeights_(modelWeights) {};
void loadNetwork();
void loadClasses(std::string classesFilePath);
std::vector<std::string> getClasses();
void setInput(Mat blob);
std::vector<std::string> getOutputsNames();
void runForwardPass(std::vector<Mat> &outs, std::vector<std::string> outnames);
double getInferenceTime(std::vector<double> &layersTimes);
private:
std::vector<std::string> classes_; // stores class names used in COCO dataset
std::string modelConfiguration_; // specify model configurations
std::string modelWeights_; // specify model weights
Net network_; // used to create and manipulate artificial neural network
};
#endif | [
"goelvasu0712@gmail.com"
] | goelvasu0712@gmail.com |
2ac2adfbf54b96db89f8705f54f26345decac0c4 | 44b8e3a2046b2a20490df4607d0244dd5c6d491c | /Bomberman.cpp | 60bd25df0d537e471b677f623e0df29cec494fe7 | [] | no_license | thomasfantou/Bomberman | 348b09ed3b6a861635b992837b9edf3a8092686c | 9ca2a10c91c3434fa0d1fc22bcb48400f9345c22 | refs/heads/master | 2021-01-19T11:02:58.333903 | 2013-07-18T10:21:52 | 2013-07-18T10:21:52 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,843 | cpp | #include "Bomberman.h"
Bomberman::Bomberman(void)
{
}
Bomberman::Bomberman(int _player)
{
position.x = POSITION_X;
position.y = POSITION_Y;
velocity.x = 0;
velocity.y = 0;
vitesse = 2;
moving = false;
lastMovement = 0;
spriteRect.Top = 0;
spriteRect.Left = 0;
spriteRect.Right = 38;
spriteRect.Bottom = 38;
frame = 0;
games = 0;
bombCount = 1;
bombLvl = 1;
player = _player;
switch(_player)
{
case 1:
image.LoadFromFile("Sprites\\bombermanspritesP1.png");
colonne = 1;
row = 1;
break;
case 2:
image.LoadFromFile("Sprites\\bombermanspritesP2.png");
colonne = 13;
row = 13;
break;
case 3:
image.LoadFromFile("Sprites\\bombermanspritesP3.png");
colonne = 13;
row = 1;
break;
case 4:
image.LoadFromFile("Sprites\\bombermanspritesP4.png");
colonne = 1;
row = 13;
break;
}
position.x += SQUARE_SIZE * colonne;
position.y += SQUARE_SIZE * row;
sprite.SetImage(image);
sprite.SetPosition(position.x, position.y);
}
Bomberman::~Bomberman(void)
{
}
void Bomberman::move(int direction)
{
if(!moving)
{
switch (direction)
{
case UP:
velocity.y = -1 * vitesse;
break;
case RIGHT:
velocity.x = 1 * vitesse;
break;
case DOWN:
velocity.y = 1 * vitesse;
break;
case LEFT:
velocity.x = -1 * vitesse;
break;
}
lastMovement = direction;
moving = true;
}
}
void Bomberman::update(float elapsedTime)
{
if(moving) // on test si il doit y avoir un mouvement pour update car on enlevera le mouvement qd on aura atteint une autre case
{
position.x += velocity.x;
position.y += velocity.y;
int pX = POSITION_X;
int px = position.x;
int pY = POSITION_Y;
int py = position.y;
if((px - pX)%SQUARE_SIZE == 0 && (py - pY)%SQUARE_SIZE == 0) // Si le bomberman arrive pile sur une case il s'arrete
{
moving = false;
velocity.x = 0;
velocity.y = 0;
switch(lastMovement)
{
case UP:
row--;
break;
case RIGHT:
colonne++;
break;
case DOWN:
row++;
break;
case LEFT:
colonne--;
break;
}
//std::cout << "position :" << colonne << ":" << row << std::endl;
configureSprite(STOP);
}
if(velocity.x > 0)
{
if(((px - pX)%SQUARE_SIZE >= (SQUARE_SIZE - vitesse))) // si le bomberman est presque arrive sur une case, on va lui ajouter la vitesse necessaire pour se mettre pile dessus
{
velocity.x = (SQUARE_SIZE - (px - pX)%SQUARE_SIZE);
}
configureSprite(RIGHT);
}
if(velocity.x < 0)
{
if(((px - pX)%SQUARE_SIZE <= (vitesse)) && ((px - pX)%SQUARE_SIZE != 0))// si le bomberman est presque arrive sur une case, on va lui ajouter la vitesse necessaire pour se mettre pile dessus
{
velocity.x = -((px - pX)%SQUARE_SIZE);
}
configureSprite(LEFT);
}
if(velocity.y > 0)
{
if(((py - pY)%SQUARE_SIZE >= (SQUARE_SIZE - vitesse)))// si le bomberman est presque arrive sur une case, on va lui ajouter la vitesse necessaire pour se mettre pile dessus
{
velocity.y = (SQUARE_SIZE - (py - pY)%SQUARE_SIZE);
}
configureSprite(DOWN);
}
if(velocity.y < 0)
{
if(((py - pY)%SQUARE_SIZE <= (vitesse)) && ((py - pY)%SQUARE_SIZE) != 0)// si le bomberman est presque arrive sur une case, on va lui ajouter la vitesse necessaire pour se mettre pile dessus
{
velocity.y = -((py - pY)%SQUARE_SIZE);
}
configureSprite(UP);
}
}
for(int i = 0; i < vBomb.size(); i++) // on regarde si les bombe on passé leur temps de vie, si c'est le cas on les élimine de la liste
{
vBomb.at(i).timeToLive -= elapsedTime;
if(vBomb.at(i).timeToLive <= 0.f)
{
Explosion explosion(vBomb.at(i));
vExplosion.push_back(explosion);
vBomb.erase(vBomb.begin() + i);
bombCount++;
}
}
for(int i = 0; i < vExplosion.size(); i++) // si l'explosion est terminé, on l'élimine de la liste
{
if(!vExplosion.at(i).alive)
{
vExplosion.erase(vExplosion.begin() + i);
}
}
}
void Bomberman::unmove(int direction)
{
switch (direction)
{
case UP:
velocity.y = 0;
break;
case RIGHT:
velocity.x = 0;
break;
case DOWN:
velocity.y = 0;
break;
case LEFT:
velocity.x = 0;
break;
}
}
void Bomberman::configureSprite(int direction)
{
if(direction == STOP) //on a défini -1 si
{
spriteRect.Top = lastMovement * 38;
spriteRect.Left = 0;
spriteRect.Right = spriteRect.Left + 38;
spriteRect.Bottom = spriteRect.Top + 38;
frame = 0;
}
else
{
spriteRect.Top = direction * SQUARE_SIZE;
spriteRect.Bottom = spriteRect.Top + 38;
spriteRect.Left = frame * SQUARE_SIZE;
spriteRect.Right = spriteRect.Left + 38;
if(frame == 8)
frame = 1;
else
frame++;
}
}
void Bomberman::dropBomb()
{
if(bombCount >= 1)
{
Bombe bombe(player, bombLvl); //player pour la couleur, et bombLvl pour la taille
bombe.setPosition(position, colonne, row);
vBomb.push_back(bombe);
bombCount--;
}
} | [
"tbfantou@gmail.com"
] | tbfantou@gmail.com |
dac2b767257e612772d0f79a2014830ff3b584ec | c7b454ec5489a47959d78cd239e069e08993eaef | /labs/Lab21/lab21main.cpp | 683d55fa335318e07ae3e60add20050d484c3f5e | [] | no_license | Yaboi-Gengarboi/cs201 | a087711508504a873b4b3ce9c9867bfe293641fe | 9476a26f7e739b62dd3b197bfa7361d7609eee63 | refs/heads/master | 2020-07-14T23:26:18.336464 | 2019-12-06T02:39:54 | 2019-12-06T02:39:54 | 205,425,806 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | /*
lab21main.cpp
Justyn P. Durnford
Created on 10/23/2019
Finished on 10/23/2019
Main file for Lab 20
*/
#include "truncstruct.hpp"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::string;
int main()
{
string str = "";
int num = 0;
cout << "Enter a string" << endl;
getline(cin, str);
StringInfo si = trunc8(str);
cout << si.str << endl;
cout << si.len << endl;
str = "";
cout << "Enter a string" << endl;
getline(cin, str);
cout << "Enter a number" << endl;
cin >> num;
StringInfo si2 = { str, num };
StringInfo si3 = trunc(si2);
cout << si3.str << endl;
cout << si3.len << endl;
return 0;
} | [
"jpdurnford@alaska.edu"
] | jpdurnford@alaska.edu |
9d1d1501a9a4c36f4b19d400b8f88f40c1af6cc4 | c0caed81b5b3e1498cbca4c1627513c456908e38 | /src/protocols/simple_moves/DesignRepackMover.hh | 50f191b707b2e2c8c56a7286a5dec074647d04f4 | [] | no_license | malaifa/source | 5b34ac0a4e7777265b291fc824da8837ecc3ee84 | fc0af245885de0fb82e0a1144422796a6674aeae | refs/heads/master | 2021-01-19T22:10:22.942155 | 2017-04-19T14:13:07 | 2017-04-19T14:13:07 | 88,761,668 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,432 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu.
/// @file protocols/simple_moves/DesignRepackMover.hh
/// @author Sarel Fleishman (sarelf@u.washington.edu), Eva-Maria Strauch (evas01@u.washington.edu)
#ifndef INCLUDED_protocols_simple_moves_DesignRepackMover_hh
#define INCLUDED_protocols_simple_moves_DesignRepackMover_hh
// Project Headers
#include <core/scoring/ScoreFunction.fwd.hh>
#include <core/pose/Pose.fwd.hh>
#include <protocols/moves/Mover.hh>
#include <core/pack/task/PackerTask.fwd.hh>
#include <core/pack/task/TaskFactory.fwd.hh>
#include <core/types.hh>
#include <utility/tag/Tag.fwd.hh>
#include <basic/datacache/DataMap.fwd.hh>
#include <protocols/filters/Filter.fwd.hh>
#include <utility/exit.hh>
// C++ headers
#include <string>
// Unit headers
#include <protocols/simple_moves/DesignRepackMover.fwd.hh>
#include <utility/vector1.hh>
namespace protocols {
namespace simple_moves {
/// @brief a pure virtual base class for movers which redesign and repack the interface
class DesignRepackMover : public protocols::moves::Mover
{
public:
DesignRepackMover();
DesignRepackMover( std::string const & name );
void setup_packer_and_movemap( core::pose::Pose const & pose );
protocols::moves::MoverOP clone() const = 0; // this is a pure virtual class that cannot be instantiated
protocols::moves::MoverOP fresh_instance() const = 0;
virtual void parse_my_tag( utility::tag::TagCOP, basic::datacache::DataMap &, protocols::filters::Filters_map const &, protocols::moves::Movers_map const &, core::pose::Pose const & );
// managing minimization options
void min_rb( utility::vector1< bool > const & min_rb ) { min_rb_ = min_rb; min_rb_set_ = true;}
/// @brief in most cases, there would only be one rb dof making it useful to have a non-vector accessor to min_rb_. However, if the pose has multiple jumps, setting min_rb_ in this way might cause trouble in other parts of the code.
void min_rb( bool const min_rb ) { min_rb_.clear(); min_rb_.push_back( min_rb ); min_rb_set_ = true; }
utility::vector1< bool > const & min_rb() const { runtime_assert( min_rb_set() ); return min_rb_; }
bool min_rb_set() const { return min_rb_set_; }
void min_sc( utility::vector1< bool > const & min_sc ) { min_sc_ = min_sc; min_sc_set_ = true; }
utility::vector1< bool > const & min_sc() const { runtime_assert( min_sc_set() ); return min_sc_; }
bool min_sc_set() const { return min_sc_set_; }
void min_bb( utility::vector1< bool > const & min_bb ) { min_bb_ = min_bb; min_bb_set_ = true; }
utility::vector1< bool > const & min_bb() const { runtime_assert( min_bb_set() ); return min_bb_; }
bool min_bb_set() const { return min_bb_set_; }
bool optimize_foldtree() const { return optimize_foldtree_; }
void optimize_foldtree( bool const opt ) { optimize_foldtree_ = opt; }
/// @brief a dummy apply so that instantiation of this baseclass would be possible.
virtual void apply( core::pose::Pose & ) {}
virtual std::string get_name() const;
void prevent_repacking( utility::vector1< core::Size > const & p ) { prevent_repacking_ = p; }
utility::vector1< core::Size > const & prevent_repacking() const { return( prevent_repacking_ ); }
void restrict_to_repacking( utility::vector1< core::Size > const & p ) { restrict_to_repacking_ = p; }
utility::vector1< core::Size > const & restrict_to_repacking() const { return( restrict_to_repacking_ ); }
void design( bool const des ) { design_partner1_ = des; design_partner2_ = des; }
bool design() const { return( design_partner1_ || design_partner2_ ); }
void set_scorefxn_repack( core::scoring::ScoreFunctionCOP scorefxn );
void set_scorefxn_minimize( core::scoring::ScoreFunctionCOP scorefxn );
core::scoring::ScoreFunctionOP scorefxn_repack() const;
core::scoring::ScoreFunctionOP scorefxn_minimize() const;
core::pack::task::PackerTaskCOP task() const;
core::pack::task::PackerTaskOP & task();
/// @brief after fiddling with a task from outside this mover, clear it, or else, on the next iteration through
/// the mover the changes will be remembered
void clear_task();
void clear_task_factory();
void use_preset_task( bool const bt ) { use_preset_task_ = bt; }
bool use_preset_task() const { return use_preset_task_; }
void task_factory( core::pack::task::TaskFactoryOP p );
core::pack::task::TaskFactoryOP & task_factory();
core::pack::task::TaskFactoryOP task_factory() const;
virtual ~DesignRepackMover();
protected:
core::scoring::ScoreFunctionOP scorefxn_repack_;
core::scoring::ScoreFunctionOP scorefxn_minimize_;
bool repack_partner1_, repack_partner2_;
bool design_partner1_, design_partner2_; // design or only repack?
// curr_ variables are reset with every apply, whereas the min_ variables do not
utility::vector1< bool > min_sc_, curr_min_sc_, min_rb_;
utility::vector1< bool > min_bb_, curr_min_bb_, curr_min_rb_;
bool min_rb_set_, min_sc_set_, min_bb_set_;
utility::vector1< core::Size > target_residues_;
core::Real interface_distance_cutoff_;
bool repack_non_ala_; // do we redesign nonalanine positions?
bool optimize_foldtree_; // do we want to optimize or keep the input fold tree or optimize it?
bool automatic_repacking_definition_;
core::pack::task::PackerTaskOP task_;
bool use_preset_task_;// use as a basis for computing the packer task a task that was precomputed.
utility::vector1< bool > allowed_aas_; //the default allowed aas in designable positions
// The following parameters override the automatically decided parameters.
utility::vector1< core::Size > prevent_repacking_; //residues that should not be repacked
utility::vector1< core::Size > restrict_to_repacking_; //residues that should not be designed
core::pack::task::TaskFactoryOP task_factory_; // sequence positions and residue-level tasks to apply when setup_packer_task is done
bool symmetry_;
};
} // simple_moves
} // protocols
#endif /*INCLUDED_protocols_protein_interface_design_movers_DesignRepackMover_HH*/
| [
"malaifa@yahoo.com"
] | malaifa@yahoo.com |
e8b533d1a0a7ee8b5d6a31b2bbca9b2bd0c1f23d | f77f680fbca3644d88869b542bf12b2664ef583c | /lazorSolver/lazorSolver/Point.cpp | a9ad67ceba2dce720f82cfe7cc975beb9b41ce24 | [
"Apache-2.0"
] | permissive | peyremorgan/LazorSolver | fee690643373ca0a6882e8ddf7119d1bb842154f | e9886ea00eed70ed45ab37a8b25c3426cb409748 | refs/heads/master | 2020-06-01T15:13:38.735572 | 2014-11-03T10:03:48 | 2014-11-03T10:03:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 337 | cpp | #include "Point.h"
Point::Point()
{
}
Point::Point(int x, int y)
{
this->x = x;
this->y = y;
}
Point::~Point()
{
}
bool operator==(Point const& a, Point const& b)
{
return a.x == b.x && a.y == b.y;
}
std::ostream& operator<<(std::ostream& flux, Point const& point)
{
flux << "x=" << point.x << ", y=" << point.y;
return flux;
} | [
"paulbnt@free.fr"
] | paulbnt@free.fr |
c2019afc84117b6a118e24198077f74cb89c4ba1 | 230fb8845f39bef0f30f5d3541eff5dc0641de14 | /Connect3/Export/windows/obj/include/lime/graphics/opengl/GLObject.h | fffdf809c5a6fc87fed1d57ac02744e161aff6bc | [] | no_license | vhlk/AlgoritmoMinMax | 76abd62a6e2859ed229e5831264b6d8af27e318d | 40eded4948794ca48d50d16d2133a9ab21207768 | refs/heads/main | 2023-06-30T15:16:17.492478 | 2021-08-02T13:29:32 | 2021-08-02T13:29:32 | 390,493,745 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 2,513 | h | // Generated by Haxe 4.2.0
#ifndef INCLUDED_lime_graphics_opengl_GLObject
#define INCLUDED_lime_graphics_opengl_GLObject
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_STACK_FRAME(_hx_pos_def54b8cacb52d8e_2614_new)
HX_DECLARE_CLASS3(lime,graphics,opengl,GLObject)
namespace lime{
namespace graphics{
namespace opengl{
class HXCPP_CLASS_ATTRIBUTES GLObject_obj : public ::hx::Object
{
public:
typedef ::hx::Object super;
typedef GLObject_obj OBJ_;
GLObject_obj();
public:
enum { _hx_ClassId = 0x018b5f13 };
void __construct(int id);
inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="lime.graphics.opengl.GLObject")
{ return ::hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return ::hx::Object::operator new(inSize+extra,true,"lime.graphics.opengl.GLObject"); }
inline static ::hx::ObjectPtr< GLObject_obj > __new(int id) {
::hx::ObjectPtr< GLObject_obj > __this = new GLObject_obj();
__this->__construct(id);
return __this;
}
inline static ::hx::ObjectPtr< GLObject_obj > __alloc(::hx::Ctx *_hx_ctx,int id) {
GLObject_obj *__this = (GLObject_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(GLObject_obj), true, "lime.graphics.opengl.GLObject"));
*(void **)__this = GLObject_obj::_hx_vtable;
{
HX_STACKFRAME(&_hx_pos_def54b8cacb52d8e_2614_new)
HXDLIN(2614) ( ( ::lime::graphics::opengl::GLObject)(__this) )->id = id;
}
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(::hx::DynamicArray inArgs);
//~GLObject_obj();
HX_DO_RTTI_ALL;
::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp);
static bool __GetStatic(const ::String &inString, Dynamic &outValue, ::hx::PropertyAccess inCallProp);
::hx::Val __SetField(const ::String &inString,const ::hx::Val &inValue, ::hx::PropertyAccess inCallProp);
void __GetFields(Array< ::String> &outFields);
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("GLObject",c4,da,30,7f); }
static ::lime::graphics::opengl::GLObject fromInt(int type,int id);
static ::Dynamic fromInt_dyn();
int id;
::Dynamic ptr;
::Array< ::Dynamic> refs;
};
} // end namespace lime
} // end namespace graphics
} // end namespace opengl
#endif /* INCLUDED_lime_graphics_opengl_GLObject */
| [
"vhlk@cin.ufpe.br"
] | vhlk@cin.ufpe.br |
ace7fef89ef044357a852bdcc03fe80e9e6e6db8 | d28e013c718091502ceae29597e9e7d781834b53 | /Ultimate/lib/iw4/party.cpp | 3ca297cdb110f35c2c83288dc01698a6fceea6ca | [] | no_license | Scoudcorp/Ultimate | f0a1d1be32c4a86c08e4c317f077e6c907011257 | 06bc77ddb58766f346067cb40796fe268b85beb0 | refs/heads/master | 2021-06-04T08:15:49.625160 | 2019-05-15T08:22:00 | 2019-05-15T08:22:00 | 136,847,174 | 20 | 12 | null | 2021-02-16T12:52:47 | 2018-06-10T21:45:11 | C++ | UTF-8 | C++ | false | false | 184 | cpp | #include "party.h"
std::array<uint8_t, 4> PartyClient::getRemoteIp() const
{
std::array<uint8_t, 4> out{};
std::copy(remoteIp, remoteIp + 4, out.begin());
return out;
}
| [
"tvvaalen@gmail.com"
] | tvvaalen@gmail.com |
2c40923051fef3b63cd297d890eff1ecc5a5f5c2 | a3430869256640cb48c6dbe171e8205d044c65ef | /580 Final/HW4test/rend.cpp | 616bec0c871fd1a5e0082ed5839b14c65ecfbc49 | [] | no_license | XiangyuLi926/CSCI-580-3D-Graphic-and-Rendering | 615a2586a7cfcf30558b591a9c8c1b3abe253f16 | 5bdba9f77e2cee911a6eeab04fa745752bd82343 | refs/heads/master | 2021-01-10T14:39:58.570299 | 2016-03-30T03:50:54 | 2016-03-30T03:50:54 | 55,028,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,087 | cpp | #include <string.h>
#include <math.h>
#include "rend.h"
#define DEGREE2RADIAN 0.01745329252f
int GzRotXMat(float degree, GzMatrix mat)
{
memset(mat, 0, sizeof(GzMatrix));
mat[0][0] = 1.f;
mat[1][1] = cosf(degree * DEGREE2RADIAN);
mat[1][2] = -sinf(degree * DEGREE2RADIAN);
mat[2][1] = -mat[1][2];
mat[2][2] = mat[1][1];
mat[3][3] = 1.f;
return GZ_SUCCESS;
}
int GzRotYMat(float degree, GzMatrix mat)
{
memset(mat, 0, sizeof(GzMatrix));
mat[0][0] = cosf(degree * DEGREE2RADIAN);
mat[0][2] = sinf(degree * DEGREE2RADIAN);
mat[1][1] = 1.f;
mat[2][0] = -mat[0][2];
mat[2][2] = mat[0][0];
mat[3][3] = 1.f;
return GZ_SUCCESS;
}
int GzRotZMat(float degree, GzMatrix mat)
{
memset(mat, 0, sizeof(GzMatrix));
mat[0][0] = cosf(degree * DEGREE2RADIAN);
mat[0][1] = -sinf(degree * DEGREE2RADIAN);
mat[1][0] = -mat[0][1];
mat[1][1] = mat[0][0];
mat[2][2] = 1.f;
mat[3][3] = 1.f;
return GZ_SUCCESS;
}
int GzTrxMat(GzCoord translate, GzMatrix mat)
{
memset(mat, 0, sizeof(GzMatrix));
mat[0][0] = 1.f;
mat[X][3] = translate[X];
mat[1][1] = 1.f;
mat[Y][3] = translate[Y];
mat[2][2] = 1.f;
mat[Z][3] = translate[Z];
mat[3][3] = 1.f;
return GZ_SUCCESS;
}
int GzScaleMat(GzCoord scale, GzMatrix mat)
{
memset(mat, 0, sizeof(GzMatrix));
mat[X][X] = scale[X];
mat[Y][Y] = scale[Y];
mat[Z][Z] = scale[Z];
mat[3][3] = 1.f;
return GZ_SUCCESS;
}
//----------------------------------------------------------
// Begin main functions
int GzNewRender(GzRender **render, GzRenderClass renderClass, GzDisplay *display)
{
GzRender *pThis = new GzRender();
if (pThis == NULL)
{
*render = NULL;
return GZ_FAILURE;
}
*render = pThis;
pThis->renderClass = renderClass;
pThis->display = display;
pThis->open = 0;
/* Matrix transforms */
pThis->camera.position[X] = DEFAULT_IM_X;
pThis->camera.position[Y] = DEFAULT_IM_Y;
pThis->camera.position[Z] = DEFAULT_IM_Z;
pThis->camera.lookat[X] = 0.f;
pThis->camera.lookat[Y] = 0.f;
pThis->camera.lookat[Z] = 0.f;
pThis->camera.worldup[X] = 0.f;
pThis->camera.worldup[Y] = 1.f;
pThis->camera.worldup[Z] = 0.f;
pThis->camera.FOV = DEFAULT_FOV;
pThis->matlevel = -1;
memset(pThis->Xsp, 0, sizeof(pThis->Xsp));
pThis->Xsp[0][0] = display->xres * 0.5f;
pThis->Xsp[0][3] = pThis->Xsp[0][0];
pThis->Xsp[1][1] = -display->yres * 0.5f;
pThis->Xsp[1][3] = -pThis->Xsp[1][1];
pThis->Xsp[2][2] = 1.f;
pThis->Xsp[3][3] = 1.f;
/* Lighting & shading */
GzColor tocopy[3] = { DEFAULT_AMBIENT, DEFAULT_DIFFUSE, DEFAULT_SPECULAR };
memcpy(pThis->Ka, tocopy[0], sizeof(GzColor));
memcpy(pThis->Kd, tocopy[1], sizeof(GzColor));
memcpy(pThis->Ks, tocopy[2], sizeof(GzColor));
return GZ_SUCCESS;
}
int GzFreeRender(GzRender *render)
{
if (render == NULL) return GZ_FAILURE;
delete render;
return GZ_SUCCESS;
}
static inline void
NormalNormal(GzCoord &This, bool precise = true)
{
float sum = This[X] * This[X] + This[Y] * This[Y] + This[Z] * This[Z];
if (precise || (sizeof(int) != sizeof(float))) sum = 1.f / sqrtf(sum);
else
{
float half = sum * 0.5f;
int i = *(int *)∑
i = 0x5f3759df - (i >> 1);
sum = *(float *)&i;
sum *= (1.5f - (half * sum * sum));
sum *= (1.5f - (half * sum * sum));
}
This[X] *= sum;
This[Y] *= sum;
This[Z] *= sum;
}
static inline float
NormalDotProduct(GzCoord &A, GzCoord &B)
{
return (A[X] * B[X] + A[Y] * B[Y] + A[Z] * B[Z]);
}
static inline float
NormalDotProduct(GzMatrix &A, int row, GzCoord &B)
{
return (A[row][X] * B[X] + A[row][Y] * B[Y] + A[row][Z] * B[Z]);
}
int GzBeginRender(GzRender *render)
{
GzCoord test = {1.0e19,0,0};
NormalNormal(test, false);
if (render == NULL)
{
return GZ_FAILURE;
}
render->open = 1 & render->display->open;
float recipd = tanf(render->camera.FOV * DEGREE2RADIAN * 0.5f);
render->Xsp[2][2] = 0x7FFFFFFF * recipd;
/* compute Xpi */
memset(render->camera.Xpi, 0, sizeof(GzMatrix));
render->camera.Xpi[0][0] = 1.f;
render->camera.Xpi[1][1] = 1.f;
render->camera.Xpi[2][2] = 1.f;
render->camera.Xpi[3][2] = recipd;
render->camera.Xpi[3][3] = 1.f;
/* compute Xiw */
GzCoord camZ = {
render->camera.lookat[X] - render->camera.position[X],
render->camera.lookat[Y] - render->camera.position[Y],
render->camera.lookat[Z] - render->camera.position[Z]
};
NormalNormal(camZ);
float dotYZ = NormalDotProduct(render->camera.worldup, camZ);
GzCoord camY = {
render->camera.worldup[X] - (dotYZ * camZ[X]),
render->camera.worldup[Y] - (dotYZ * camZ[Y]),
render->camera.worldup[Z] - (dotYZ * camZ[Z])
};
NormalNormal(camY);
render->camera.Xiw[0][X] = camY[Y] * camZ[Z] - camY[Z] * camZ[Y];
render->camera.Xiw[0][Y] = camY[Z] * camZ[X] - camY[X] * camZ[Z];
render->camera.Xiw[0][Z] = camY[X] * camZ[Y] - camY[Y] * camZ[X];
render->camera.Xiw[0][3] = -NormalDotProduct(render->camera.Xiw, 0, render->camera.position);
memcpy(render->camera.Xiw[1], camY, sizeof(GzCoord));
render->camera.Xiw[1][3] = -NormalDotProduct(render->camera.Xiw, 1, render->camera.position);
memcpy(render->camera.Xiw[2], camZ, sizeof(GzCoord));
render->camera.Xiw[2][3] = -NormalDotProduct(render->camera.Xiw, 2, render->camera.position);
memset(render->camera.Xiw[3], 0, sizeof(GzCoord));
render->camera.Xiw[3][3] = 1.f;
render->matlevel = -1;
GzPushMatrix(render, render->camera.Xpi);
GzPushMatrix(render, render->camera.Xiw);
render->numlights = -1;
render->flatcolor[RED] = 1.f;
render->flatcolor[GREEN] = 1.f;
render->flatcolor[BLUE] = 1.f;
return GZ_SUCCESS;
}
int GzPutCamera(GzRender *render, GzCamera *camera)
{
render->open = 0;
memcpy(&(render->camera), camera, sizeof(GzCamera));
return GZ_SUCCESS;
}
int GzPushMatrix(GzRender *render, GzMatrix matrix)
{
if ((render->matlevel + 1) == MATLEVELS)
{
return GZ_FAILURE;
}
render->matlevel++;
GzMatrix &vert = render->Xvert[render->matlevel];
if (render->matlevel > 0)
{
GzMatrix &last = render->Xvert[render->matlevel - 1];
for (int y = 0; y < 4; y++)
for (int x = 0; x < 4; x++)
{
vert[y][x] = last[y][0] * matrix[0][x] + last[y][1] * matrix[1][x] +
last[y][2] * matrix[2][x] + last[y][3] * matrix[3][x];
}
}
else
{
memcpy(vert, matrix, sizeof(GzMatrix));
}
/* Compute norm=inv(vert.') */
GzMatrix &norm = render->Xnorm[render->matlevel];
norm[0][0] = vert[1][1] * vert[2][2] - vert[1][2] * vert[2][1];
norm[0][1] = vert[1][2] * vert[2][0] - vert[1][0] * vert[2][2];
norm[0][2] = vert[1][0] * vert[2][1] - vert[1][1] * vert[2][0];
norm[1][0] = vert[0][2] * vert[2][1] - vert[0][1] * vert[2][2];
norm[1][1] = vert[0][0] * vert[2][2] - vert[0][2] * vert[2][0];
norm[1][2] = vert[0][1] * vert[2][0] - vert[0][0] * vert[2][1];
norm[2][0] = vert[0][1] * vert[1][2] - vert[0][2] * vert[1][1];
norm[2][1] = vert[0][2] * vert[1][0] - vert[0][0] * vert[1][2];
norm[2][2] = vert[0][0] * vert[1][1] - vert[0][1] * vert[1][0];
return GZ_SUCCESS;
}
int GzPopMatrix(GzRender *render)
{
if (render->matlevel < 0) return GZ_FAILURE;
render->matlevel--;
return GZ_SUCCESS;
}
int GzPushLight(GzRender *render, GzLight light)
{
if ((render->numlights + 1) == MAX_LIGHTS)
{
return GZ_FAILURE;
}
render->numlights++;
memcpy(&(render->lights[render->numlights]), &light, sizeof(GzLight));
return GZ_SUCCESS;
}
int GzPopLight(GzRender *render)
{
if (render->numlights < 0) return GZ_FAILURE;
render->numlights--;
return GZ_SUCCESS;
}
int GzPutAttribute(GzRender *render, int numAttributes, GzToken *nameList, GzPointer *valueList)
{
if ((render == NULL) || (render->open == 0)) return GZ_FAILURE;
int status = 0;
while (numAttributes > 0)
{
numAttributes--;
switch (nameList[numAttributes])
{
case GZ_RGB_COLOR:
{
GzColor *color = (GzColor *)valueList[numAttributes];
render->flatcolor[RED] = (*color)[RED];
render->flatcolor[GREEN] = (*color)[GREEN];
render->flatcolor[BLUE] = (*color)[BLUE];
break;
}
case GZ_DIRECTIONAL_LIGHT:
{
GzLight *light = (GzLight *)valueList[numAttributes];
if ((render->numlights + 1) == MAX_LIGHTS)
{
status |= GZ_FAILURE;
}
else
{
render->numlights++;
memcpy(&(render->lights[render->numlights]), light, sizeof(GzLight));
}
break;
}
case GZ_AMBIENT_LIGHT:
{
GzLight *light = (GzLight *)valueList[numAttributes];
memcpy(&(render->ambientlight), light, sizeof(GzLight));
break;
}
case GZ_AMBIENT_COEFFICIENT:
{
GzColor *color = (GzColor *)valueList[numAttributes];
memcpy(&(render->Ka), color, sizeof(GzColor));
break;
}
case GZ_DIFFUSE_COEFFICIENT:
{
GzColor *color = (GzColor *)valueList[numAttributes];
memcpy(&(render->Kd), color, sizeof(GzColor));
break;
}
case GZ_SPECULAR_COEFFICIENT:
{
GzColor *color = (GzColor *)valueList[numAttributes];
memcpy(&(render->Ks), color, sizeof(GzColor));
break;
}
case GZ_DISTRIBUTION_COEFFICIENT:
{
float *power = (float *)valueList[numAttributes];
render->spec = *power;
break;
}
case GZ_INTERPOLATE:
{
int *style = (int *)valueList[numAttributes];
render->interp_mode = *style;
break;
}
default:
{
status |= GZ_FAILURE;
break;
}
}
}
return status;
}
/* Begin draw functions */
static inline void
GzCompute_Color(GzRender *render, float Vx, float Vy, GzCoord &Normal, GzColor &color)
{
color[RED] = render->ambientlight.color[RED] * render->Ka[RED];
color[GREEN] = render->ambientlight.color[GREEN] * render->Ka[GREEN];
color[BLUE] = render->ambientlight.color[BLUE] * render->Ka[BLUE];
/* compute E */
GzCoord E =
{
-((Vx - render->Xsp[0][3]) / render->Xsp[0][0] * render->camera.Xpi[3][2]),
-((Vy - render->Xsp[1][3]) / render->Xsp[1][1] * render->camera.Xpi[3][2]),
-1
};
NormalNormal(E, false);
for (int i = render->numlights; i >= 0; i--)
{
GzCoord &L = render->lights[i].direction;
GzColor &Le = render->lights[i].color;
float NL = NormalDotProduct(Normal, L);
float NE = NormalDotProduct(Normal, E);
bool flipnormal = (NL < 0.f) && (NE < 0.f);
if (((NL > 0.f) && (NE > 0.f)) || flipnormal)
{
color[RED] += Le[RED] * render->Kd[RED] * (flipnormal ? -NL : NL);
color[GREEN] += Le[GREEN] * render->Kd[GREEN] * (flipnormal ? -NL : NL);
color[BLUE] += Le[BLUE] * render->Kd[BLUE] * (flipnormal ? -NL : NL);
GzCoord R =
{
(NL + NL) * Normal[X] - L[X],
(NL + NL) * Normal[Y] - L[Y],
(NL + NL) * Normal[Z] - L[Z]
};
float RE = NormalDotProduct(R, E);
if (RE > 0.f)
{
RE = powf(RE, render->spec);
color[RED] += Le[RED] * render->Ks[RED] * RE;
color[GREEN] += Le[GREEN] * render->Ks[GREEN] * RE;
color[BLUE] += Le[BLUE] * render->Ks[BLUE] * RE;
}
}
}
}
static inline int
GzDraw_Triangle_LEE(GzRender *render, GzCoord(&Vertex)[3], GzCoord(&Normal)[3])
{
GzCoord NdcNorm[3];
if (render->matlevel >= 0)
{
GzMatrix &vert = render->Xvert[render->matlevel];
GzMatrix &norm = render->Xnorm[render->matlevel];
for (int i = 0; i < 3; i++)
{
float cvert[4] =
{
NormalDotProduct(vert, 0, Vertex[i]) + vert[0][3],
NormalDotProduct(vert, 1, Vertex[i]) + vert[1][3],
NormalDotProduct(vert, 2, Vertex[i]) + vert[2][3],
NormalDotProduct(vert, 3, Vertex[i]) + vert[3][3]
};
/* Xsp transform */
Vertex[i][X] = (cvert[0] / cvert[3]) * render->Xsp[0][0] + render->Xsp[0][3];
Vertex[i][Y] = (cvert[1] / cvert[3]) * render->Xsp[1][1] + render->Xsp[1][3];
Vertex[i][Z] = (cvert[2] / cvert[3]) * render->Xsp[2][2];
/* projected Z clip */
if ((Vertex[i][Z] < 0) || (Vertex[i][Z] > (float)0x7FFFFFFF))
{
return GZ_SUCCESS;
}
if (Normal == NULL) continue;
NdcNorm[i][0] = NormalDotProduct(norm, 0, Normal[i]);
NdcNorm[i][1] = NormalDotProduct(norm, 1, Normal[i]);
NdcNorm[i][2] = NormalDotProduct(norm, 2, Normal[i]);
NormalNormal(NdcNorm[i]);
}
}
/* Draw bounding check */
int Xmin = render->display->xres, Xmax = -1;
int Ymin = render->display->yres, Ymax = -1;
for (int i = 0; i < 3; i++)
{
if (Xmin > Vertex[i][X]) Xmin = (int)Vertex[i][X];
if (Xmax < Vertex[i][X]) Xmax = (int)Vertex[i][X];
if (Ymin > Vertex[i][Y]) Ymin = (int)Vertex[i][Y];
if (Ymax < Vertex[i][Y]) Ymax = (int)Vertex[i][Y];
}
Xmin = (Xmin < 0) ? 0 : Xmin;
Xmax = (Xmax >= render->display->xres) ? (render->display->xres - 1) : Xmax;
Ymin = (Ymin < 0) ? 0 : Ymin;
Ymax = (Ymax >= render->display->yres) ? (render->display->yres - 1) : Ymax;
if ((Xmin > Xmax) || (Ymin > Ymax)) return GZ_SUCCESS;
/*
* Line Equations 0-2: AB,AC,BC lines
* Interpolations 3: Z 4: red or Nx 5: green or Ny 6: blue or Nz
*/
#define XCEF_INTERPOLATE(Va, Vb, Vc) (Va * Xcef[1] + Vb * Xcef[2] + Vc * Xcef[0])\
/(Vertex[0][X] * Xcef[1] + Vertex[1][X] * Xcef[2] + Vertex[2][X] * Xcef[0])
#define YCEF_INTERPOLATE(Va, Vb, Vc) (Va * Ycef[1] + Vb * Ycef[2] + Vc * Ycef[0])\
/(Vertex[0][Y] * Ycef[1] + Vertex[1][Y] * Ycef[2] + Vertex[2][Y] * Ycef[0])
#define D_INTERPOLATE(Va, Vb, Vc, Xcef, Ycef) (0.33333333333f * (Va + Vb + Vc\
- Xcef * (Vertex[0][X] + Vertex[1][X] + Vertex[2][X])\
- Ycef * (Vertex[0][Y] + Vertex[1][Y] + Vertex[2][Y])))
float Xcef[7] =
{
Vertex[0][Y] - Vertex[1][Y],
Vertex[1][Y] - Vertex[2][Y],
Vertex[2][Y] - Vertex[0][Y],
XCEF_INTERPOLATE(Vertex[0][Z], Vertex[1][Z], Vertex[2][Z])
};
float Ycef[7] =
{
Vertex[1][X] - Vertex[0][X],
Vertex[2][X] - Vertex[1][X],
Vertex[0][X] - Vertex[2][X],
YCEF_INTERPOLATE(Vertex[0][Z], Vertex[1][Z], Vertex[2][Z])
};
float EvalStart[7] =
{
Xcef[0] * Xmin + Ycef[0] * Ymin + Vertex[0][X] * Vertex[1][Y] - Vertex[1][X] * Vertex[0][Y],
Xcef[1] * Xmin + Ycef[1] * Ymin + Vertex[1][X] * Vertex[2][Y] - Vertex[2][X] * Vertex[1][Y],
Xcef[2] * Xmin + Ycef[2] * Ymin + Vertex[2][X] * Vertex[0][Y] - Vertex[0][X] * Vertex[2][Y],
Xcef[3] * Xmin + Ycef[3] * Ymin + D_INTERPOLATE(Vertex[0][Z], Vertex[1][Z], Vertex[2][Z], Xcef[3], Ycef[3])
};
switch (render->interp_mode)
{
case GZ_COLOR:
{
GzColor colors[3];
GzCompute_Color(render, Vertex[0][X], Vertex[0][Y], NdcNorm[0], colors[0]);
GzCompute_Color(render, Vertex[1][X], Vertex[1][Y], NdcNorm[1], colors[1]);
GzCompute_Color(render, Vertex[2][X], Vertex[2][Y], NdcNorm[2], colors[2]);
/* X interpolation of RGB */
Xcef[4] = XCEF_INTERPOLATE(colors[0][RED], colors[1][RED], colors[2][RED]);
Xcef[5] = XCEF_INTERPOLATE(colors[0][GREEN], colors[1][GREEN], colors[2][GREEN]);
Xcef[6] = XCEF_INTERPOLATE(colors[0][BLUE], colors[1][BLUE], colors[2][BLUE]);
/* Y interpolation of RGB */
Ycef[4] = YCEF_INTERPOLATE(colors[0][RED], colors[1][RED], colors[2][RED]);
Ycef[5] = YCEF_INTERPOLATE(colors[0][GREEN], colors[1][GREEN], colors[2][GREEN]);
Ycef[6] = YCEF_INTERPOLATE(colors[0][BLUE], colors[1][BLUE], colors[2][BLUE]);
/* Initiate value of RGB interpolation */
EvalStart[4] = Xcef[4] * Xmin + Ycef[4] * Ymin + D_INTERPOLATE\
(colors[0][RED], colors[1][RED], colors[2][RED], Xcef[4], Ycef[4]);
EvalStart[5] = Xcef[5] * Xmin + Ycef[5] * Ymin + D_INTERPOLATE\
(colors[0][GREEN], colors[1][GREEN], colors[2][GREEN], Xcef[5], Ycef[5]);
EvalStart[6] = Xcef[6] * Xmin + Ycef[6] * Ymin + D_INTERPOLATE\
(colors[0][BLUE], colors[1][BLUE], colors[2][BLUE], Xcef[6], Ycef[6]);
break;
}
case GZ_NORMALS:
{
/* X interpolation of NdcNorm */
Xcef[4] = XCEF_INTERPOLATE(NdcNorm[0][X], NdcNorm[1][X], NdcNorm[2][X]);
Xcef[5] = XCEF_INTERPOLATE(NdcNorm[0][Y], NdcNorm[1][Y], NdcNorm[2][Y]);
Xcef[6] = XCEF_INTERPOLATE(NdcNorm[0][Z], NdcNorm[1][Z], NdcNorm[2][Z]);
/* Y interpolation of NdcNorm */
Ycef[4] = YCEF_INTERPOLATE(NdcNorm[0][X], NdcNorm[1][X], NdcNorm[2][X]);
Ycef[5] = YCEF_INTERPOLATE(NdcNorm[0][Y], NdcNorm[1][Y], NdcNorm[2][Y]);
Ycef[6] = YCEF_INTERPOLATE(NdcNorm[0][Z], NdcNorm[1][Z], NdcNorm[2][Z]);
/* Initiate value of NdcNorm interpolation */
EvalStart[4] = Xcef[4] * Xmin + Ycef[4] * Ymin + D_INTERPOLATE\
(NdcNorm[0][X], NdcNorm[1][X], NdcNorm[2][X], Xcef[4], Ycef[4]);
EvalStart[5] = Xcef[5] * Xmin + Ycef[5] * Ymin + D_INTERPOLATE\
(NdcNorm[0][Y], NdcNorm[1][Y], NdcNorm[2][Y], Xcef[5], Ycef[5]);
EvalStart[6] = Xcef[6] * Xmin + Ycef[6] * Ymin + D_INTERPOLATE\
(NdcNorm[0][Z], NdcNorm[1][Z], NdcNorm[2][Z], Xcef[6], Ycef[6]);
break;
}
default:
{
Xcef[4] = 0.f;
Xcef[5] = 0.f;
Xcef[6] = 0.f;
Ycef[4] = 0.f;
Ycef[5] = 0.f;
Ycef[6] = 0.f;
EvalStart[4] = 0.f;
EvalStart[5] = 0.f;
EvalStart[6] = 0.f;
break;
}
}
bool ntoprow = false;
for (; Ymin <= Ymax; Ymin++)
{
float EvalNow[7];
memcpy(EvalNow, EvalStart, sizeof(EvalNow));
for (int Xnow = Xmin; Xnow <= Xmax; Xnow++)
{
bool Flag[3][2] =
{
{ EvalNow[0] <= 0.f, EvalNow[0] >= 0.f },
{ EvalNow[1] <= 0.f, EvalNow[1] >= 0.f },
{ EvalNow[2] <= 0.f, EvalNow[2] >= 0.f }
};
bool uniFlag[2] =
{
Flag[0][0] && Flag[1][0] && Flag[2][0],
Flag[0][1] && Flag[1][1] && Flag[2][1]
};
if (uniFlag[0] || uniFlag[1])
{
if (uniFlag[0] && uniFlag[1] && ntoprow && (Xnow != Xmin))
{
/*Only draw top left part*/
continue;
}
switch (render->interp_mode)
{
case GZ_COLOR:
{
GzPutDisplay(render->display,
Xnow,
Ymin,
(GzIntensity)(EvalNow[4] * 4095.f),
(GzIntensity)(EvalNow[5] * 4095.f),
(GzIntensity)(EvalNow[6] * 4095.f),
0,
(GzDepth)EvalNow[3]);
break;
}
case GZ_NORMALS:
{
GzColor Ncolor;
GzCoord Nnow = { EvalNow[4], EvalNow[5], EvalNow[6] };
NormalNormal(Nnow, false);
GzCompute_Color(render, (float)Xnow, (float)Ymin, Nnow, Ncolor);
GzPutDisplay(render->display,
Xnow,
Ymin,
(GzIntensity)(Ncolor[RED] * 4095.f),
(GzIntensity)(Ncolor[GREEN] * 4095.f),
(GzIntensity)(Ncolor[BLUE] * 4095.f),
0,
(GzDepth)EvalNow[3]);
break;
}
default:
{
GzPutDisplay(render->display,
Xnow,
Ymin,
(GzIntensity)(render->flatcolor[RED] * 4095.f),
(GzIntensity)(render->flatcolor[GREEN] * 4095.f),
(GzIntensity)(render->flatcolor[BLUE] * 4095.f),
0,
(GzDepth)EvalNow[3]);
break;
}
}
}
EvalNow[0] += Xcef[0];
EvalNow[1] += Xcef[1];
EvalNow[2] += Xcef[2];
EvalNow[3] += Xcef[3];
EvalNow[4] += Xcef[4];
EvalNow[5] += Xcef[5];
EvalNow[6] += Xcef[6];
}
EvalStart[0] += Ycef[0];
EvalStart[1] += Ycef[1];
EvalStart[2] += Ycef[2];
EvalStart[3] += Ycef[3];
EvalStart[4] += Ycef[4];
EvalStart[5] += Ycef[5];
EvalStart[6] += Ycef[6];
ntoprow = true;
}
return GZ_SUCCESS;
}
int GzPutTriangle(GzRender *render, int numParts, GzToken *nameList, GzPointer *valueList)
{
if ((render == NULL) || (render->open == 0)) return GZ_FAILURE;
GzCoord(*Vertex)[3] = NULL;
GzCoord(*Normal)[3] = NULL;
int status = 0;
while (numParts > 0)
{
numParts--;
switch (nameList[numParts])
{
case GZ_POSITION:
{
Vertex = (GzCoord(*)[3])valueList[numParts];
break;
}
case GZ_NORMAL:
{
Normal = (GzCoord(*)[3])valueList[numParts];
break;
}
default:
{
status |= GZ_FAILURE;
break;
}
}
}
if (Vertex != NULL)
{
GzDraw_Triangle_LEE(render, *Vertex, *Normal);
}
return status;
} | [
"lixy0926@gmail.com"
] | lixy0926@gmail.com |
8241cf37135785091c0d159bc7708106ff0c429e | 2231d1fe2e587713dcbe0f4f6d182b794ffaca9a | /src/Game/Dialog.cpp | 42bfdc0600e8d5b0878c37688978a89b6bff21d2 | [
"MIT"
] | permissive | adahera222/LD34-7 | 5852970a82c40620b0584fce59e266b52967dddf | 102d34f1f0e0893efb5c27674058fb0188621fdc | refs/heads/master | 2020-12-14T07:19:09.960880 | 2013-12-18T11:36:53 | 2013-12-18T11:36:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,479 | cpp | #include "Dialog.hpp"
#include "../Resources.hpp"
#include <Kunlaboro/EntitySystem.hpp>
const float gDistance = 96;
const float gHorizDistance = 128;
Dialog::Dialog(): Kunlaboro::Component("Game.Dialog"), mTime(0), mPosition(-10000, 10000)
{
}
Dialog::~Dialog()
{
}
void Dialog::addedToEntity()
{
auto has = getEntitySystem()->getAllComponentsOnEntity(getOwnerId(), "Game.Dialog").size();
if (has > 1)
getEntitySystem()->destroyComponent(this);
else
{
requestMessage("Event.Update", [this](const Kunlaboro::Message& msg)
{
float dt = boost::any_cast<float>(msg.payload);
mTime += dt;
auto reply = sendQuestion("Where am I?");
if (reply.handled)
{
mPosition = boost::any_cast<sf::Vector2f>(reply.payload);
}
if (mTime > 5.f)
{
getEntitySystem()->destroyComponent(this);
}
});
requestMessage("Event.Draw", [this](const Kunlaboro::Message& msg)
{
auto& target = *std::get<0>(boost::any_cast<std::tuple<sf::RenderTarget*,float>>(msg.payload));
sf::Text message(mMessage, Resources::Font_Dosis, 26U);
auto rect = message.getLocalBounds();
sf::RectangleShape box(sf::Vector2f(rect.width + 16, rect.height + 16));
sf::ConvexShape speechThingy(3);
speechThingy.setPoint(0, sf::Vector2f(rect.width * (1.f / 8.f), rect.height + 8));
speechThingy.setPoint(1, sf::Vector2f(0, rect.height + 8 + gDistance * (1.f/3.f)));
speechThingy.setPoint(2, sf::Vector2f(rect.width * (2.f/6.f), rect.height + 8));
float alpha = 0.f;
if (mTime > 4.f)
alpha = (mTime-4);
speechThingy.setFillColor(sf::Color(255,255,255,255-(255*alpha)));
box.setFillColor(sf::Color(255, 255, 255, 255 - (255*alpha)));
message.setColor(sf::Color(0, 0, 0, 255 - (255*alpha)));
message.setOrigin(-8, rect.height / 2.f + gDistance);
box.setOrigin(0, rect.height / 2.f + 8 + gDistance);
speechThingy.setOrigin(0, rect.height / 2.f + gDistance);
speechThingy.setPosition(mPosition);
message.setPosition(mPosition);
box.setPosition(mPosition);
target.draw(box);
target.draw(message);
target.draw(speechThingy);
});
}
} | [
"ace@haxalot.com"
] | ace@haxalot.com |
8a29d2fabc348905765cbbb6693247800a3b5b3d | 630a68871d4cdcc9dbc1f8ac8b44f579ff994ecf | /myodd/boost/libs/hana/example/struct/comparable.cpp | 9c053d98195cd69b4c13c09b6ef994df9afec8cc | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | FFMG/myoddweb.piger | b56b3529346d9a1ed23034098356ea420c04929d | 6f5a183940661bd7457e6a497fd39509e186cbf5 | refs/heads/master | 2023-01-09T12:45:27.156140 | 2022-12-31T12:40:31 | 2022-12-31T12:40:31 | 52,210,495 | 19 | 2 | MIT | 2022-12-31T12:40:32 | 2016-02-21T14:31:50 | C++ | UTF-8 | C++ | false | false | 740 | cpp | // Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <boost/hana/assert.hpp>
#include <boost/hana/define_struct.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/keys.hpp>
#include <boost/hana/not_equal.hpp>
#include <boost/hana/string.hpp>
#include <string>
namespace hana = boost::hana;
struct Person {
BOOST_HANA_DEFINE_STRUCT(Person,
(std::string, name),
(unsigned short, age)
);
};
int main() {
Person john{"John", 30}, kevin{"Kevin", 20};
BOOST_HANA_RUNTIME_CHECK(hana::equal(john, john));
BOOST_HANA_RUNTIME_CHECK(hana::not_equal(john, kevin));
}
| [
"github@myoddweb.com"
] | github@myoddweb.com |
de6e5e3866c7b9f1744406b7f66933fc8b58db4f | 17b18f105c49cd0c88871e87196e5427a0efc02a | /source/document.cpp | 3352887635e5734b447ff02c065ae3acf9796eaa | [] | no_license | EvgenLeontev/SearchSystem | 85bb5876a5f4f355fc997551914c15e6011d044f | 38ff0cefe544df0d98ccb6aa1ece62a0904a07e5 | refs/heads/main | 2023-06-29T11:18:16.268003 | 2021-08-03T11:15:07 | 2021-08-03T11:15:07 | 389,961,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 991 | cpp | #include "document.h"
using namespace std;
Document::Document(int id, double relevance, int rating)
: id(id)
, relevance(relevance)
, rating(rating)
{}
ostream& operator<<(ostream& out, const Document& document) {
out << "{ "s
<< "document_id = "s << document.id << ", "s
<< "relevance = "s << document.relevance << ", "s
<< "rating = "s << document.rating << " }"s;
return out;
}
void PrintDocument(const Document& document) {
cout << "{ "s
<< "document_id = "s << document.id << ", "s
<< "relevance = "s << document.relevance << ", "s
<< "rating = "s << document.rating << " }"s << endl;
}
void PrintMatchDocumentResult(int document_id, const vector<string_view>& words, DocumentStatus status) {
cout << "{ "s
<< "document_id = "s << document_id << ", "s
<< "status = "s << static_cast<int>(status) << ", "s
<< "words ="s;
for (const string_view word : words) {
cout << ' ' << string(word);
}
cout << "}"s << endl;
} | [
"60736388+240000@users.noreply.github.com"
] | 60736388+240000@users.noreply.github.com |
46209a52f729037d1ee0098217e4ea0cb9e91c0e | 9870e11c26c15aec3cc13bc910e711367749a7ff | /ZJ/zj_a_044.cpp | 8eac993b990e37243cea0902f46cd0a5a453e31f | [] | no_license | liuq901/code | 56eddb81972d00f2b733121505555b7c7cbc2544 | fcbfba70338d3d10bad2a4c08f59d501761c205a | refs/heads/master | 2021-01-15T23:50:10.570996 | 2016-01-16T16:14:18 | 2016-01-16T16:14:18 | 12,918,517 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 169 | cpp | #include <cstdio>
#include <cstdlib>
int main()
{
int n;
while (scanf("%d",&n)!=EOF)
printf("%d\n",(n-1)*(n*n+n+6)/6+2);
system("pause");
return(0);
}
| [
"liuq901@163.com"
] | liuq901@163.com |
76477be1013e4369424aa736eb7a00609524f0e5 | 34d9c27e1bd90e061c14395c4065b29ab0d817f6 | /ext/osgBullet/osgbCollision/BoundingCylinder.h | 4d94e88df95dce239e996eff4e4a5d1d706b4555 | [] | no_license | whztt07/test_osg | e03e7d3b200a522e67a6e66f02ef4b46fa1221fe | 2ed7c45420eaffc4585b8823e756bc71aafa75fb | refs/heads/master | 2021-01-15T09:25:06.161997 | 2016-07-12T20:02:04 | 2016-07-12T20:02:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,258 | h | /*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* osgBullet is (C) Copyright 2009-2012 by Kenneth Mark Bryden
*
* 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.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#ifndef __OSGBCOLLISION_BOUNDINGCYLINDER_H__
#define __OSGBCOLLISION_BOUNDINGCYLINDER_H__
#if 0
#include <osgbCollision/Export.h>
#else
#define OSGBCOLLISION_EXPORT
#endif
#include <osg/Vec3>
namespace osgbCollision
{
/** \class BoundingCylinder BoundingCylinder.h <osgbCollision/BoundingCylinder.h>
\brief Used internally to store cylinder parameters.
TBD Consider not encapsulating parameters in a class. */
class OSGBCOLLISION_EXPORT BoundingCylinder
{
public:
BoundingCylinder( void );
virtual ~BoundingCylinder( void );
void init()
{
length = radius = 0.0f;
}
void setAxis( const osg::Vec3 & a )
{
axis = a;
axis.normalize();
}
const osg::Vec3 & getAxis() const
{
return( axis );
}
void setRadius( float r )
{
radius = r;
}
float getRadius() const
{
return( radius );
}
void setLength( float l )
{
length = l;
}
float getLength() const
{
return( length );
}
void expandBy( const osg::Vec3& v );
void expandBy( float x,
float y,
float z );
void expandBy( const BoundingCylinder& bc );
protected:
float length;
float radius;
osg::Vec3 axis;
};
// osgbCollision
}
// __OSGBCOLLISION_BOUNDINGCYLINDER_H__
#endif
| [
"yaroslav.tarasov@gmail.com"
] | yaroslav.tarasov@gmail.com |
117b62489805b2245d27a9c6286929551c3d30fb | 2549e0ea4c920b50a987e4094e76842acd2bf57c | /NewHard_c_program_With_some_visual_studio/MYSTRTOK.CPP | db6d57a59a3a01f594b706cfca2c29349ce134d1 | [] | no_license | sultanularefin/old_c_programs | 1a221766add12a5f55c087fde8155e3a58e2f2c2 | 0d8bf8851ede46c060ec28bfe880a62dcd88e07e | refs/heads/master | 2023-07-15T07:40:32.490081 | 2021-08-19T01:07:30 | 2021-08-19T01:07:30 | 397,775,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | cpp | #include<stdio.h>
#include<conio.h>
char * mystrtok(char * str,const char * delimiter);
int main(void) {
char a[100]="my name is sultanul arefin one of my friend's name is similar to mine. ";
// clrscr();
char *token;
token=mystrtok(a," ");
printf("Token is ==> %s\n",token);
while(token) {
token=mystrtok(NULL," ");
if(token) printf("Token is ==> %s\n",token);
else printf("NULL\n");
}
printf("\n\n\n");
getch();
return 0;
}
char * mystrtok(char * str,const char * delimiter)
{
static char *s;
if(str)
{
int j=0;
char *p ;
p=&str[0];
s=&str[0];
while (str[j])
{
for(int i=0;delimiter[i];i++)
{
if(str[j] == delimiter[i])
{
str[j]='\0';
++j;
s=&str[j];
return p;
}
}
j++;
}
}
if(!str) //else //if
{
int j=0;
char *p;
char str1[100];
while(*s)
{
str1[j]=*s;
j++;
s++;
}
str1[j]='\0';
p=&str1[0];
j=0;
while (str1[j])
{
for(int i=0;delimiter[i];i++)
{
if(str1[j] == delimiter[i])
{
str1[j]='\0';
++j;
s=&str1[j];
return p;
}
}
j++;
}
}
return NULL;
}
| [
"arefin.nordecode@gmail.com"
] | arefin.nordecode@gmail.com |
84e0b649c52a879ab5090bc8b64da170bf971d95 | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/xdktest/cafe6/xtests/debugger/stress/Base/Dbg_Stress_Sub.h | 8b9e634a1b9aaab30265e1eacc2ae24d9a9fe654 | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | h | ///////////////////////////////////////////////////////////////////////////////
// Dbg_Stress_Sub.h
//
// Created by :
// Xbox XDK Test
//
// Description :
// Declaration of the CDbgStressSubSuite class
//
#ifndef __SNIFF_H__
#define __SNIFF_H__
#ifndef __STDAFX_H__
#error include 'stdafx.h' before including this file for PCH
#endif
///////////////////////////////////////////////////////////////////////////////
// CDbgStressSubSuite class
class CDbgStressSubSuite : public CIDESubSuite
{
public:
DECLARE_SUBSUITE(CDbgStressSubSuite)
//exeSubSuite() { m_strName = "TestWizard Generated script"; m_strOwner = "Xbox XDK Test"; }
DECLARE_TESTLIST()
protected:
void CleanUp(void);
};
#endif //__SNIFF_H__
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
61c5607c4d2605dd0808d98ba129ed54c8227601 | 6693c202f4aa960b05d7dfd0ac8e19a0d1199a16 | /Codeforces-Gym/101147 - 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)/D.cpp | 210bf5015d8b20aaf4d71b2f6600a3a109b3d00b | [] | no_license | eliogovea/solutions_cp | 001cf73566ee819990065ea054e5f110d3187777 | 088e45dc48bfb4d06be8a03f4b38e9211a5039df | refs/heads/master | 2020-09-11T11:13:47.691359 | 2019-11-17T19:30:57 | 2019-11-17T19:30:57 | 222,045,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 517 | cpp | // 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)
// 101147D
#include <bits/stdc++.h>
using namespace std;
const int N = 20;
int n, m;
long long c[N + 5][N + 5];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
freopen("popcorn.in", "r", stdin);
for (int i = 0; i <= N; i++) {
c[i][0] = c[i][i] = 1;
for (int j = 1; j < i; j++) {
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
}
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
cout << c[n][m] << "\n";
}
}
| [
"eliogovea1993@gmail.com"
] | eliogovea1993@gmail.com |
a2084a655be2b345aad46a9f79c91fb8a6df5445 | 4edd2d889ff0c2633c0675c91a00d8c52cf1e512 | /B3E7/src/main.cpp | 3e8caf406c33b36a141ee7f86fc4fcbf972945fe | [] | no_license | GermanSar/EjerciciosC | be252c9239c0b6f208005dd3d87a29c4ca18733a | c8877a89d1066ff5ebcd653d31c9c0ff4e485534 | refs/heads/main | 2023-03-16T09:16:37.371377 | 2021-03-08T22:22:59 | 2021-03-08T22:22:59 | 344,898,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 854 | cpp | /*7. Escriba un programa que solicite una edad (un entero) e indique en la
salida estándar si la edad introducida está en el rango [18-25].
#include<iostream>
using namespace std;
int main(){
int edad;
cout<<"Digite su edad: ";
cin>>edad;
if((edad>=18)&&(edad<=25)){
cout<<"Su edad esta en el rango de [18-25]";
}
else{
cout<<"Su edad esta fuera de rango";
}
return 0;
}
*/
#include <Arduino.h>
int edad;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println("Digite su edad: "); while(!Serial.available()){} edad = Serial.parseInt();
Serial.print(String(edad));
if((edad>=18)&&(edad<=25)){
Serial.println("Su edad esta en el rango de [18-25]: " + String(edad));
}
else{
Serial.println("Su edad esta fuera de rango: " + String(edad));
}
}
| [
"noreply@github.com"
] | noreply@github.com |
26055d81022ae0d1e7eab6bfa83f4c0188753df4 | 9d0c1da53da9e60d4a891d7edb7a02c31c8d26b9 | /libksieve/shared/error.cpp | c494801ddac7bc30b0e183975781318bbfb92ce7 | [] | no_license | serghei/kde3-kdepim | 7e6d4a0188c35a2c9c17babd317bfe3c0f1377d2 | a1980f1560de118f19f54a5eff5bae87a6aa4784 | refs/heads/master | 2021-01-17T10:03:14.624954 | 2018-11-04T21:31:00 | 2018-11-04T21:31:00 | 3,688,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,439 | cpp | /* -*- c++ -*-
error.cpp
This file is part of KSieve,
the KDE internet mail/usenet news message filtering library.
Copyright (c) 2002-2003 Marc Mutz <mutz@kde.org>
KSieve is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
KSieve 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config.h>
#include <ksieve/error.h>
#include <klocale.h> // i18n
#include <climits> // UINT_MAX
namespace KSieve {
const char *Error::typeToString(Type t)
{
switch(t)
{
#define CASE(x) case x: return #x
CASE(None);
CASE(Custom);
CASE(CRWithoutLF);
CASE(SlashWithoutAsterisk);
CASE(IllegalCharacter);
CASE(UnexpectedCharacter);
CASE(NoLeadingDigits);
CASE(NonCWSAfterTextColon);
CASE(NumberOutOfRange);
CASE(InvalidUTF8);
CASE(UnfinishedBracketComment);
CASE(PrematureEndOfMultiLine);
CASE(PrematureEndOfQuotedString);
CASE(PrematureEndOfStringList);
CASE(PrematureEndOfTestList);
CASE(PrematureEndOfBlock);
CASE(MissingWhitespace);
CASE(MissingSemicolonOrBlock);
CASE(ExpectedBlockOrSemicolon);
CASE(ExpectedCommand);
CASE(ConsecutiveCommasInStringList);
CASE(ConsecutiveCommasInTestList);
CASE(MissingCommaInTestList);
CASE(MissingCommaInStringList);
CASE(NonStringInStringList);
CASE(NonCommandInCommandList);
CASE(NonTestInTestList);
CASE(RequireNotFirst);
CASE(RequireMissingForCommand);
CASE(RequireMissingForTest);
CASE(RequireMissingForComparator);
CASE(UnsupportedCommand);
CASE(UnsupportedTest);
CASE(UnsupportedComparator);
CASE(TestNestingTooDeep);
CASE(BlockNestingTooDeep);
CASE(InvalidArgument);
CASE(ConflictingArguments);
CASE(ArgumentsRepeated);
CASE(CommandOrderingConstraintViolation);
CASE(IncompatibleActionsRequested);
CASE(MailLoopDetected);
CASE(TooManyActions);
#undef CASE
default:
return "<unknown>";
}
}
QString Error::asString() const
{
QString err;
switch(type())
{
case None:
return QString::null;
case Custom:
return mStringOne;
// Parse errors:
case CRWithoutLF:
err = i18n("Parse error: Carriage Return (CR) without Line Feed (LF)");
break;
case SlashWithoutAsterisk:
err = i18n("Parse error: Unquoted Slash ('/') without Asterisk ('*'). "
"Broken Comment?");
break;
case IllegalCharacter:
err = i18n("Parse error: Illegal Character");
break;
case UnexpectedCharacter:
err = i18n("Parse error: Unexpected Character, probably a missing space?");
break;
case NoLeadingDigits:
err = i18n("Parse error: Tag Name has leading Digits");
break;
case NonCWSAfterTextColon:
err = i18n("Parse error: Only whitespace and #comments may "
"follow \"text:\" on the same line");
break;
case NumberOutOfRange:
err = i18n("Parse error: Number out of Range (must be smaller than %1)").arg(UINT_MAX);
break;
case InvalidUTF8:
err = i18n("Parse error: Invalid UTF-8 sequence");
break;
case PrematureEndOfMultiLine:
err = i18n("Parse error: Premature end of Multiline String (did you forget the '.'?)");
break;
case PrematureEndOfQuotedString:
err = i18n("Parse error: Premature end of Quoted String (missing closing '\"')");
break;
case PrematureEndOfStringList:
err = i18n("Parse error: Premature end of String List (missing closing ']')");
break;
case PrematureEndOfTestList:
err = i18n("Parse error: Premature end of Test List (missing closing ')')");
break;
case PrematureEndOfBlock:
err = i18n("Parse error: Premature end of Block (missing closing '}')");
break;
case MissingWhitespace:
err = i18n("Parse error: Missing Whitespace");
break;
case MissingSemicolonOrBlock:
err = i18n("Parse error: Missing ';' or Block");
break;
case ExpectedBlockOrSemicolon:
err = i18n("Parse error: Expected ';' or '{', got something else");
break;
case ExpectedCommand:
err = i18n("Parse error: Expected Command, got something else");
break;
case ConsecutiveCommasInStringList:
err = i18n("Parse error: Trailing, Leading or Duplicate Commas in String List");
break;
case ConsecutiveCommasInTestList:
err = i18n("Parse error: Trailing, Leading or Duplicate Commas in Test List");
break;
case MissingCommaInStringList:
err = i18n("Parse error: Missing ',' between Strings in String List");
break;
case MissingCommaInTestList:
err = i18n("Parse error: Missing ',' between Tests in Test List");
break;
case NonCommandInCommandList:
err = i18n("Parse error: Expected Command, got something else");
break;
case NonStringInStringList:
err = i18n("Parse error: Only Strings allowed in String Lists");
break;
case NonTestInTestList:
err = i18n("Parse error: Only Tests allowed in Test Lists");
break;
// validity errors:
case RequireNotFirst:
err = i18n("\"require\" must be first command");
break;
case RequireMissingForCommand:
err = i18n("\"require\" missing for command \"%1\"").arg(mStringOne);
break;
case RequireMissingForTest:
err = i18n("\"require\" missing for test \"%1\"").arg(mStringOne);
break;
case RequireMissingForComparator:
err = i18n("\"require\" missing for comparator \"%1\"").arg(mStringOne);
break;
case UnsupportedCommand:
err = i18n("Command \"%1\" not supported").arg(mStringOne);
break;
case UnsupportedTest:
err = i18n("Test \"%1\" not supported").arg(mStringOne);
break;
case UnsupportedComparator:
err = i18n("Comparator \"%1\" not supported").arg(mStringOne);
break;
case TestNestingTooDeep:
err = i18n("Site Policy Limit Violation: Test nesting too deep (max. %1)").arg(mStringOne.toUInt());
break;
case BlockNestingTooDeep:
err = i18n("Site Policy Limit Violation: Block nesting too deep (max. %1)").arg(mStringOne.toUInt());
break;
case InvalidArgument:
err = i18n("Invalid Argument \"%1\" to \"%2\"").arg(mStringOne).arg(mStringTwo);
break;
case ConflictingArguments:
err = i18n("Conflicting Arguments: \"%1\" and \"%2\"").arg(mStringOne).arg(mStringTwo);
break;
case ArgumentsRepeated:
err = i18n("Argument \"%1\" Repeated").arg(mStringOne);
break;
case CommandOrderingConstraintViolation:
err = i18n("Command \"%1\" violates command ordering constraints").arg(mStringOne);
break;
// runtime errors:
case IncompatibleActionsRequested:
err = i18n("Incompatible Actions \"%1\" and \"%2\" requested").arg(mStringOne).arg(mStringTwo);
break;
case MailLoopDetected:
err = i18n("Mail Loop detected");
break;
case TooManyActions:
err = i18n("Site Policy Limit Violation: Too many Actions requested (max. %1)").arg(mStringOne.toUInt());
break;
default:
err = i18n("Unknown error");
break;
}
return err;
}
} // namespace KSieve
| [
"serghei.amelian@gmail.com"
] | serghei.amelian@gmail.com |
e953a2bebe754c2edb71d66df4e18d718928bf1c | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/crashpad/crashpad/util/misc/capture_context_test.cc | deeea9e3c280436bfa8bb713cb3989dff3db3645 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 3,753 | cc | // Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/misc/capture_context.h"
#include <stdint.h>
#include <algorithm>
#include "gtest/gtest.h"
#include "util/misc/address_sanitizer.h"
#include "util/misc/capture_context_test_util.h"
namespace crashpad {
namespace test {
namespace {
#if defined(OS_FUCHSIA)
// Fuchsia uses -fsanitize=safe-stack by default, which splits local variables
// and the call stack into separate regions (see
// https://clang.llvm.org/docs/SafeStack.html). Because this test would like to
// find an approximately valid stack pointer by comparing locals to the
// captured one, disable safe-stack for this function.
__attribute__((no_sanitize("safe-stack")))
#endif
void TestCaptureContext() {
NativeCPUContext context_1;
CaptureContext(&context_1);
{
SCOPED_TRACE("context_1");
ASSERT_NO_FATAL_FAILURE(SanityCheckContext(context_1));
}
// The program counter reference value is this function’s address. The
// captured program counter should be slightly greater than or equal to the
// reference program counter.
uintptr_t pc = ProgramCounterFromContext(context_1);
#if !defined(ADDRESS_SANITIZER)
// AddressSanitizer can cause enough code bloat that the “nearby” check would
// likely fail.
const uintptr_t kReferencePC =
reinterpret_cast<uintptr_t>(TestCaptureContext);
EXPECT_PRED2([](uintptr_t actual,
uintptr_t reference) { return actual - reference < 64u; },
pc,
kReferencePC);
#endif // !defined(ADDRESS_SANITIZER)
// Declare sp and context_2 here because all local variables need to be
// declared before computing the stack pointer reference value, so that the
// reference value can be the lowest value possible.
uintptr_t sp;
NativeCPUContext context_2;
// The stack pointer reference value is the lowest address of a local variable
// in this function. The captured program counter will be slightly less than
// or equal to the reference stack pointer.
const uintptr_t kReferenceSP =
std::min(std::min(reinterpret_cast<uintptr_t>(&context_1),
reinterpret_cast<uintptr_t>(&context_2)),
std::min(reinterpret_cast<uintptr_t>(&pc),
reinterpret_cast<uintptr_t>(&sp)));
sp = StackPointerFromContext(context_1);
EXPECT_PRED2([](uintptr_t actual,
uintptr_t reference) { return reference - actual < 768u; },
sp,
kReferenceSP);
// Capture the context again, expecting that the stack pointer stays the same
// and the program counter increases. Strictly speaking, there’s no guarantee
// that these conditions will hold, although they do for known compilers even
// under typical optimization.
CaptureContext(&context_2);
{
SCOPED_TRACE("context_2");
ASSERT_NO_FATAL_FAILURE(SanityCheckContext(context_2));
}
EXPECT_EQ(StackPointerFromContext(context_2), sp);
EXPECT_GT(ProgramCounterFromContext(context_2), pc);
}
TEST(CaptureContext, CaptureContext) {
ASSERT_NO_FATAL_FAILURE(TestCaptureContext());
}
} // namespace
} // namespace test
} // namespace crashpad
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
d060afc25b0f576b87d908f8f317c39e1a566b6c | 901ed391a0c2fb75c5364b6f075c87bbcb5edf0a | /uva12577.cpp | cd342ee9839fc8b44aa99b57a983a10dc4f972cd | [] | no_license | piash76/UVA | dec0103396fd133d6ec34803e2135910790d492a | ebaafacd4b09cebc00aed9fd58ce5a62e25599a3 | refs/heads/main | 2023-07-12T09:52:45.832507 | 2021-08-19T08:19:50 | 2021-08-19T08:19:50 | 354,215,725 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 488 | cpp | #include<bits/stdc++.h>
#include<string>
using namespace std;
int main()
{
int i=1;
string a="Hajj",b="Umrah",c;
while(1)
{
cin>>c;
if(c=="*")
{
break;
}
if(c==a)
{
cout<<"Case "<<i<<": Hajj-e-Akbar"<<endl;
i++;
}
else if(c==b)
{
cout<<"Case "<<i<<": Hajj-e-Asghar"<<endl;
i++;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
987c9df6fd794f64b72e13b6e6c00040e2ae1cf1 | f0129e941cd52280eb0aadcb8b8b59c491942918 | /source/VGP_ConsoleTest/stdafx.cpp | 695ccd80010799d6c4b9b97fb62927378546ca9f | [
"Apache-2.0"
] | permissive | letitvi/VideoGridPlayer | ea15bc46e1ffa5db201d6a08627e92edf76ebef5 | 5d419efb3cdd389c047031f39fe19326a14d8c28 | refs/heads/master | 2021-01-10T08:40:35.633718 | 2016-04-13T14:44:35 | 2016-04-13T14:44:35 | 55,423,215 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 333 | cpp | // stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다.
// VGP_ConsoleTest.pch는 미리 컴파일된 헤더가 됩니다.
// stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다.
#include "stdafx.h"
// TODO: 필요한 추가 헤더는
// 이 파일이 아닌 STDAFX.H에서 참조합니다.
| [
"revomania@outlook.com"
] | revomania@outlook.com |
509ab5f716f2bcae0949a51d2ebdbdd5c839415d | 354b4b4479ecc177c7e2a56168d6c948672be8a0 | /CCF/CCF2017-9-3JSON查询.cpp | 3668561966fa3dc87623f347878616a520a91760 | [] | no_license | TonyWu199/Algorithm_Practice | c8435d3061ea62b824a3f6fffe65bd94bcac0087 | a85c1e7673c26f5213e014e49b88680f691cbfe7 | refs/heads/master | 2022-05-01T18:11:42.158628 | 2022-04-28T09:01:44 | 2022-04-28T09:01:44 | 112,853,047 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24 | cpp |
using namespace std;
| [
"851260121@qq.com"
] | 851260121@qq.com |
fe7869b27ad1df9de832c3561a6be5395163ba3a | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/blink/renderer/core/css/properties/longhands/perspective_origin_custom.cc | e6a7c62ba1f6ffaf64db214edde3bbc6aee4d3c3 | [
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 2,391 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/css/properties/longhands/perspective_origin.h"
#include "third_party/blink/renderer/core/css/css_value_pair.h"
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
namespace CSSLonghand {
const CSSValue* PerspectiveOrigin::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumePosition(range, context,
CSSPropertyParserHelpers::UnitlessQuirk::kForbid,
base::Optional<WebFeature>());
}
bool PerspectiveOrigin::IsLayoutDependent(const ComputedStyle* style,
LayoutObject* layout_object) const {
return layout_object && layout_object->IsBox();
}
const CSSValue* PerspectiveOrigin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
Node* styled_node,
bool allow_visited_style) const {
if (layout_object) {
LayoutRect box;
if (layout_object->IsBox())
box = ToLayoutBox(layout_object)->BorderBoxRect();
return CSSValuePair::Create(
ZoomAdjustedPixelValue(
MinimumValueForLength(style.PerspectiveOriginX(), box.Width()),
style),
ZoomAdjustedPixelValue(
MinimumValueForLength(style.PerspectiveOriginY(), box.Height()),
style),
CSSValuePair::kKeepIdenticalValues);
} else {
return CSSValuePair::Create(
ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
style.PerspectiveOriginX(), style),
ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
style.PerspectiveOriginY(), style),
CSSValuePair::kKeepIdenticalValues);
}
}
} // namespace CSSLonghand
} // namespace blink
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
29e3b8fbd13a3c6d1d9a644d69e8202fe1def439 | de4ba05ade2ef91ef8e401df73194abee3c657d9 | /imam9ais/spoj/CRSCNTRY/CRSCNTRY-13446244.cpp | 7d045ef7b726f9e4922c537e502e5aeed1f72e57 | [] | no_license | IMAM9AIS/SPOJ_SOLUTIONS | bed576afb2b7cc0518162574f15bc2026ce75aa1 | d43481399696a8a7e4a52060a43b8d08f2272e41 | refs/heads/master | 2021-01-01T16:25:07.801813 | 2015-07-04T00:26:58 | 2015-07-04T00:26:58 | 38,515,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,212 | cpp | #include<bits/stdc++.h>
using namespace std;
int ar1[2002];
int ar2[2002];
int n;
int m;
int dp[2005][2005]={-1};
int lcs(int i,int j)
{
//cout<<"int"<<i<<" "<<j<<endl;
if(i>=n || j>=m)
{ dp[i][j]=-1;
return 0;
}
else if(ar1[i]==ar2[j])
{
if(dp[i+1][j+1]==-1)
dp[i+1][j+1]=lcs(i+1,j+1);
return (1+dp[i+1][j+1]);
}
else
{
if(dp[i+1][j]==-1)
dp[i+1][j]=lcs(i+1,j);
if(dp[i][j+1]==-1)
dp[i][j+1]=lcs(i,j+1);
return (max(dp[i+1][j],dp[i][j+1]));
}
}
int main()
{
int t;
scanf("%d",&t);
int maxdis=0;
int a;
while(t--)
{
scanf("%d",&a);
int k=0;
ar1[k++]=a;
while(1)
{
scanf("%d",&a);
if(a==0)break;
ar1[k++]=a;
}
n=k;k=0;
while(1)
{
scanf("%d",&a);
if(a==0)
{
m=k;
//cout<<n<<" "<<m<<endl;
int re=lcs(0,0);
memset(dp,-1,sizeof dp);
//cout<<re<<endl;
//for(int i=0;i<n;i++)
// cout<<ar1[i]<<" ";
// cout<<endl;
// for(int i=0;i<m;i++)
// cout<<ar2[i]<<" ";
// cout<<endl;
maxdis=max(re,maxdis);
k=0;
scanf("%d",&a);
if(a==0)
{
cout<<maxdis<<endl;maxdis=0;
break;
}
}
ar2[k++]=a;
}
}
}
| [
"imamkhursheed@gmail.com"
] | imamkhursheed@gmail.com |
89f8d14b76c1412900b67ad33d447865cf03d5ec | 43b17c6877fa6a2e24ce4d0bff806b1b09255cb0 | /include/Gwen/Renderers/OpenGL_DebugFont.h | 45e5449f8a3cd776cf9e335bc2315c0e054c0688 | [] | no_license | dabroz/gwen-plus | bf145419fbc908e9e317b99cf4c299b5cbee3dec | 42a024f43c4d5f152c8f2acff7360353d4060160 | refs/heads/master | 2016-09-06T19:40:07.590030 | 2012-01-13T22:30:48 | 2012-01-13T22:30:48 | 3,022,753 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 730 | h | /*
GWEN
Copyright (c) 2011 Facepunch Studios
See license in Gwen.h
*/
#ifndef GWEN_RENDERERS_OPENGL_DEBUGFONT_H
#define GWEN_RENDERERS_OPENGL_DEBUGFONT_H
#include "Gwen/Gwen.h"
#include "Gwen/Renderers/OpenGL.h"
namespace Gwen
{
namespace Renderer
{
class OpenGL_DebugFont : public Gwen::Renderer::OpenGL
{
public:
OpenGL_DebugFont();
~OpenGL_DebugFont();
void RenderText( Gwen::Font* pFont, Gwen::Point pos, const Gwen::UnicodeString& text );
Gwen::Point MeasureText( Gwen::Font* pFont, const Gwen::UnicodeString& text );
protected:
Gwen::Texture* m_pFontTexture;
float m_fFontScale[2];
float m_fLetterSpacing;
};
}
}
#endif
| [
"garrynewman@gmail.com@82b74e7c-beea-4a93-d681-cf472943600a"
] | garrynewman@gmail.com@82b74e7c-beea-4a93-d681-cf472943600a |
b4855852dc8b2828de0b545a975ca73a381f4880 | e1700081b3e9fa1c74e6dd903da767a3fdeca7f5 | /libs/gridcreatingcondition/poisson/poisson_pch.h | 202de13e45ff3a37c82ed88928b58eddd993a6cf | [
"MIT"
] | permissive | i-RIC/prepost-gui | 2fdd727625751e624245c3b9c88ca5aa496674c0 | 8de8a3ef8366adc7d489edcd500a691a44d6fdad | refs/heads/develop_v4 | 2023-08-31T09:10:21.010343 | 2023-08-31T06:54:26 | 2023-08-31T06:54:26 | 67,224,522 | 8 | 12 | MIT | 2023-08-29T23:04:45 | 2016-09-02T13:24:00 | C++ | UTF-8 | C++ | false | false | 1,217 | h | /* Add C includes here */
#if defined __cplusplus
/* Add C++ includes here */
#include <algorithm>
#include <memory>
#include <vector>
#include <QAction>
#include <QCoreApplication>
#include <QCursor>
#include <QDataStream>
#include <QDialog>
#include <QFile>
#include <QKeyEvent>
#include <QLocale>
#include <QMenu>
#include <QMessageBox>
#include <QPixmap>
#include <QPointF>
#include <QString>
#include <QtCore/qbytearray.h>
#include <QtCore/qglobal.h>
#include <QtCore/qmetatype.h>
#include <QtCore/QVariant>
#include <QThread>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QDoubleSpinBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QVBoxLayout>
#include <QUndoCommand>
#include <QVector2D>
#include <vtkActor.h>
#include <vtkActor2DCollection.h>
#include <vtkActorCollection.h>
#include <vtkCardinalSpline.h>
#include <vtkParametricSpline.h>
#include <vtkPolyData.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>
#include <vtkTextProperty.h>
#endif // __cplusplus
| [
"charlton@usgs.gov"
] | charlton@usgs.gov |
1a6a076eb07d473940f0557205db86993ba9db75 | 30a32533d9d745ce48290df8d07734d55a8039d7 | /src/rml/test/rml_omp_stub.cpp | eb701b17143058448aa0db743c99dbe896be06f8 | [
"Apache-2.0",
"Intel"
] | permissive | sol-ansano-kim/tbb | bf45b13e29789d61361d6192a47099443a87b226 | eb6336ad29450f2a64af5123ca1b9429ff6bc11d | refs/heads/tbb_2017 | 2020-06-29T06:28:50.462048 | 2017-06-07T07:54:02 | 2017-06-07T07:54:02 | 200,463,076 | 0 | 0 | Apache-2.0 | 2019-08-04T07:31:14 | 2019-08-04T07:31:14 | null | UTF-8 | C++ | false | false | 2,480 | cpp | /*
Copyright (c) 2005-2017 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This file is compiled with C++, but linked with a program written in C.
// The intent is to find dependencies on the C++ run-time.
#include <stdlib.h>
#include "../../../include/tbb/tbb_stddef.h" // __TBB_override
#include "harness_defs.h"
#define RML_PURE_VIRTUAL_HANDLER abort
#if _MSC_VER==1500 && !defined(__INTEL_COMPILER)
// VS2008/VC9 seems to have an issue;
#pragma warning( push )
#pragma warning( disable: 4100 )
#elif __TBB_MSVC_UNREACHABLE_CODE_IGNORED
// VS2012-2013 issues "warning C4702: unreachable code" for the code which really
// shouldn't be reached according to the test logic: rml::client has the
// implementation for the "pure" virtual methods to be aborted if they are
// called.
#pragma warning( push )
#pragma warning( disable: 4702 )
#endif
#include "rml_omp.h"
#if ( _MSC_VER==1500 && !defined(__INTEL_COMPILER)) || __TBB_MSVC_UNREACHABLE_CODE_IGNORED
#pragma warning( pop )
#endif
rml::versioned_object::version_type Version;
class MyClient: public __kmp::rml::omp_client {
public:
rml::versioned_object::version_type version() const __TBB_override {return 0;}
size_type max_job_count() const __TBB_override {return 1024;}
size_t min_stack_size() const __TBB_override {return 1<<20;}
rml::job* create_one_job() __TBB_override {return NULL;}
void acknowledge_close_connection() __TBB_override {}
void cleanup(job&) __TBB_override {}
policy_type policy() const __TBB_override {return throughput;}
void process( job&, void*, __kmp::rml::omp_client::size_type ) __TBB_override {}
};
//! Never actually set, because point of test is to find linkage issues.
__kmp::rml::omp_server* MyServerPtr;
#define HARNESS_NO_PARSE_COMMAND_LINE 1
#define HARNESS_CUSTOM_MAIN 1
#include "harness.h"
extern "C" void Cplusplus() {
MyClient client;
Version = client.version();
REPORT("done\n");
}
| [
"alexey.v.moskalev@intel.com"
] | alexey.v.moskalev@intel.com |
2a44349de0d2a64b155a38d07f70aba4828be160 | c2ee28873a2cbb0c9a319fd92cce6af2ff65ab41 | /Project1_Starter_Code/Token.cpp | f101937d1f1bf790d58f7b787162d2c985cf043f | [] | no_license | julianacsmith/project-1 | f0ae846447da91b6818a47f964974284117cbedd | a9b9fa8e5f2ec14e0c5617091d00f04bc5c16053 | refs/heads/master | 2023-07-18T15:33:10.896128 | 2021-09-06T15:00:42 | 2021-09-06T15:00:42 | 403,662,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | cpp | #include "Token.h"
Token::Token(TokenType type, std::string description, int line) {
// TODO: initialize all member variables
}
| [
"clarinetplayer2020@gmail.com"
] | clarinetplayer2020@gmail.com |
be1508d17b1b030b156db5ce46143881d0d8a932 | d89df4cf6e89529f91db28115059278b6691e77b | /src/vendors/OceanOptics/features/spectrometer/JazSpectrometerFeature.cpp | 8818addd5f8d48b5e6a4dc614160092478eff0c2 | [
"MIT"
] | permissive | udyni/seabreeze | d31f1abeac5489929318ca9406b6e2064eb1e197 | 3d3934f8f0df61c11cef70516cf62a8472cab974 | refs/heads/master | 2021-03-23T12:46:31.498576 | 2020-04-06T15:01:14 | 2020-04-06T15:01:14 | 247,455,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,543 | cpp | /***************************************************//**
* @file JazSpectrometerFeature.cpp
* @date November 2011
* @author Ocean Optics, Inc.
*
* LICENSE:
*
* SeaBreeze Copyright (C) 2014, Ocean Optics Inc
*
* 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.
*******************************************************/
#include "common/globals.h"
#include "vendors/OceanOptics/features/spectrometer/JazSpectrometerFeature.h"
#include "vendors/OceanOptics/protocols/ooi/exchanges/IntegrationTimeExchange.h"
#include "vendors/OceanOptics/protocols/ooi/exchanges/ReadSpectrumExchange.h"
#include "vendors/OceanOptics/protocols/ooi/exchanges/JazSpectrumExchange.h"
#include "vendors/OceanOptics/protocols/ooi/exchanges/RequestSpectrumExchange.h"
#include "vendors/OceanOptics/protocols/ooi/exchanges/TriggerModeExchange.h"
#include "vendors/OceanOptics/protocols/ooi/impls/OOISpectrometerProtocol.h"
using namespace seabreeze;
using namespace ooiProtocol;
const long JazSpectrometerFeature::INTEGRATION_TIME_MINIMUM = 1000;
const long JazSpectrometerFeature::INTEGRATION_TIME_MAXIMUM = 655350000;
const long JazSpectrometerFeature::INTEGRATION_TIME_INCREMENT = 1000;
const long JazSpectrometerFeature::INTEGRATION_TIME_BASE = 1;
JazSpectrometerFeature::JazSpectrometerFeature(
ProgrammableSaturationFeature *saturationFeature)
: GainAdjustedSpectrometerFeature(saturationFeature) {
this->numberOfPixels = 2048;
this->numberOfBytesPerPixel = sizeof(unsigned short);
this->maxIntensity = 65535;
this->integrationTimeMinimum = JazSpectrometerFeature::INTEGRATION_TIME_MINIMUM;
this->integrationTimeMaximum = JazSpectrometerFeature::INTEGRATION_TIME_MAXIMUM;
this->integrationTimeBase = JazSpectrometerFeature::INTEGRATION_TIME_BASE;
this->integrationTimeIncrement = JazSpectrometerFeature::INTEGRATION_TIME_INCREMENT;
for(int i = 2; i < 24; i++) {
this->electricDarkPixelIndices.push_back(i);
}
IntegrationTimeExchange *intTime = new IntegrationTimeExchange(JazSpectrometerFeature::INTEGRATION_TIME_BASE);
Transfer *requestFormattedSpectrum = new RequestSpectrumExchange();
Transfer *readFormattedSpectrum = new JazSpectrumExchange(this->numberOfPixels * 2, this->numberOfPixels, this);
Transfer *requestUnformattedSpectrum = new RequestSpectrumExchange();
Transfer *readUnformattedSpectrum = new ReadSpectrumExchange(this->numberOfPixels * 2, this->numberOfPixels);
Transfer *requestFastBufferSpectrum = new RequestSpectrumExchange();
Transfer *readFastBufferSpectrum = new ReadSpectrumExchange(this->numberOfPixels * 2, this->numberOfPixels);
TriggerModeExchange *triggerMode = new TriggerModeExchange();
OOISpectrometerProtocol *ooiProtocol = new OOISpectrometerProtocol(intTime, requestFormattedSpectrum, readFormattedSpectrum,
requestUnformattedSpectrum, readUnformattedSpectrum, requestFastBufferSpectrum, readFastBufferSpectrum, triggerMode);
this->protocols.push_back(ooiProtocol);
this->triggerModes.push_back(
new SpectrometerTriggerMode(SPECTROMETER_TRIGGER_MODE_NORMAL));
this->triggerModes.push_back(
new SpectrometerTriggerMode(SPECTROMETER_TRIGGER_MODE_SOFTWARE));
this->triggerModes.push_back(
new SpectrometerTriggerMode(SPECTROMETER_TRIGGER_MODE_SYNCHRONIZATION));
this->triggerModes.push_back(
new SpectrometerTriggerMode(SPECTROMETER_TRIGGER_MODE_HARDWARE));
}
JazSpectrometerFeature::~JazSpectrometerFeature() {
}
| [
"michele.devetta@cnr.it"
] | michele.devetta@cnr.it |
a287cd33b5f5c22c67ce80e59a3a9f4ccbc460c3 | 3f24a6811b01df8ec359de33957b00a696a915d4 | /parser_generator/grammatic.h | bf7d7e06d54e06052e462ca439732d94c9fb4cc3 | [] | no_license | evgeniyfeder/parser_generator | fd741b54321b882b44fb585d22ea08c085909eb8 | 2aa6d0e673c0808cae62c2fe236c6ff3138a48f6 | refs/heads/master | 2020-04-19T18:08:56.348685 | 2019-07-13T18:54:05 | 2019-07-13T18:54:05 | 168,354,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,371 | h | #ifndef __GRAMMATIC_H_
#define __GRAMMATIC_H_
#include <unordered_map>
#include <unordered_set>
#include <filesystem>
#include "types.h"
class grammatic_t {
public:
grammatic_t() = default;
grammatic_t(std::string const & start);
grammatic_t & add_term(term_t const & term, bool skip = false);
grammatic_t & add_non_term(non_term_t && non_term);
grammatic_t & set_header(std::string const & header);
grammatic_t & set_start(std::string const & start);
void finish(std::filesystem::path const & directory);
private:
void count_first();
void count_follow();
void generate_parser(std::filesystem::path const & directory);
void generate_lexer(std::filesystem::path const & directory);
std::unordered_set<std::string> get_first_terms(rule_t const &rule, size_t index, bool count_first = false);
int32_t find_rule(const std::string & first_name, non_term_ptr const & nterm);
void print_rule(const rule_t & rule, std::ofstream & cpp_file);
private:
std::string start;
std::string header;
std::unordered_map<std::string, non_term_ptr> non_terms;
std::unordered_map<std::string, term_ptr> terms;
std::unordered_set<std::string> skips;
std::unordered_map<std::string, std::unordered_set<std::string>> first;
std::unordered_map<std::string, std::unordered_set<std::string>> follow;
};
#endif // __GRAMMATIC_H_
| [
"evgeniyfeder@github.com"
] | evgeniyfeder@github.com |
f386b3216cb955fd46492b48180a917983a457c9 | 62474567e3959aa8cb2cc6c3b0280ee5f8bf769f | /examples/OPAtomReader/OPAtomContentPackage.cpp | 632c7ca088fd83d2b3120887bd2e0da80198db85 | [
"BSD-3-Clause"
] | permissive | Limecraft/ebu-libmxfpp | 5e184c53845b1b4870b017f34b703574ae2814a3 | 8148d928a13c13738dcc95c328c3609322d67203 | refs/heads/master | 2021-07-05T18:11:29.508659 | 2021-05-31T13:43:56 | 2021-05-31T13:43:56 | 5,097,979 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,175 | cpp | /*
* Holds the essence data for each track in the clip
*
* Copyright (C) 2009, British Broadcasting Corporation
* All Rights Reserved.
*
* Author: Philip de Nier
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the British Broadcasting Corporation nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <libMXF++/MXFException.h>
#include "OPAtomContentPackage.h"
using namespace std;
using namespace mxfpp;
OPAtomContentElement::OPAtomContentElement()
{
mIsPicture = true;
mMaterialTrackId = 0;
mEssenceOffset = 0;
}
OPAtomContentPackage::OPAtomContentPackage()
{
mPosition = 0;
}
OPAtomContentPackage::~OPAtomContentPackage()
{
size_t i;
for (i = 0; i < mEssenceDataVector.size(); i++)
delete mEssenceDataVector[i];
// mEssenceData contains copies of content elements
}
bool OPAtomContentPackage::HaveEssenceData(uint32_t mp_track_id) const
{
return GetEssenceData(mp_track_id, false) != 0;
}
const OPAtomContentElement *OPAtomContentPackage::GetEssenceData(uint32_t mp_track_id) const
{
return GetEssenceData(mp_track_id, true);
}
const unsigned char *OPAtomContentPackage::GetEssenceDataBytes(uint32_t mp_track_id) const
{
const OPAtomContentElement *element = GetEssenceData(mp_track_id);
return element->GetBytes();
}
uint32_t OPAtomContentPackage::GetEssenceDataSize(uint32_t mp_track_id) const
{
const OPAtomContentElement *element = GetEssenceData(mp_track_id);
return element->GetSize();
}
const OPAtomContentElement *OPAtomContentPackage::GetEssenceDataI(size_t index) const
{
MXFPP_ASSERT(index < mEssenceDataVector.size());
return mEssenceDataVector[index];
}
const unsigned char *OPAtomContentPackage::GetEssenceDataIBytes(size_t index) const
{
const OPAtomContentElement *element = GetEssenceDataI(index);
return element->GetBytes();
}
uint32_t OPAtomContentPackage::GetEssenceDataISize(size_t index) const
{
const OPAtomContentElement *element = GetEssenceDataI(index);
return element->GetSize();
}
OPAtomContentElement* OPAtomContentPackage::GetEssenceData(uint32_t mp_track_id, bool check) const
{
map<uint32_t, OPAtomContentElement*>::const_iterator result = mEssenceData.find(mp_track_id);
if (result == mEssenceData.end()) {
if (check)
MXFPP_ASSERT(result != mEssenceData.end());
return 0;
}
return result->second;
}
OPAtomContentElement* OPAtomContentPackage::AddElement(uint32_t mp_track_id)
{
MXFPP_ASSERT(!GetEssenceData(mp_track_id, false));
mEssenceDataVector.push_back(new OPAtomContentElement());
mEssenceData[mp_track_id] = mEssenceDataVector.back();
return GetEssenceData(mp_track_id, true);
}
| [
"philipn@users.sourceforge.net"
] | philipn@users.sourceforge.net |
8c3475643194b4139fb96527308331de3e11af53 | 03295b1f28566523d090eaab2d6f49d0e4e5b6a8 | /Test/Test_char.cpp | 751bd10a1ae5ee683d74c6ac724b289f581d84c5 | [] | no_license | kleinsbotle/LinkedList | e42a9f99b6ef9d2f6d4e5f9e060bad86cf7da99a | b4b405717998e6087b6e83b59e42be2b47b51f50 | refs/heads/master | 2020-04-29T19:35:27.285065 | 2019-04-06T19:04:38 | 2019-04-06T19:04:38 | 176,360,239 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,078 | cpp | //
// Created by efg on 04.03.2019.
//
#include "List.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using testing::Eq;
namespace{
class ListTest : public ::testing::Test{
public:
List<char>* list;
ListTest(){
list = new List<char>;
}
};
}
TEST_F(ListTest, IsEmpty) {
EXPECT_TRUE(list->is_empty());
}
TEST_F(ListTest, IsEmpty_false){
list->push_front('a');
EXPECT_FALSE(list->is_empty());
}
TEST_F(ListTest, GetSize_empty){
EXPECT_EQ(0, list->get_size());
}
TEST_F(ListTest, GetSize){
list->push_front('a');
list->push_front('b');
list->push_front('c');
list->push_front('d');
EXPECT_EQ(4, list->get_size());
}
TEST_F(ListTest, At_empty){
try{
list->at(1);
}
catch(std::length_error &except){
EXPECT_THAT(std::string(except.what()), Eq("The list is empty"));
}
}
TEST_F(ListTest, At) {
list->push_front('d');
list->push_front('c');
list->push_front('b');
list->push_front('a');
EXPECT_EQ('d', list->at(3));
}
TEST_F(ListTest, At_WrongIndex){
list->push_front('a');
try{
list->at(5);
}
catch(std::out_of_range &except){
EXPECT_THAT(std::string(except.what()), Eq("Incorrect index"));
}
}
TEST_F(ListTest, PushFront_empty){
list->push_front('a');
EXPECT_EQ('a', list->at(0));
}
TEST_F(ListTest, PushBack_empty){
list->push_back('a');
EXPECT_EQ('a', list->at(0));
}
TEST_F(ListTest, PushFront){
list->push_back('b');
list->push_front('a');
EXPECT_EQ('a', list->at(0));
}
TEST_F(ListTest, PushBack){
list->push_front('a');
list->push_back('b');
EXPECT_EQ('b', list->at(1));
}
TEST_F(ListTest, PopBack_empty){
try{
list->pop_back();
}
catch(std::length_error &except){
EXPECT_THAT(std::string(except.what()), Eq("The list is empty"));
}
}
TEST_F(ListTest, PopFront_empty){
try{
list->pop_front();
}
catch(std::length_error &except){
EXPECT_THAT(std::string(except.what()), Eq("The list is empty"));
}
}
TEST_F(ListTest, PopBack_1){
list->push_front('a');
list->pop_back();
EXPECT_TRUE(list->is_empty());
}
TEST_F(ListTest, PopFront_1){
list->push_back('a');
list->pop_front();
EXPECT_TRUE(list->is_empty());
}
TEST_F(ListTest, PopBack){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->pop_back();
EXPECT_EQ('c', list->at(2));
}
TEST_F(ListTest, PopFront){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->pop_front();
EXPECT_EQ('b', list->at(0));
}
TEST_F(ListTest, Insert_empty){
try{
list->insert(1, 'a');
}
catch(std::length_error &except){
EXPECT_THAT(std::string(except.what()), Eq("The list is empty"));
}
}
TEST_F(ListTest, Insert_WrongIndex){
list->push_front('a');
try{
list->insert(5, 'b');
}
catch(std::out_of_range &except){
EXPECT_THAT(std::string(except.what()), Eq("Incorrect index"));
}
}
TEST_F(ListTest, Insert_first){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->insert(0, 'z');
EXPECT_EQ('z', list->at(0));
}
TEST_F(ListTest, Insert){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->insert(2, 'z');
EXPECT_EQ('z', list->at(2));
}
TEST_F(ListTest, Remove_first){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->remove(0);
EXPECT_EQ('b', list->at(0));
}
TEST_F(ListTest, Remove_last){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->remove(3);
EXPECT_EQ('c', list->at(2));
}
TEST_F(ListTest, Remove){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->push_back('e');
list->remove(2);
EXPECT_EQ('d', list->at(2));
}
TEST_F(ListTest, Clear){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->clear();
EXPECT_TRUE(list->is_empty());
}
TEST_F(ListTest, Set_empty){
try{
list->set(2, 'a');
}
catch(std::length_error &except){
EXPECT_THAT(std::string(except.what()), Eq("The list is empty"));
}
}
TEST_F(ListTest, Set_wrong_index){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
try{
list->set(5, 'z');
}
catch(std::out_of_range &except){
EXPECT_THAT(std::string(except.what()), Eq("Incorrect index"));
}
}
TEST_F(ListTest, Set){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->set(2, 'f');
EXPECT_EQ('f', list->at(2));
}
TEST_F(ListTest, Set_first){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->set(0, 'g');
EXPECT_EQ('g', list->at(0));
}
TEST_F(ListTest, Set_last){
list->push_back('a');
list->push_back('b');
list->push_back('c');
list->push_back('d');
list->set(3, 'x');
EXPECT_EQ('x', list->at(3));
}
TEST_F(ListTest, Remove_empty){
try{
list->remove(1);
}
catch(std::length_error &except){
EXPECT_THAT(std::string(except.what()), Eq("The list is empty"));
}
}
TEST_F(ListTest, Remove_wrong_index){
list->push_front('a');
try{
list->remove(2);
}
catch(std::out_of_range &except){
EXPECT_THAT(std::string(except.what()), Eq("Incorrect index"));
}
}
| [
"ostenok@gmail.com"
] | ostenok@gmail.com |
cb05e79965f83f039bdc8a0133d2e8da2830474f | bf4ebec70d8331e7c4612d093bfa77ff1f3b9e01 | /utils/procedureresult.cpp | 05ebf8ad17bafaf2e4c98a0e5b19c7dd7edfbf04 | [] | no_license | VIPERWorld/Animation-Retargeter-Qt-Port | 8919e9f73a0142d850d389024d0fce64e74a0c90 | 7e0bb5bacc7de7f49618934b37748a5cd8b1fd2e | refs/heads/master | 2021-01-01T04:33:11.131845 | 2016-06-12T18:17:03 | 2016-06-12T18:17:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cpp | #include "procedureresult.h"
ProcedureResult::ProcedureResult(bool outcome, QString message):
result(outcome), errorMessage(message)
{
}
void ProcedureResult::setMessage(QString message){
errorMessage = message;
}
bool ProcedureResult::getResult()
{
return result;
}
QString ProcedureResult::getMessage(){
return errorMessage;
}
| [
"alex.handby@gmail.com"
] | alex.handby@gmail.com |
9ac29b5d5d4cef3bba5810124f79e72b55e01676 | 02b187d56a2c6a71480135fcc4d24d0903c37ebe | /Baekjoon/27866.cpp | b229d84e13f91afe1de52c580da737e7e9b0aaa3 | [] | no_license | mbkim95/Algorithm | 13fdab15746dbeddd147986a56f4452430cc5963 | 5cb9ad2a8af9079725782b98ed068c711501f596 | refs/heads/master | 2023-04-27T20:33:04.569574 | 2023-04-16T02:50:50 | 2023-04-16T02:50:50 | 154,241,473 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | cpp | #include <iostream>
using namespace std;
int main() {
string s;
int i;
cin >> s;
cin >> i;
cout << s[i-1] << '\n';
return 0;
} | [
"mbkim95@naver.com"
] | mbkim95@naver.com |
887872459552e04576027870287c4ca907676e82 | ed3bba176334177b83840729a26af3768d87563e | /PA1/1_gaussian_smoothing/src/2D_Gaussian_Smoothing_1_mask.cpp | 6a801aae2e34626c5c0662fb1fd25ab04be80501 | [] | no_license | mwiegant/CS485_Computer_Vision | b9cf3d975a583b354a812af30e04441e887dbe14 | 34b276f1ce7e3402fdf23532d71939b69571684b | refs/heads/master | 2021-06-13T16:55:32.783616 | 2017-04-18T16:23:11 | 2017-04-18T16:23:11 | 82,478,452 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,006 | cpp | #include <fstream>
#include "Gauss_masks.c"
#include "ReadImage.cpp"
#include "WriteImage.cpp"
using namespace std;
namespace Gauss_2D_1Mask {
/* function prototypes */
void performSmoothing(int*** dataIn, int** dataOut, int& numRows, int& numColumns, int maskSize, float** mask);
void performNormalization(int** dataOut, int& numRows, int& numColumns, int& maxGreyValue);
string buildOutputFilename(string& filepath, int& sigma);
/*
* Performs 2D Gaussian Smoothing by calling helper functions to perform
* the various steps required.
*
* If any step fails, an error is returned.
*/
void perform2D_Gaussian_Smoothing_1_mask(int sigma, string pathToImage)
{
int returnStatus = 0;
int maskSize = 5 * sigma;
float** mask;
int*** dataIn;
int** dataOut;
int numRows, numColumns, maxGreyValue;
// allocate space for the mask
mask = new float*[maskSize];
for(int i = 0; i < maskSize; i++)
{
mask[i] = new float[maskSize];
}
// calculate the mask
Gauss_2D_mask( (float) sigma, maskSize, maskSize, mask );
// extract all data from the file
ReadImage(pathToImage.c_str(), dataIn, numRows, numColumns, maxGreyValue);
// allocate space for dataOut
dataOut = new int*[numColumns];
for(int i = 0; i < numColumns; i++)
{
dataOut[i] = new int[numRows];
}
// perform smoothing across the data
performSmoothing(dataIn, dataOut, numRows, numColumns, maskSize, mask);
// normalize the data
// performNormalization(dataOut, numRows, numColumns, maxGreyValue);
// adjust the output file name
pathToImage = buildOutputFilename(pathToImage, sigma);
// output results into a new file
WriteImage(pathToImage.c_str(), dataOut, numRows, numColumns, maxGreyValue);
}
/*
* Does the actual smoothing operation, taking the values from several pixels
* and combining them into a new value for each pixel. The output pixel data is
* stored inside the "dataOut" parameter, which is passed by reference.
*/
void performSmoothing(int*** dataIn, int** dataOut, int& numRows, int& numColumns, int maskSize, float** mask)
{
int currentX, startIndexX, endIndexX, maskIndexX;
int currentY, startIndexY, endIndexY, maskIndexY;
float sum;
// loop through all the data in dataIn
for(currentX = 0; currentX < numRows; currentX++)
{
for(currentY = 0; currentY < numColumns; currentY++)
{
// generate the start and end indices
startIndexX = currentX - (maskSize / 2);
endIndexX = currentX + (maskSize / 2);
startIndexY = currentY - (maskSize / 2);
endIndexY = currentY + (maskSize / 2);
// set sum to 0
sum = 0;
// loop from the start index to the end index
for(int indexX = startIndexX, maskIndexX = 0; indexX <= endIndexX; indexX++, maskIndexX++)
{
for(int indexY = startIndexY, maskIndexY = 0; indexY <= endIndexY; indexY++, maskIndexY++)
{
// check if the current index is a valid index (meaning the index is actually inside the image)
if( (indexX >= 0 && indexX < numRows) && (indexY >= 0 && indexY < numColumns) )
{
// increment sum with value at dataIn[indexY][indexX] * mask[maskIndexY][maskIndexX]
sum += ( (*dataIn)[indexY][indexX] * mask[maskIndexY][maskIndexX] );
}
}
}
// push sum into dataOut
dataOut[currentY][currentX] = (int) sum;
}
}
}
/*
* Performs normalization across the data that will be written to file. This ensures that
* every pixel value falls in the acceptable range.
*/
void performNormalization(int** dataOut, int& numRows, int& numColumns, int& maxGreyValue)
{
int minimumValue = 0;
int denominator = maxGreyValue - minimumValue;
int value;
// loop through all pixels
for(int x = 0; x < numRows; x++)
{
for(int y = 0; y < numColumns; y++)
{
value = dataOut[y][x];
// apply mathematical transformation to each pixel value
dataOut[y][x] = (value - minimumValue) / denominator;
}
}
}
/*
* Builds the output filename.
*/
string buildOutputFilename(string& filepath, int& sigma)
{
string outputString = "";
int strlength = filepath.length();
int i = 0;
// copy the entire string until a "." is reached
while( filepath[i] != '.')
{
outputString += filepath[i];
i++;
}
// insert special text into filepath
outputString += "_sigma=" + to_string(sigma) + "_1_2D-mask";
// finish copying filepath into the output string
for(i; i < strlength; i++)
{
outputString += filepath[i];
}
return outputString;
}
}
| [
"mwiegant@bombora.com"
] | mwiegant@bombora.com |
b0548c1bf726ef87f16c1d649135f6c580d48793 | b0f147044ccbcd5b8dfa3de8efc04dac9f1af6bc | /include/view/MapView.hpp | 33b323b54986b5f5cec854b78e35baf8a1a09cbb | [] | no_license | LedLoaf/Soldier-Survival | 596902384324846c0d4ffeba8670d412f31c5425 | 86967b1bd11b019e5a983c0719a0f52571d80185 | refs/heads/master | 2021-01-16T00:42:37.991681 | 2013-01-30T17:54:33 | 2013-01-30T17:54:33 | 99,975,293 | 1 | 0 | null | 2017-08-11T00:22:15 | 2017-08-11T00:22:15 | null | UTF-8 | C++ | false | false | 2,364 | hpp | #ifndef MAP_VIEW_HPP_
#define MAP_VIEW_HPP_
#include <SFML/System/Thread.hpp>
#include <SFML/System/Mutex.hpp>
#include <view/View.hpp>
#include <view/model/MapViewModel.hpp>
#include <util/Location.hpp>
#include <game/WarManager.hpp>
#include "WarView.hpp"
#include <game/object/weapon/Bomb.hpp>
namespace game {
class MapObject;
class Character;
class Player;
class BombManager;
}
namespace view {
class WarView;
class MapView : public View {
friend class CharactersAnimator;
private:
MapViewModel* mapViewModel;
game::WarManager* warManager;
game::BombManager* bombManager;
sf::Mutex mapViewModelMutex;
public:
MapView(int xStart, int yStart, int xEnd, int yEnd);
~MapView();
virtual Type getType();
MapViewModel* getModel();
static int getDistanceBetween(util::Location::Position firstCharacterPosition, util::Location::Position secondCharacterPosition);
bool areColliding(game::Character* firstCharacter, game::Character* secondCharacter);
void moveCharacter(game::Character* ch, util::Location::Vector vector);
void moveCharacter(game::Player* player, util::Location::Vector vector);
bool canMoveCharacter(game::Character* ch, util::Location::Vector vector);
bool isPositionInMapArea(util::Location::Position position);
bool canCharacterStayOnNMMO(game::MapObject* notMovingMapObject);
void setModel(MapViewModel* mapModel);
void setWarManager(game::WarManager* warManager);
void startWar(game::War* war);
void stopWar(game::War* war);
void tryToPlantBomb();
void putBomb(util::Location::Position position, game::Bomb* bomb);
void removeBomb(util::Location::Position position);
bool checkIfBombHasBeenPlanted();
void beginCharactersLife();
void showDeathOf(game::Character* ch);
void buryCharacter(game::Character * ch);
game::Player* getPlayer();
virtual void pause();
virtual void resume();
private:
util::Location::Position* getPlaceToPlantBomb();
class CharactersAnimator : public sf::Thread {
public:
CharactersAnimator(MapView* mapView);
virtual void Run();
bool stillWorking();
private:
MapView* mapView;
MapViewModel* mapViewModel;
bool isWorking;
};
};
}
#endif
| [
"yet1@hornet.(none)"
] | yet1@hornet.(none) |
90db3709e25e980d258b374a52f680e0071ad1c0 | ad715f9713dc5c6c570a5ac51a18b11932edf548 | /tensorflow/compiler/mlir/tfrt/benchmarks/benchmark.cc | cf6e8327ee94b2b0f8f4c995f19eeac04398f18f | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | rockzhuang/tensorflow | f1f31bc8edfa402b748c500efb97473c001bac95 | cb40c060b36c6a75edfefbc4e5fc7ee720273e13 | refs/heads/master | 2022-11-08T20:41:36.735747 | 2022-10-21T01:45:52 | 2022-10-21T01:45:52 | 161,580,587 | 27 | 11 | Apache-2.0 | 2019-01-23T11:00:44 | 2018-12-13T03:47:28 | C++ | UTF-8 | C++ | false | false | 6,043 | cc | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/tfrt/benchmarks/benchmark.h"
#include <string>
#include "mlir/Dialect/Bufferization/Transforms/Bufferize.h"
#include "mlir/ExecutionEngine/CRunnerUtils.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/Support/FileUtilities.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/IR/BuiltinTypes.h" // from @llvm-project
#include "tensorflow/compiler/xla/mlir/transforms/runtime/compiler.h"
#include "tensorflow/core/platform/logging.h"
#include "tfrt/jitrt/jitrt_compiler.h" // from @tf_runtime
#include "tfrt/host_context/concurrent_work_queue.h" // from @tf_runtime
#include "tfrt/host_context/host_allocator.h" // from @tf_runtime
namespace tensorflow {
using ::tfrt::HostContext;
using ::tfrt::jitrt::CompilationPipelineOptions;
using ::xla::runtime::MemrefType;
const bool kStaticDim = false;
const bool kDynamicDim = true;
mlir::LogicalResult FreeReturnedMemref(const ResultConversionCtx& ctx,
RemainingResults results,
unsigned result_index, const Type* type,
const Type* runtime_type,
void* result_ptr) {
DCHECK(llvm::isa<MemrefType>(runtime_type)) << "expected memref result";
// Cast result to the arbitrary chosen memref type and rank because we only
// need to know the base pointer value.
auto* memref = static_cast<StridedMemRefType<float, 0>*>(result_ptr);
if (llvm::find(ctx.input_ptrs, memref->data) == ctx.input_ptrs.end()) {
free(memref->basePtr);
}
return mlir::success();
}
JitExecutable& CreateJitExecutable(
const HostContext& host, llvm::StringRef mlir_input,
llvm::StringRef function_name, bool lower_from_tensorflow,
const TfJitRtPipelineOptions& tf_jitrt_opts) {
// Options for the default JitRt compilation pipeline (lowering to LLVM).
CompilationPipelineOptions copts;
copts.alignment = EIGEN_MAX_ALIGN_BYTES;
copts.num_worker_threads = host.GetNumWorkerThreads();
JitExecutable::Options opts;
opts.compiler.register_dialects =
[](xla::runtime::DialectRegistry& dialects) {
mlir::RegisterAllTensorFlowDialects(*dialects);
tfrt::jitrt::RegisterDefaultJitRtDialects(dialects);
};
opts.compiler.create_compilation_pipeline =
[&, copts, lower_from_tensorflow](xla::runtime::PassManager& passes) {
if (lower_from_tensorflow)
tensorflow::CreateTfJitRtPipeline(*passes, tf_jitrt_opts);
tfrt::jitrt::CreateDefaultJitRtCompilationPipeline(passes, copts);
};
opts.compiler.create_specialization_pipeline =
CreateJitRtSpecializationPipeline;
opts.compiler.calling_convention = xla::runtime::DefaultCallingConvention(
mlir::bufferization::BufferizeTypeConverter());
// Cache all jit executables, otherwise different benchmark runs will produce
// different .so files and the same compiled function will have different
// records in the perf profile.
static auto* cache = new llvm::StringMap<std::unique_ptr<JitExecutable>>();
std::string key =
llvm::formatv("{0}/{1}/{2}", mlir_input.data(), copts.num_worker_threads,
hash_value(tf_jitrt_opts));
// Compile and cache MLIR function.
auto it = cache->find(key);
if (it == cache->end()) {
absl::StatusOr<JitExecutable> jit_executable =
JitExecutable::Instantiate(mlir_input, function_name, opts);
if (!jit_executable.ok())
LOG(FATAL) << "Failed to instantiate JitExecutable from the function: "
<< function_name.str()
<< "; error: " << jit_executable.status().message();
auto storage = std::make_unique<JitExecutable>(std::move(*jit_executable));
it = cache->insert_or_assign(key, std::move(storage)).first;
}
return *(it->getValue());
}
MemrefDesc TensorToMemrefDesc(const Tensor& tensor) {
llvm::SmallVector<ssize_t> dims(tensor.shape().dims());
for (int d = 0; d < tensor.shape().dims(); ++d)
dims[d] = tensor.shape().dim_size(d);
xla::PrimitiveType dtype;
if (tensor.dtype() == DT_FLOAT)
dtype = xla::PrimitiveType::F32;
else if (tensor.dtype() == DT_INT64)
dtype = xla::PrimitiveType::S64;
else
LOG(FATAL) << "Unsupported tensor dtype: " << tensor.dtype();
tfrt::TensorShape shape(dims);
return MemrefDesc(
shape.GetRank(), dtype, tensor.data(), 0, [&](auto sizes, auto strides) {
MutableArrayRef<int64_t> sizes_ref(sizes.data(), sizes.size());
MutableArrayRef<int64_t> strides_ref(strides.data(), strides.size());
shape.GetDimensions(sizes_ref);
shape.GetStrides(strides_ref);
});
}
std::string PrintTensorType(llvm::ArrayRef<int64_t> shape,
llvm::StringRef element_type) {
std::string result{"tensor<"};
llvm::raw_string_ostream ss(result);
for (int64_t dim : shape) {
if (mlir::ShapedType::isDynamic(dim)) {
ss << '?';
} else {
ss << dim;
}
ss << 'x';
}
ss << element_type << '>';
return result;
}
std::string PrintDenseArray(llvm::ArrayRef<int32_t> array) {
std::string result{"dense<["};
llvm::raw_string_ostream ss(result);
for (auto elem : llvm::enumerate(array)) {
if (elem.index() > 0) ss << ',';
ss << elem.value();
}
ss << "]>";
return result;
}
} // namespace tensorflow
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
164558565301b91b6e313ee2a1524bc261f3502a | 77c7744d0b303165f0418eaef588939b561c98f2 | /Module 2/Chapter05/chapter05/scenemsaa.cpp | ecccd186cad52c5f99615cad1e7448cbb7c00a99 | [
"MIT"
] | permissive | PacktPublishing/OpenGL-Build-High-Performance-Graphics | 3e5f0dcae0b0c60b8c41d52aa32b20fe6aacc5dc | 7e68e1f2cf1b0a02c82786c6fde93b34b42f2b86 | refs/heads/master | 2023-02-16T04:21:45.656668 | 2023-01-30T10:14:51 | 2023-01-30T10:14:51 | 88,623,563 | 81 | 26 | null | null | null | null | UTF-8 | C++ | false | false | 3,353 | cpp | #include "scenemsaa.h"
#include <cstdio>
#include <cstdlib>
#include "glutils.h"
#include "defines.h"
using glm::vec3;
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform2.hpp>
SceneMsaa::SceneMsaa() : width(800), height(600), angle(0.0f), tPrev(0.0f), rotSpeed(PI/8.0)
{ }
void SceneMsaa::initScene()
{
compileAndLinkShader();
glClearColor(0.5f,0.5f,0.5f,1.0f);
glEnable(GL_DEPTH_TEST);
float c = 5.0f;
projection = glm::ortho(-0.4f * c, 0.4f * c, -0.3f *c, 0.3f*c, 0.1f, 100.0f);
plane = new VBOPlane(50.0f, 50.0f, 1, 1);
angle = PI / 2.0;
GLint bufs, samples;
glGetIntegerv(GL_SAMPLE_BUFFERS, &bufs);
glGetIntegerv(GL_SAMPLES, &samples);
printf("MSAA: buffers = %d samples = %d\n", bufs, samples);
glEnable(GL_MULTISAMPLE);
// Array for quad
GLfloat verts[] = {
-1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f
};
GLfloat tc[] = {
0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f
};
// Set up the buffers
unsigned int handle[2];
glGenBuffers(2, handle);
glBindBuffer(GL_ARRAY_BUFFER, handle[0]);
glBufferData(GL_ARRAY_BUFFER, 6 * 3 * sizeof(float), verts, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, handle[1]);
glBufferData(GL_ARRAY_BUFFER, 6 * 2 * sizeof(float), tc, GL_STATIC_DRAW);
// Set up the vertex array object
glGenVertexArrays( 1, &quad );
glBindVertexArray(quad);
glBindBuffer(GL_ARRAY_BUFFER, handle[0]);
glVertexAttribPointer( (GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, ((GLubyte *)NULL + (0)) );
glEnableVertexAttribArray(0); // Vertex position
glBindBuffer(GL_ARRAY_BUFFER, handle[1]);
glVertexAttribPointer( (GLuint)2, 2, GL_FLOAT, GL_FALSE, 0, ((GLubyte *)NULL + (0)) );
glEnableVertexAttribArray(2); // Texture coordinates
glBindVertexArray(0);
}
void SceneMsaa::update( float t )
{
float deltaT = t - tPrev;
if(tPrev == 0.0f) deltaT = 0.0f;
tPrev = t;
angle += rotSpeed * deltaT;
if( angle > TWOPI_F) angle -= TWOPI_F;
}
void SceneMsaa::render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
view = glm::lookAt(vec3(3.0f * cos(angle),0.0f,3.0f * sin(angle)), vec3(0.0f,0.0f,0.0f), vec3(0.0f,1.0f,0.0f));
model = glm::rotate(30.0f, vec3(0.0f,0.0f,1.0f));
setMatrices();
// Render the quad
glBindVertexArray(quad);
glDrawArrays(GL_TRIANGLES, 0, 6);
glFinish();
}
void SceneMsaa::setMatrices()
{
mat4 mv = view * model;
prog.setUniform("MVP", projection * mv);
}
void SceneMsaa::resize(int w, int h)
{
glViewport(0,0,w,h);
width = w;
height = h;
}
void SceneMsaa::compileAndLinkShader()
{
if( ! prog.compileShaderFromFile("shader/centroid.vs",GLSLShader::VERTEX) )
{
printf("Vertex shader failed to compile!\n%s",
prog.log().c_str());
exit(1);
}
if( ! prog.compileShaderFromFile("shader/centroid.fs",GLSLShader::FRAGMENT))
{
printf("Fragment shader failed to compile!\n%s",
prog.log().c_str());
exit(1);
}
if( ! prog.link() )
{
printf("Shader program failed to link!\n%s",
prog.log().c_str());
exit(1);
}
prog.use();
}
| [
"jijom@packtpub.com"
] | jijom@packtpub.com |
96dc50417693af6513664c7a5a03971f00d54da7 | 2c3cfe9708498925ea80e362950bd14c023eee84 | /ModelStaticEdit.h | 26a067b9043dac250d04c2c6a39d8a0f709bc95e | [] | no_license | lujianfeiccie/mfc_multi_choice_editor | ee88def0d0dff6620ef725b86149b293d6bd60db | d23babdfd9d4f07c1ce8fcb536248004180688c9 | refs/heads/master | 2020-11-26T19:22:40.586011 | 2014-12-17T04:51:27 | 2014-12-17T04:51:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | h | #pragma once
typedef enum TAG
{
TAG_QUESTION,
TAG_ANSWER
}TAG;
typedef enum TYPE
{
TYPE_TEXT,
TYPE_IMAGE
}TYPE;
class CModelStaticEdit
{
public:
CModelStaticEdit(void);
~CModelStaticEdit(void);
CStatic* m_static;
CEdit* m_edit;
CString m_value;
TAG m_tag;
TYPE m_type;
};
| [
"lujianfeiccie@gmail.com"
] | lujianfeiccie@gmail.com |
a60ca83bf2444a478db9e19aad92e7484d2975a8 | a4b31e7ab70b456b0227d49b8c454af249579944 | /139.word-break.cpp | c8f142c5950189e237acb0c10531a63d8134cb72 | [] | no_license | meton-robean/HandOnLeetCode | 2b61ac4f0c757d12b9f61a072680b935d7ca5fd0 | f06cdef78db3c4973a8cde063adf4b687a7a082e | refs/heads/master | 2020-07-23T21:06:46.645862 | 2020-05-12T06:39:55 | 2020-05-12T06:39:55 | 207,706,399 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 777 | cpp | /*
* @lc app=leetcode id=139 lang=cpp
*
* [139] Word Break
*/
// @lc code=start
/*
dp[i]表示str(0 ~ i)区间是否符合条件,可切分与匹配到.
str: 0---------------k------i
dp[i] = ( dp[k] && if str(k, i) in wordDict )
*/
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> dp( s.length()+1, false); //init
dp[0] = true;
for( int i = 1; i <= s.length(); i++){
for( int k = i-1; k>=0; --k){
if ( dp[k] && std::count( wordDict.begin(), wordDict.end(), s.substr(k, i-k)) ){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
};
// @lc code=end
| [
"569263721@qq.com"
] | 569263721@qq.com |
6afac15ef51746c68e5612cfd14654d8503629c0 | b8ebaaab6d71e33298d78e60a477ed27ecacd424 | /src/system.cpp | af9e28964d3c0d2790b1a09225af8567a59d35e3 | [] | no_license | MrFlowProduction/OllioFirmware | b82e198744aceba36cf6bf444f1f88d5a4830ca9 | ec6827ead47fad6c9295f13f879dc699772829a1 | refs/heads/master | 2023-07-05T07:24:08.973430 | 2021-08-26T18:21:56 | 2021-08-26T18:21:56 | 384,767,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | cpp | #include <system.h>
#ifdef __cplusplus
extern "C" {
#endif
uint8_t temprature_sens_read();
#ifdef __cplusplus
}
#endif
uint8_t temprature_sens_read();
float internal_temp(){
return (temprature_sens_read() - 32) / 1.8;
} | [
"38991405+MrFlowProduction@users.noreply.github.com"
] | 38991405+MrFlowProduction@users.noreply.github.com |
943990f0a82eb51f5ce33bcd5c8b3330612e0333 | 85a90519c644098eba8cca252449ee54ab22e458 | /cpp/opengl_game/0.3.7/src/scene.cpp | 60e5896610140ad5d4a7b9e28ecdf344baf711a8 | [] | no_license | fcccode/interview-1 | 17b492dacc20aae489bb2aabddc8f36268b36cc8 | 6db7c1999359905d3f791cde09b8e252112d6354 | refs/heads/master | 2020-04-29T11:40:19.471532 | 2012-05-11T13:52:07 | 2012-05-11T13:52:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,763 | cpp | #include "stdafx.h"
#include "draw/font.h"
#include "gui/gui.h"
#include "iichan/iichan.h"
#include "draw/draw.h"
#include "misc.h"
#include "config.h"
#ifdef _DEBUG_GUI
#include "gui_misc.h"
#include "gui_msgalloc.h"
#endif
#include "scene.h"
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
extern GUI* gui;
extern IICHAN* iichan;
extern unsigned int current_state;
extern config cfg;
extern HINSTANCE hInst;
extern unsigned int fps;
extern unsigned int frames;
extern int move_ticks;
extern int player_ticks;
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
int mouseX = 0;
int mouseY = 0;
bool mouse[3] = { false, false, false };
HGLRC hRC = NULL;
HDC hDC = NULL;
HWND game_window = NULL;
WNDCLASS window_class;
RECT window_rect;
DEVMODE dmScreenSettings;
int dwStyle = 0;
bool fullscreenflag = false;
PIXELFORMATDESCRIPTOR pfd;
int pf = 0;
bool active = true;
// --------------------------------------------------------------------------
long __stdcall WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_MOUSEMOVE:
{
mouseX = LOWORD(lParam);
mouseY = HIWORD(lParam);
return 0;
}
case WM_LBUTTONDOWN:
{
mouse[0] = true;
return 0;
}
case WM_LBUTTONUP:
{
mouse[0] = false;
return 0;
}
case WM_RBUTTONDOWN:
{
mouse[1] = true;
return 0;
}
case WM_RBUTTONUP:
{
mouse[1] = false;
return 0;
}
case WM_ACTIVATE:
{
switch(wParam)
{
case WA_ACTIVE:
case WA_CLICKACTIVE: active = true; break;
case WA_INACTIVE: active = false; break;
}
return 0;
}
case WM_DESTROY:
case WM_QUIT:
hDC = NULL;
game_window = NULL;
current_state = GAME_EXITING;
return 0;
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
void ClearScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
}
void PrintFPS()
{
static const font_t* font = FontByName(DEBUG_FONT);
glColor4ub(0, 255, 0, 255);
char frames_per_second[16];
sprintf(frames_per_second, "FPS: %u\0", fps);
PrintText(frames_per_second, font, 5, 40);
}
void PrintDebug()
{
static const font_t* font = FontByName(DEBUG_FONT);
glColor4ub(0, 255, 0, 255);
#ifdef DRAW_TIME_ELAPSED
char time_elapsed[32];
sprintf(time_elapsed, "Time elapsed: %u", current_time / 1000);
PrintText(time_elapsed, font, 5, 230);
#endif
#ifdef _DEBUG_MOUSE
char mx[4];
sprintf(mx, "Mouse X: %u", mouseX);
PrintText(mx, font, 5, 55);
char my[4];
sprintf(my, "Mouse Y: %u", mouseY);
PrintText(my, font, 5, 70);
#endif
#ifdef _DEBUG_GUI
if(gui)
{
if(gui->GetMessages())
{
char queue[32];
sprintf(queue, "Messages in msg_allocator: %u", gui->GetMessages()->GetMessageCount());
PrintText(queue, FontByName(DEBUG_FONT), 5, 75);
}
}
#endif
#ifdef PRINT_VERSION
#ifdef VERSION
#ifdef VERSION_X
#ifdef VERSION_Y
if(current_state == GAME_MAINMENU)
PrintText(VERSION, font, VERSION_X, VERSION_Y);
#else
if(current_state == GAME_MAINMENU)
PrintText(VERSION, font, VERSION_X, 25);
#endif
#else
#ifdef VERSION_Y
if(current_state == GAME_MAINMENU)
PrintText(VERSION, font, 5, VERSION_Y);
#else
PrintText(ENGINE, font, 5, 10);
PrintText(VERSION, font, 5, 25);
#endif
#endif
#endif
#endif
#ifdef _DEBUG_GAME
if(game)
game->DebugToScreen();
#endif
#ifdef _DEBUG_KEYBOARD
int i = 0;
PrintText("Keyboard: ", font, 5, 230);
for(vector<UCHAR>::iterator it = pressed_keys.begin();
it != pressed_keys.end();
it++)
{
i++;
char text = (*it);
PrintTextSafe(&text, 1, font, 65+i*15, 230);
}
#endif
}
void DrawScene()
{
if(iichan)
iichan->Draw();
if(gui)
gui->Draw();
if(cfg.debug)
PrintDebug();
if(cfg.show_fps)
PrintFPS();
frames++;
}
static void InitOGLSettings()
{
glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.1f);
glReadBuffer(GL_BACK);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}
void ApplyConfig(config* cfg)
{
ResizeScene(cfg->window_width,
cfg->window_height,
cfg->scr_width,
cfg->scr_height,
cfg->fullscreen);
}
void ResizeScene(UINT window_width, UINT window_height,
UINT scr_width, UINT scr_height, bool fullscreen)
{
RECT new_rect;
new_rect.left = 0;
new_rect.top = 0;
new_rect.right = window_width;
new_rect.bottom = window_height;
if(fullscreen)
{
dwStyle = WS_POPUP;
}
else
{
dwStyle = WS_CAPTION | WS_BORDER;
}
AdjustWindowRect(&new_rect, dwStyle, false);
if(!fullscreen)
{
SetWindowPos(game_window,
HWND_TOP,
GetSystemMetrics(0) - GetSystemMetrics(0)/2 - new_rect.right / 2,
GetSystemMetrics(1) - GetSystemMetrics(1)/2 - new_rect.bottom / 2,
new_rect.right - (new_rect.left),
new_rect.bottom - (new_rect.top),
SWP_SHOWWINDOW);
InitOGLSettings();
glViewport(0, 0,
window_width,
window_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,
scr_width,
scr_height,
0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
else
{
KillWindow(hInst);
InitWindow(hInst, true);
SetWindowPos(game_window,
HWND_TOP,
0, 0,
window_width,
window_height,
SWP_SHOWWINDOW);
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = scr_width;
dmScreenSettings.dmPelsHeight = scr_height;
dmScreenSettings.dmBitsPerPel = cfg.scr_bpp;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
InitOGLSettings();
glViewport(0, 0,
window_width,
window_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,
window_width,
window_height,
0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
DWORD disp;
//disp = ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
disp = DISP_CHANGE_SUCCESSFUL;
switch(disp)
{
case DISP_CHANGE_SUCCESSFUL:
{
fullscreenflag = true;
ShowCursor(true);
break;
}
case DISP_CHANGE_BADDUALVIEW:
{
fullscreenflag = false;
ShowCursor(true);
LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADDUALVIEW)");
MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADDUALVIEW", MB_OK | MB_ICONEXCLAMATION);
break;
}
case DISP_CHANGE_BADFLAGS:
{
fullscreenflag = false;
ShowCursor(true);
LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADFLAGS)");
MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADFLAGS", MB_OK | MB_ICONEXCLAMATION);
break;
}
case DISP_CHANGE_BADMODE:
{
fullscreenflag = false;
ShowCursor(true);
LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADMODE)");
MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADMODE", MB_OK | MB_ICONEXCLAMATION);
break;
}
case DISP_CHANGE_BADPARAM:
{
fullscreenflag = false;
ShowCursor(true);
LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADPARAM)");
MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADPARAM", MB_OK | MB_ICONEXCLAMATION);
break;
}
case DISP_CHANGE_FAILED:
{
fullscreenflag = false;
ShowCursor(true);
LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_FAILED)");
MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_FAILED", MB_OK | MB_ICONEXCLAMATION);
break;
}
case DISP_CHANGE_NOTUPDATED:
{
fullscreenflag = false;
ShowCursor(true);
LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_NOTUPDATED)");
MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_NOTUPDATED", MB_OK | MB_ICONEXCLAMATION);
break;
}
case DISP_CHANGE_RESTART:
{
fullscreenflag = false;
ShowCursor(true);
LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_RESTART)");
MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_RESTART", MB_OK | MB_ICONEXCLAMATION);
break;
}
}
}
fullscreenflag = fullscreen;
}
void Flip()
{
glFlush();
SwapBuffers(hDC);
}
void InitWindow(HINSTANCE hInstance, bool fullscreen)
{
window_rect.left = 0;
window_rect.right = DEFAULT_WINDOW_WIDTH;
window_rect.top = 0;
window_rect.bottom = DEFAULT_WINDOW_HEIGHT;
window_class.hInstance = hInstance;
window_class.style = CS_VREDRAW | CS_HREDRAW | CS_OWNDC;
window_class.lpfnWndProc = WndProc;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hbrBackground = NULL;
window_class.hIcon = LoadIcon(NULL, IDI_WINLOGO);
window_class.hCursor = LoadCursor(NULL, IDC_ARROW);
window_class.lpszMenuName = NULL;
window_class.lpszClassName = "OpenOrionClass";
//dwStyle = WS_CAPTION | WS_BORDER;
//if(fullscreen)
// dwStyle = WS_POPUP;
if(!RegisterClass(&window_class))
{
MessageBox(NULL, "Failed to register window class", "RegisterClass() Error", MB_OK | MB_ICONEXCLAMATION);
LogToFile("debug.log", "Failed to register window class");
PostQuitMessage(-1);
}
game_window = CreateWindow(window_class.lpszClassName,
GAMENAME,
dwStyle,
GetSystemMetrics(0) - GetSystemMetrics(0)/2 - window_rect.right / 2,
GetSystemMetrics(1) - GetSystemMetrics(1)/2 - window_rect.bottom / 2,
window_rect.right - window_rect.left,
window_rect.bottom - window_rect.top,
NULL,
NULL,
hInstance,
NULL);
if(!game_window)
{
LogToFile("Failed to create game window");
MessageBox(NULL, "Failed to create game window", "CreateWindowEx() Error", MB_OK | MB_ICONEXCLAMATION);
PostQuitMessage(-1);
}
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_GENERIC_ACCELERATED;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cDepthBits = 24;
pfd.iLayerType = PFD_MAIN_PLANE;
pfd.cColorBits = cfg.scr_bpp;
hDC = GetDC(game_window);
if(!hDC)
{
LogToFile("Failed to create device context");
MessageBox(NULL, "Failed to create device context", "GetDC() Error", MB_OK | MB_ICONEXCLAMATION);
PostQuitMessage(-1);
}
pf = ChoosePixelFormat(hDC, &pfd);
if(!pf)
{
LogToFile("Failed to choose pixel format");
MessageBox(NULL, "Failed to set pixel format", "ChoosePixelFormat() Error", MB_OK | MB_ICONEXCLAMATION);
PostQuitMessage(-1);
}
if(!SetPixelFormat(hDC, pf, &pfd))
{
LogToFile("Failed to set pixel format");
MessageBox(NULL, "Failed to set pixel format", "SetPixelFormat() Error", MB_OK | MB_ICONEXCLAMATION);
PostQuitMessage(-1);
}
hRC = wglCreateContext(hDC);
if(!hRC)
{
LogToFile("Failed to create rendering context");
MessageBox(NULL, "Failed to create rendering context", "wglCreateContext() Error", MB_OK | MB_ICONEXCLAMATION);
PostQuitMessage(-1);
}
if(!wglMakeCurrent(hDC, hRC))
{
LogToFile("Failed to make current context");
MessageBox(NULL, "Failed to make current context", "wglMakeCurrent() Error", MB_OK | MB_ICONEXCLAMATION);
PostQuitMessage(-1);
}
ShowWindow(game_window, SW_SHOW);
SetForegroundWindow(game_window);
SetFocus(game_window);
}
void KillWindow(HINSTANCE hInstance)
{
if(fullscreenflag)
{
ChangeDisplaySettings(NULL, 0);
ShowCursor(true);
}
if(hRC)
{
if(!wglMakeCurrent(NULL, NULL))
{
LogToFile("Failed to release current context");
MessageBox(NULL, "Failed to release current context", "wglMakeCurrent() Error", MB_OK | MB_ICONEXCLAMATION);
}
if(!wglDeleteContext(hRC))
{
LogToFile("Failed to delete rendering context");
MessageBox(NULL, "Failed to delete rendering context", "wglDeleteContext() Error", MB_OK | MB_ICONEXCLAMATION);
}
hRC = NULL;
}
if(hDC && ReleaseDC(game_window, hDC) != 1)
{
LogToFile("Failed to release device context");
MessageBox(NULL, "Failed to release device context", "ReleaseDC() Error", MB_OK | MB_ICONEXCLAMATION);
hDC = NULL;
}
if(game_window && DestroyWindow(game_window) == 0)
{
LogToFile("Failed to destroy game window");
MessageBox(NULL, "Failed to destroy game window", "DestroyWindow() Error", MB_OK | MB_ICONEXCLAMATION);
game_window = NULL;
}
if(!UnregisterClass(window_class.lpszClassName, hInstance))
{
LogToFile("Failed to unregister game window class");
MessageBox(NULL, "Failed to unregister game window class", "UnregisterClass() Error", MB_OK | MB_ICONEXCLAMATION);
hInstance = NULL;
}
} | [
"enderstd@gmail.com"
] | enderstd@gmail.com |
97c55016eed69a60f77602021da67545aad64f04 | b55a53d257875078be0433937fe2a05619cbc520 | /c3dsolarwidget.cpp | 2f92c4e12f9d4eb43a3497af731c1b27ad3acaf0 | [] | no_license | Qt-Widgets/skytechx | 326c8861dc9282514ce5f8ca7b54a08df391bd90 | bd09ceae2281e8712bb89d45a7d3e18fc22137d5 | refs/heads/master | 2020-12-11T01:38:09.743592 | 2016-09-18T11:16:23 | 2016-09-18T11:16:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,462 | cpp | #include "c3dsolarwidget.h"
#include "cskpainter.h"
#include "transform.h"
#include "ccomdlg.h"
#include "casterdlg.h"
#include "smartlabeling.h"
static QList <QVector3D> ptsList[8];
static QList <QVector3D> objList;
static QVector3D cometTail[4];
C3DSolarWidget::C3DSolarWidget(QWidget *parent) :
QWidget(parent)
{
setAttribute(Qt::WA_OpaquePaintEvent, true);
setAttribute(Qt::WA_NoSystemBackground, true);
setMouseTracking(true);
m_pixmap = NULL;
objList.clear();
m_lockAt = -1;
m_index = -1;
m_yaw = 0;
m_pitch = D2R(135);
m_drag = false;
m_rotate = false;
m_scale = 30;
m_translate = QVector3D(0, 0, 20);
cometTail[0] = QVector3D(-0.1f, 0, 0);
cometTail[1] = QVector3D(+0.1f, 0, 0);
cometTail[2] = QVector3D(-0.1f, 0, 0.1f);
cometTail[3] = QVector3D(+0.1f, 0, 0.1f);
}
void C3DSolarWidget::setView(mapView_t *view, bool genOrbit)
{
static double lastJD = -1;
m_view = *view;
if (genOrbit || qAbs(m_view.jd - lastJD) > 365 * 2)
{
generateOrbits();
lastJD = m_view.jd;
}
update();
}
void C3DSolarWidget::generateComet(int index, double time, double period, bool isComet)
{
double oldJD = m_view.jd;
double jdt = m_view.jd;
double per = period;
objList.clear();
m_isComet = isComet;
for (double jd = jdt - time; jd <= jdt + time; jd += per)
{
QVector3D pos;
if (isComet)
{
comet_t *com = &tComets[index];
m_view.jd = jd;
cAstro.setParam(&m_view);
if (!comSolve(com, jd, false))
{
break;
}
pos = QVector3D(com->orbit.hRect[0], com->orbit.hRect[1], com->orbit.hRect[2]);
}
else
{
asteroid_t *com = &tAsteroids[index];
m_view.jd = jd;
cAstro.setParam(&m_view);
astSolve(com, jd, false);
pos = QVector3D(com->orbit.hRect[0], com->orbit.hRect[1], com->orbit.hRect[2]);
}
objList.append(pos);
}
m_view.jd = oldJD;
m_index = index;
update();
}
void C3DSolarWidget::setShowHeight(bool show)
{
m_showHeight = show;
update();
}
void C3DSolarWidget::setShowEclipticPlane(bool show)
{
m_showEclipticPlane = show;
update();
}
void C3DSolarWidget::setShowRadius(bool show)
{
m_showRadius = show;
update();
}
void C3DSolarWidget::setLockAt(int index)
{
if (index == -1)
{ // free cam
setViewParam(CM_UNDEF, CM_UNDEF, 0, 0, 0, true);
}
m_lockAt = index;
update();
}
void C3DSolarWidget::setViewParam(double yaw, double pitch, double x, double y, double z, bool updateView)
{
if (!IS_UNDEF(yaw))
{
m_yaw = yaw;
}
if (!IS_UNDEF(pitch))
{
m_pitch = pitch;
}
if (!IS_UNDEF(x))
{
m_translate.setX(x);
}
if (!IS_UNDEF(y))
{
m_translate.setY(y);
}
if (!IS_UNDEF(z))
{
m_translate.setZ(z);
}
if (updateView)
{
update();
}
}
void C3DSolarWidget::removeOrbit()
{
m_index = -1;
objList.clear();
update();
}
QPixmap *C3DSolarWidget::getPixmap()
{
return m_pixmap;
}
void C3DSolarWidget::generateOrbits()
{
double steps[8] = {8, 1, 4, 10, 20, 25, 30, 40};
for (int i = PT_SUN; i <= PT_NEPTUNE; i++)
{
ptsList[i].clear();
}
#pragma omp parallel for shared(ptsList)
for (int i = PT_SUN; i <= PT_NEPTUNE; i++)
{
mapView_t view = m_view;
CAstro ast;
orbit_t o;
ast.setParam(&view);
ast.calcPlanet(i, &o, false, false, false);
double last = o.hLon;
double total = 0;
if (i == 0)
ptsList[i].append(QVector3D(o.eRect[0], o.eRect[1], 0));
else
ptsList[i].append(QVector3D(o.hRect[0], o.hRect[1], o.hRect[2]));
do
{
view.jd += steps[i] * 0.5;
ast.setParam(&view);
ast.calcPlanet(i, &o, false, true, false);
double delta = o.hLon - last;
if (delta < 0)
{
delta = fabs(delta + R360);
}
total += delta;
last = o.hLon;
if (total > R360)
{
break;
}
if (i == 0)
ptsList[i].append(QVector3D(o.eRect[0], o.eRect[1], 0));
else
ptsList[i].append(QVector3D(o.hRect[0], o.hRect[1], o.hRect[2]));
} while (1);
}
}
void C3DSolarWidget::paintEvent(QPaintEvent *)
{
if ((m_pixmap && m_pixmap->size() != size()) || !m_pixmap)
{
if (m_pixmap)
{
delete m_pixmap;
}
m_pixmap = new QPixmap(size());
}
CSkPainter painter(this);
CSkPainter p;
g_labeling.clear();
p.begin(m_pixmap);
CAstro ast;
p.setFont(QFont("verdana", 12));
if (m_lockAt == -2 && m_index >= 0)
{ // look at current object
if (m_isComet)
{
comet_t *com = &tComets[m_index];
cAstro.setParam(&m_view);
if (comSolve(com, m_view.jd, false))
{
QVector3D pos(com->orbit.hRect[0], com->orbit.hRect[1], com->orbit.hRect[2]);
setViewParam(CM_UNDEF, CM_UNDEF, -pos.x(), -pos.y(), -pos.z(), false);
}
}
else
{
asteroid_t *com = &tAsteroids[m_index];
cAstro.setParam(&m_view);
astSolve(com, m_view.jd, false);
QVector3D pos(com->orbit.hRect[0], com->orbit.hRect[1], com->orbit.hRect[2]);
setViewParam(CM_UNDEF, CM_UNDEF, -pos.x(), -pos.y(), -pos.z(), false);
}
rtfCreateOrthoView(width(), height(), 0.005, 10500, m_scale, m_translate, m_yaw, m_pitch, true);
}
else
if (m_lockAt >= PT_SUN)
{
orbit_t o;
ast.setParam(&m_view);
if (m_lockAt != 20 && m_lockAt != PT_SUN)
{
ast.calcPlanet(m_lockAt, &o, false, true, false);
setViewParam(CM_UNDEF, CM_UNDEF, -o.hRect[0], -o.hRect[1], -o.hRect[2], false);
rtfCreateOrthoView(width(), height(), 0.005, 10500, m_scale, m_translate, m_yaw, m_pitch, true);
}
else
if (m_lockAt == PT_SUN)
{
setViewParam(CM_UNDEF, CM_UNDEF, 0, 0, 0, false);
rtfCreateOrthoView(width(), height(), 0.005, 10500, m_scale, m_translate, m_yaw, m_pitch);
}
else
{ // earth
ast.calcPlanet(PT_SUN, &o, false, true, false);
setViewParam(CM_UNDEF, CM_UNDEF, -o.eRect[0], -o.eRect[1], -o.eRect[2], false);
rtfCreateOrthoView(width(), height(), 0.005, 10500, m_scale, m_translate, m_yaw, m_pitch, true);
}
}
else
{
rtfCreateOrthoView(width(), height(), 0.005, 10500, m_scale, m_translate, m_yaw, m_pitch);
}
p.setRenderHint(QPainter::Antialiasing, true);
p.fillRect(rect(), Qt::black);
double minSize = 3;
SKPOINT p1, p2;
// sun
p1.w.x = 0;
p1.w.y = 0;
p1.w.z = 0;
if (trfProjectPoint(&p1))
{
double r = m_scale * 600000 / AU1;
if (r < minSize)
{
r = minSize;
}
p.setPen(Qt::yellow);
p.setBrush(Qt::yellow);
p.drawEllipse(QPointF(p1.sx, p1.sy), r, r);
g_labeling.addLabel(QPoint(p1.sx, p1.sy), r, tr("Sun"), -1, RT_BOTTOM_RIGHT, SL_AL_ALL);
}
// axis
p1.w.x = -40;
p1.w.y = 0;
p1.w.z = 0;
p2.w.x = 40;
p2.w.y = 0;
p2.w.z = 0;
if (trfProjectLine(&p1, &p2))
{
p.setPen(QPen(Qt::white, 0.5, Qt::DotLine));
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
p1.w.x = 0;
p1.w.y = -40;
p1.w.z = 0;
p2.w.x = 0;
p2.w.y = 40;
p2.w.z = 0;
if (trfProjectLine(&p1, &p2))
{
p.setPen(QPen(Qt::white, 0.5, Qt::DotLine));
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
p1.w.x = 0;
p1.w.y = 0;
p1.w.z = 5;
p2.w.x = 0;
p2.w.y = 0;
p2.w.z = -5;
if (trfProjectLine(&p1, &p2))
{
p.setPen(QPen(Qt::gray, 0.5, Qt::DotLine));
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
p.renderText(p1.sx, p1.sy, 5, tr("NEP"), RT_TOP);
p.renderText(p2.sx, p2.sy, 5, tr("SEP"), RT_BOTTOM);
}
double from = 40;
double step = 1;
if (m_showEclipticPlane)
{
p.setPen(QPen(Qt::gray, 0.25, Qt::DotLine));
for (double d = -from; d < from; d += step)
{
p1.w.x = -from;
p1.w.y = d;
p1.w.z = 0;
p2.w.x = from;
p2.w.y = d;
p2.w.z = 0;
if (trfProjectLine(&p1, &p2))
{
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
p1.w.x = d;
p1.w.y = -from;
p1.w.z = 0;
p2.w.x = d;
p2.w.y = from;
p2.w.z = 0;
if (trfProjectLine(&p1, &p2))
{
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
}
}
for (int i = PT_SUN; i <= PT_NEPTUNE; i++)
{
for (int j = 0; j < ptsList[i].count(); j++)
{
QVector3D pt1 = ptsList[i][j];
QVector3D pt2 = ptsList[i][(j + 1) % ptsList[i].count()];
p1.w.x = pt1.x();
p1.w.y = pt1.y();
p1.w.z = pt1.z();
p2.w.x = pt2.x();
p2.w.y = pt2.y();
p2.w.z = pt2.z();
if (trfProjectLine(&p1, &p2))
{
p.setPen(QPen(Qt::white, 0.5));
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
}
QColor color[8] = {Qt::blue, Qt::lightGray, Qt::yellow, Qt::red, Qt::darkYellow, Qt::yellow, Qt::green, Qt::blue};
orbit_t o;
QVector3D pos;
ast.setParam(&m_view);
ast.calcPlanet(i, &o, false, true, false);
if (i == 0)
{
pos = QVector3D(o.eRect[0], o.eRect[1], 0);
}
else
{
pos = QVector3D(o.hRect[0], o.hRect[1], o.hRect[2]);
}
p1.w.x = pos.x();
p1.w.y = pos.y();
p1.w.z = pos.z();
if (trfProjectPoint(&p1))
{
double rad;
if (i == 0)
{
rad = 6371;
}
else
{
rad = o.dx;
}
double r = m_scale * rad * 0.5 / AU1;
if (r < minSize)
{
r = minSize;
}
p.setPen(color[i]);
p.setBrush(color[i]);
p.drawEllipse(QPointF(p1.sx, p1.sy), r, r);
p.setPen(Qt::white);
g_labeling.addLabel(QPoint(p1.sx, p1.sy), r, (i == 0) ? tr("Earth") : o.name, -1, RT_BOTTOM_RIGHT, SL_AL_ALL);
if (i == 0)
{ // earth
orbit_t o;
ast.setParam(&m_view);
ast.calcPlanet(PT_MOON, &o, false, true, false);
pos = QVector3D(o.hRect[0], o.hRect[1], o.hRect[2]);
p1.w.x += pos.x();
p1.w.y += pos.y();
p1.w.z += pos.z();
if (trfProjectPoint(&p1))
{
p.setPen(Qt::gray);
p.setBrush(Qt::gray);
p.drawEllipse(QPointF(p1.sx, p1.sy), r / 2, r / 2);
if (m_scale > 6000)
g_labeling.addLabel(QPoint(p1.sx, p1.sy), r * 2, tr("Moon"), -1, RT_BOTTOM_RIGHT, SL_AL_ALL);
}
}
}
if (m_showRadius)
{
p1.w.x = pos.x();
p1.w.y = pos.y();
p1.w.z = pos.z();
p2.w.x = 0;
p2.w.y = 0;
p2.w.z = 0;
if (trfProjectLine(&p1, &p2))
{
p.setPen(QPen(Qt::gray, 0.75, Qt::DotLine));
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
}
}
for (int j = 0; j < objList.count() - 1; j++)
{
QVector3D pt1 = objList[j];
QVector3D pt2 = objList[j + 1];
p1.w.x = pt1.x();
p1.w.y = pt1.y();
p1.w.z = pt1.z();
p2.w.x = pt2.x();
p2.w.y = pt2.y();
p2.w.z = pt2.z();
if (trfProjectLine(&p1, &p2))
{
if (p1.w.z > 0)
{
p.setPen(QPen(Qt::green, 1));
}
else
{
p.setPen(QPen(Qt::red, 1));
}
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
p1.w.x = pt1.x();
p1.w.y = pt1.y();
p1.w.z = 0;
p2.w.x = pt2.x();
p2.w.y = pt2.y();
p2.w.z = 0;
if (m_showHeight)
{
if (trfProjectLine(&p1, &p2))
{
p.setPen(QPen(Qt::darkBlue, 0.5));
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
if (!(j % 10))
{
p1.w.x = pt1.x();
p1.w.y = pt1.y();
p1.w.z = pt1.z();
p2.w.x = pt1.x();
p2.w.y = pt1.y();
p2.w.z = 0;
if (trfProjectLine(&p1, &p2))
{
if (p1.w.z > 0)
{
p.setPen(QPen(Qt::darkGreen, 0.5));
}
else
{
p.setPen(QPen(Qt::darkRed, 0.5));
}
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
}
}
}
double rr = 0, RR = 0;
QString name;
if (m_index >= 0)
{
QVector3D pos;
if (m_isComet)
{
comet_t *com = &tComets[m_index];
cAstro.setParam(&m_view);
if (!comSolve(com, m_view.jd, false))
{
return;
}
pos = QVector3D(com->orbit.hRect[0], com->orbit.hRect[1], com->orbit.hRect[2]);
rr = com->orbit.r;
RR = com->orbit.R;
name = com->name;
}
else
{
asteroid_t *com = &tAsteroids[m_index];
cAstro.setParam(&m_view);
astSolve(com, m_view.jd, false);
pos = QVector3D(com->orbit.hRect[0], com->orbit.hRect[1], com->orbit.hRect[2]);
rr = com->orbit.r;
RR = com->orbit.R;
name = com->name;
}
p1.w.x = pos.x();
p1.w.y = pos.y();
p1.w.z = pos.z();
if (trfProjectPoint(&p1))
{
double r = 6;
double tail = 1;
p.setPen(Qt::red);
p.setBrush(Qt::white);
p.drawEllipse(QPointF(p1.sx, p1.sy), r, r);
if (m_showRadius)
{
SKPOINT pt1, pt2;
pt1.w.x = p1.w.x;
pt1.w.y = p1.w.y;
pt1.w.z = p1.w.z;
pt2.w.x = 0;
pt2.w.y = 0;
pt2.w.z = 0;
if (trfProjectLine(&pt1, &pt2))
{
p.setPen(QPen(Qt::lightGray, 1.25, Qt::DotLine));
p.drawLine(pt1.sx, pt1.sy, pt2.sx, pt2.sy);
}
}
if (m_isComet)
{ // draw tail
QVector3D vec = -pos.normalized();
p2.w.x = (pos.x() - vec.x()) * tail;
p2.w.y = (pos.y() - vec.y()) * tail;
p2.w.z = (pos.z() - vec.z()) * tail;
if (trfProjectLine(&p1, &p2))
{
p.setPen(QPen(Qt::white, 0.5));
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
for (int i = 0; i < 4; i++)
{
QVector3D vec2 = vec + cometTail[i];
vec2.normalize();
p2.w.x = (pos.x() - vec2.x()) * tail;
p2.w.y = (pos.y() - vec2.y()) * tail;
p2.w.z = (pos.z() - vec2.z()) * tail;
if (trfProjectLine(&p1, &p2))
{
p.setPen(QPen(Qt::white, 0.5));
p.drawLine(p1.sx, p1.sy, p2.sx, p2.sy);
}
}
}
p.setPen(Qt::white);
g_labeling.addLabel(QPoint(p1.sx, p1.sy), r, name, -1, RT_BOTTOM_RIGHT, SL_AL_ALL);
}
}
p.setPen(Qt::white);
g_labeling.render(&p);
QFontMetrics mt(p.font());
const int h = mt.height() + 5;
const int m = 15;
p.setPen(Qt::white);
if (m_pitch > R90)
{
p.renderText(5, height() - h * 4 - m, 5, tr("Looking from top"), RT_BOTTOM_RIGHT);
}
else
{
p.renderText(5, height() - h * 4 - m, 5, tr("Looking from bottom"), RT_BOTTOM_RIGHT);
}
if (m_index >= 0)
{
p.renderText(5, height() - h * 3 - m, 5, tr("Distance from Sun : %1 AU").arg(rr, 0, 'f', 8), RT_BOTTOM_RIGHT);
p.renderText(5, height() - h * 2 - m, 5, tr("Distance from Earth : %1 AU / %2 KM").arg(RR, 0, 'f', 8).arg(RR * AU1, 0, 'f', 2), RT_BOTTOM_RIGHT);
}
if (m_index >= 0)
{
p.save();
QFont font(p.font());
font.setBold(true);
p.setFont(font);
p.renderText(width() / 2, 5, 5, tr("Orbit of ") + name, RT_BOTTOM);
p.restore();
}
int ix = 10;
int iy = height() - 10;
int sc = 0;
do
{
sc++;
}
while ((m_scale / sc) > width() - 150);
int au1 = m_scale / sc;
p.setPen(QPen(Qt::white, 3));
p.drawLine(ix, iy, ix + au1, iy);
p.drawText(5 + ix + au1, iy, QString::number(1 / (double)sc, 'f', 2) + tr(" AU"));
p.end();
painter.drawPixmap(0, 0, *m_pixmap);
}
void C3DSolarWidget::wheelEvent(QWheelEvent *e)
{
if (e->delta() < 0)
{
m_scale *= 0.8;
}
else
{
m_scale *= 1.2;
}
m_scale = CLAMP(m_scale, 4, 15000);
update();
}
void C3DSolarWidget::mousePressEvent(QMouseEvent *e)
{
if (e->buttons() & Qt::LeftButton)
{
m_drag = true;
}
else
if (e->buttons() & Qt::RightButton)
{
m_rotate = true;
}
m_lastPoint = e->pos();
}
void C3DSolarWidget::mouseMoveEvent(QMouseEvent *e)
{
double scale = m_scale * 0.5;
if (m_drag)
{
double dx = e->pos().x() - m_lastPoint.x();
double dy = e->pos().y() - m_lastPoint.y();
m_translate.setX(m_translate.x() + dx / scale);
m_translate.setY(m_translate.y() + dy / scale);
update();
m_lastPoint = e->pos();
return;
}
if (m_rotate)
{
m_pitch += 0.01 * (e->pos().y() - m_lastPoint.y());
m_yaw += 0.01 * (e->pos().x() - m_lastPoint.x());
m_pitch = CLAMP(m_pitch, 0, R180);
update();
m_lastPoint = e->pos();
return;
}
}
void C3DSolarWidget::mouseReleaseEvent(QMouseEvent * /*e*/)
{
m_drag = false;
m_rotate = false;
}
| [
"astromraz@seznam.cz"
] | astromraz@seznam.cz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.