blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa9ca14ffc314c8840f0a35a66c07ebba8ce7f46 | edf85ec3c273e7ce0ed4790e5725a55393a2c488 | /extlibs/include/Jopnal/Physics/Shape/CompoundShape.hpp | d060452187d7b3c23b32086587be3e68242c4e95 | [
"Zlib"
] | permissive | Jopnal/Jopmodel | fb9cb83dad5c4432d5ffaefc8ac45c97ce37ee97 | cfd50b9fd24eaf63497bf5bed883f0b831d9ad65 | refs/heads/master | 2021-01-17T06:33:40.982800 | 2016-08-09T08:12:28 | 2016-08-09T08:12:28 | 61,036,364 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,741 | hpp | // Jopnal Engine C++ Library
// Copyright (c) 2016 Team Jopnal
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgement in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//////////////////////////////////////////////
#ifndef JOP_COMPOUNDSHAPE_HPP
#define JOP_COMPOUNDSHAPE_HPP
// Headers
#include <Jopnal/Header.hpp>
#include <Jopnal/Physics/Shape/CollisionShape.hpp>
//////////////////////////////////////////////
namespace jop
{
class Transform;
class JOP_API CompoundShape final : public CollisionShape
{
public:
/// \brief Constructor
///
/// \param name Name of the resource
///
CompoundShape(const std::string& name);
/// \brief Add a child shape
///
/// \param childShape Reference to a valid shape
/// \param childTransform Local transform for the child
///
void addChild(CollisionShape& childShape, const Transform::Variables& childTransform);
};
}
#endif | [
"eetu.asikainen@hotmail.com"
] | eetu.asikainen@hotmail.com |
2a20cc82f54bc1e68845c918b4c0596ad4738fe7 | a84538af8bf1f763a3d71d939744976425358b30 | /src/qt/receivecoinsdialog.cpp | 31194902385b71fc1cc5dbe1f40de5761002c103 | [
"MIT"
] | permissive | YourLocalDundee/foxdcoin | 8de421b280a812e390249f14ed0b5892c546ebf1 | 9db505f6f32bd3e51bd2b2da533744c98cee23af | refs/heads/master | 2023-05-14T05:10:26.435417 | 2021-06-09T06:18:50 | 2021-06-09T06:18:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,731 | cpp | // Copyright (c) 2011-2016 The Bitcoin Core developers
// Copyright (c) 2017-2019 The Raven Core developers
// Copyright (c) 2020-2021 The Foxdcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "receivecoinsdialog.h"
#include "ui_receivecoinsdialog.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "foxdcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "receiverequestdialog.h"
#include "recentrequeststablemodel.h"
#include "walletmodel.h"
#include "guiconstants.h"
#include <QAction>
#include <QCursor>
#include <QItemSelection>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
#include <QGraphicsDropShadowEffect>
ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiveCoinsDialog),
columnResizingFixer(0),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->clearButton->setIcon(QIcon());
ui->receiveButton->setIcon(QIcon());
ui->showRequestButton->setIcon(QIcon());
ui->removeRequestButton->setIcon(QIcon());
} else {
ui->clearButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
ui->receiveButton->setIcon(_platformStyle->SingleColorIcon(":/icons/receiving_addresses"));
ui->showRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/edit"));
ui->removeRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
}
// context menu actions
QAction *copyURIAction = new QAction(tr("Copy URI"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyMessageAction = new QAction(tr("Copy message"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyURIAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(copyAmountAction);
// context menu signals
connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyURIAction, SIGNAL(triggered()), this, SLOT(copyURI()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
setupRequestFrame(platformStyle);
setupHistoryFrame(platformStyle);
}
void ReceiveCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
_model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
QTableView* tableView = ui->recentRequestsView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(_model->getRecentRequestsTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Amount, AMOUNT_MINIMUM_COLUMN_WIDTH);
connect(tableView->selectionModel(),
SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,
SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection)));
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);
tableView->show();
}
}
ReceiveCoinsDialog::~ReceiveCoinsDialog()
{
delete ui;
}
void ReceiveCoinsDialog::clear()
{
ui->reqAmount->clear();
ui->reqLabel->setText("");
ui->reqMessage->setText("");
ui->reuseAddress->setChecked(false);
updateDisplayUnit();
}
void ReceiveCoinsDialog::reject()
{
clear();
}
void ReceiveCoinsDialog::accept()
{
clear();
}
void ReceiveCoinsDialog::setupRequestFrame(const PlatformStyle *platformStyle)
{
/** Update the coincontrol frame */
ui->frame2->setStyleSheet(QString(".QFrame {background-color: %1; border: none;}").arg(platformStyle->WidgetBackGroundColor().name()));
/** Create the shadow effects on the frames */
ui->frame2->setGraphicsEffect(GUIUtil::getShadowEffect());
ui->label_5->setStyleSheet(STRING_LABEL_COLOR);
ui->label_2->setStyleSheet(STRING_LABEL_COLOR);
ui->label_2->setFont(GUIUtil::getSubLabelFont());
ui->label->setStyleSheet(STRING_LABEL_COLOR);
ui->label->setFont(GUIUtil::getSubLabelFont());
ui->label_3->setStyleSheet(STRING_LABEL_COLOR);
ui->label_3->setFont(GUIUtil::getSubLabelFont());
ui->label_4->setStyleSheet(STRING_LABEL_COLOR);
ui->label_4->setFont(GUIUtil::getSubLabelFont());
ui->label_7->setStyleSheet(STRING_LABEL_COLOR);
ui->label_7->setFont(GUIUtil::getSubLabelFont());
ui->reuseAddress->setStyleSheet(QString(".QCheckBox{ %1; }").arg(STRING_LABEL_COLOR));
ui->reqLabel->setFont(GUIUtil::getSubLabelFont());
ui->reqAmount->setFont(GUIUtil::getSubLabelFont());
ui->reqMessage->setFont(GUIUtil::getSubLabelFont());
ui->receiveButton->setFont(GUIUtil::getSubLabelFont());
ui->clearButton->setFont(GUIUtil::getSubLabelFont());
ui->recentRequestsView->setFont(GUIUtil::getSubLabelFont());
ui->showRequestButton->setFont(GUIUtil::getSubLabelFont());
ui->removeRequestButton->setFont(GUIUtil::getSubLabelFont());
ui->label_5->setFont(GUIUtil::getSubLabelFont());
ui->label_6->setFont(GUIUtil::getSubLabelFontBolded());
}
void ReceiveCoinsDialog::setupHistoryFrame(const PlatformStyle *platformStyle)
{
/** Update the coincontrol frame */
ui->frame->setStyleSheet(QString(".QFrame {background-color: %1; border: none;}").arg(platformStyle->WidgetBackGroundColor().name()));
/** Create the shadow effects on the frames */
ui->frame->setGraphicsEffect(GUIUtil::getShadowEffect());
ui->label_6->setStyleSheet(STRING_LABEL_COLOR);
contextMenu->setFont(GUIUtil::getSubLabelFont());
}
void ReceiveCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void ReceiveCoinsDialog::on_receiveButton_clicked()
{
if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())
return;
QString address;
QString label = ui->reqLabel->text();
if(ui->reuseAddress->isChecked())
{
/* Choose existing receiving address */
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
address = dlg.getReturnValue();
if(label.isEmpty()) /* If no label provided, use the previously used label */
{
label = model->getAddressTableModel()->labelForAddress(address);
}
} else {
return;
}
} else {
/* Generate new receiving address */
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "");
}
SendCoinsRecipient info(address, label,
ui->reqAmount->value(), ui->reqMessage->text());
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModel(model->getOptionsModel());
dialog->setInfo(info);
dialog->show();
clear();
/* Store request for later reference */
model->getRecentRequestsTableModel()->addNewRequest(info);
}
void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setModel(model->getOptionsModel());
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
// Enable Show/Remove buttons only if anything is selected.
bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();
ui->showRequestButton->setEnabled(enable);
ui->removeRequestButton->setEnabled(enable);
}
void ReceiveCoinsDialog::on_showRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
for (const QModelIndex& index : selection) {
on_recentRequestsView_doubleClicked(index);
}
}
void ReceiveCoinsDialog::on_removeRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());
}
// We override the virtual resizeEvent of the QWidget to adjust tables column
// sizes as the tables width is proportional to the dialogs width.
void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);
}
void ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return)
{
// press return -> submit form
if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus())
{
event->ignore();
on_receiveButton_clicked();
return;
}
}
this->QDialog::keyPressEvent(event);
}
QModelIndex ReceiveCoinsDialog::selectedRow()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return QModelIndex();
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return QModelIndex();
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
return firstIndex;
}
// copy column of selected row to clipboard
void ReceiveCoinsDialog::copyColumnToClipboard(int column)
{
QModelIndex firstIndex = selectedRow();
if (!firstIndex.isValid()) {
return;
}
GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.model()->index(firstIndex.row(), column), Qt::EditRole).toString());
}
// context menu
void ReceiveCoinsDialog::showMenu(const QPoint &point)
{
if (!selectedRow().isValid()) {
return;
}
contextMenu->exec(QCursor::pos());
}
// context menu action: copy URI
void ReceiveCoinsDialog::copyURI()
{
QModelIndex sel = selectedRow();
if (!sel.isValid()) {
return;
}
const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel();
const QString uri = GUIUtil::formatFoxdcoinURI(submodel->entry(sel.row()).recipient);
GUIUtil::setClipboard(uri);
}
// context menu action: copy label
void ReceiveCoinsDialog::copyLabel()
{
copyColumnToClipboard(RecentRequestsTableModel::Label);
}
// context menu action: copy message
void ReceiveCoinsDialog::copyMessage()
{
copyColumnToClipboard(RecentRequestsTableModel::Message);
}
// context menu action: copy amount
void ReceiveCoinsDialog::copyAmount()
{
copyColumnToClipboard(RecentRequestsTableModel::Amount);
}
| [
"foxrtb@gmail.com"
] | foxrtb@gmail.com |
bfb39f6ce76b15ea2d3812e8c2797270a033c2a8 | 947f7337f02133ff894005fa2d1d667a79040b0f | /C++/Complete-Modern-C++/Section02-Basic-Language-Facilities/namespace/src/namespace.cpp | f1559130f847a58680c12eafaaba2f38abf7c782 | [] | no_license | qelias/Udemy | 34464626f1bcce560f6274188cb479bf090db5dc | 2ddbcd001b371262c6b234e772856bbd1208d7df | refs/heads/main | 2023-03-25T01:42:11.970181 | 2021-03-23T12:15:16 | 2021-03-23T12:15:16 | 318,497,631 | 0 | 0 | null | 2021-03-20T15:36:45 | 2020-12-04T11:36:33 | Jupyter Notebook | UTF-8 | C++ | false | false | 388 | cpp | #include <iostream>
namespace Namespace1 {
float Calculate(float x, float y){
return (x + y)/2;
}
}
namespace Namespace2 {
float Calculate(float x, float y){
return (x + y);
}
}
int main(){
//using namespace Namespace1;
std::cout<<Namespace1::Calculate(1,5)<<std::endl;
std::cout<<Namespace2::Calculate(1,5)<<std::endl;
return 0;
} | [
"elias.quent@gmail.com"
] | elias.quent@gmail.com |
bb9f56b2d9ad4f27b103c7ad78d2fc4021201314 | 68af9795028bc44b4e1205f3407cd60a45f73776 | /Libs/LibCogmatix/CompositePart.h | fdb5bb262e6d606051b150568aa14322f5cb403f | [] | no_license | lindkvis/Cogmatix | 607c30c4f7a8bddfd6eeb82617e110bb982123a9 | b7dcc88a959d0fc62210bb50dc35d7dd4c73b68c | refs/heads/master | 2021-05-27T06:13:08.824681 | 2012-06-16T15:39:41 | 2012-06-16T15:39:41 | 4,606,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 848 | h | #pragma once
#include <osg/Geode>
#include "Node.h"
namespace LibCogmatix
{
class CompositePart : public TMachineNode<osg::Group>
{
public:
typedef osg::ref_ptr<CompositePart> Ptr;
typedef osg::ref_ptr<const CompositePart> CPtr;
// TODO: make this unicode
void loadGraphics (CoString fileName);
factory_protected:
CompositePart(NodeID ID, CoString name, CoString fileName) : TMachineNode<osg::Group> (ID, name)
{
loadGraphics(fileName);
}
~CompositePart() {}
CompositePart() : TMachineNode<osg::Group>() {}
CompositePart(const CompositePart& copyFrom, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY)
: TMachineNode<osg::Group>(copyFrom, copyop)
{
}
META_Node(LibCogmatix, CompositePart);
private:
String _fileName;
};
}
| [
"lindkvis@gmail.com"
] | lindkvis@gmail.com |
bda200fa2dd7b7601fa7e603cd7e6cccc32a1950 | 51d5cff1ac2c3baccaa65df86a6d82b83ada5740 | /sphereGenerator.cpp | 5fde665274ad834f5341e5e23ef528f0bb05ce48 | [] | no_license | cou929/polygonise | 4c72da66d71ef22cfa61bbea43673c4b6a4fa982 | 4bd895abe90f9c914e0b7e67830c57a949f575a4 | refs/heads/master | 2021-01-10T18:37:40.142040 | 2009-11-06T07:26:04 | 2009-11-06T07:26:04 | 299,520 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,018 | cpp | #include <iostream>
#include <vector>
#include <cmath>
std::vector <std::vector <int> > generateSphere(int radius);
std::vector <std::vector <int> > generateSphere(int radius)
{
std::vector <std::vector <int> > ret;
for (int x=-radius; x<=radius; x++)
for (int y=-radius; y<=radius; y++)
for (int z=-radius; z<=radius; z++)
{
int distance = (int)sqrt(x*x + y*y + z*z);
int range = 1;
if (distance - range <= (int)sqrt(radius*radius) && (int)sqrt(radius*radius) <= distance + range)
{
std::vector <int> tmp;
tmp.push_back(x); tmp.push_back(y); tmp.push_back(z);
ret.push_back(tmp);
}
}
return ret;
}
int main(int argc, char ** argv)
{
std::vector <std::vector <int> > sphere;
int radius = 5;
if (argc == 2)
radius = atoi(argv[1]);
sphere = generateSphere(radius);
for (int i=0; i<sphere.size(); i++)
{
for (int j=0; j<sphere[i].size(); j++)
std::cout << sphere[i][j] << "\t";
std::cout << std::endl;
}
return 0;
}
| [
"cou929@gmail.com"
] | cou929@gmail.com |
52b23d257a70956478e0a4087ad3561cb7fe9b7d | 9807004938c74382be6a1797b1948a95cdba9955 | /beam/beam/Source.cpp | 1a7ee232a809b2a02081ba5d00135ae33ca5b304 | [] | no_license | KillPeopleFast/AprilCode | e2bff81db906442469d4e90370b82ea222a722f0 | 37e330f95fed4db3b64da9f866a5fd13850af40d | refs/heads/master | 2021-01-19T04:02:32.079090 | 2017-05-02T18:55:17 | 2017-05-02T18:55:17 | 87,348,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,201 | cpp | #include <iostream>
#include <allegro5/allegro.h>
#include <math.h>
using namespace std;
const float FPS = 60;
const int SCREEN_W = 640;
const int SCREEN_H = 480;
const int ship_SIZE = 32;
enum MYKEYS {
KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_SPACE
};
int main()
{
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_BITMAP *ship = NULL;
ALLEGRO_BITMAP *beam = NULL;
ALLEGRO_BITMAP *beam2 = NULL;
float ship_x = SCREEN_W / 2.0 - ship_SIZE / 2.0;
float ship_y = SCREEN_H / 2.0 - ship_SIZE / 2.0;
bool key[5] = { false, false, false, false, false };
bool redraw = true;
bool doexit = false;
double beam_x = 0;
double beam_y = 0;
double beam2_x = 0;
double beam2_y = 0;
int t = 0; //parameter for parametric equations
bool shootBeam = false;
al_init();
al_install_keyboard();
timer = al_create_timer(1.0 / FPS);
display = al_create_display(SCREEN_W, SCREEN_H);
//create ship
ship = al_create_bitmap(ship_SIZE, ship_SIZE);
al_set_target_bitmap(ship);
al_clear_to_color(al_map_rgb(255, 0, 255));
//create first beam object
beam = al_create_bitmap(3, 3);
al_set_target_bitmap(beam);
al_clear_to_color(al_map_rgb(0, 200, 55));
////////////////////beam2
beam2 = al_create_bitmap(3, 3);
al_set_target_bitmap(beam2);
al_clear_to_color(al_map_rgb(0, 200, 55));
//set up game screen, queue, and timer to be ready to play
al_set_target_bitmap(al_get_backbuffer(display));
event_queue = al_create_event_queue();
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_timer_event_source(timer));
al_register_event_source(event_queue, al_get_keyboard_event_source());
al_clear_to_color(al_map_rgb(0, 0, 0));
al_flip_display();
al_start_timer(timer);
while (!doexit)//game loop!
{
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_TIMER) {
//reset beam when spacebar is first pressed!
if (key[KEY_SPACE] && shootBeam == false) {
t = 0; //reset time parameter
shootBeam = true; //tell render section to draw it, and movement algorithm to freeze ship when shooting
}
//move beam while space is being pressed
if (shootBeam) {
beam_x = ship_x + t;
////equation for beam////////////////////////////////////////////////////////////
//LOOK! LOOK! Here's where you can change the path of the beam!
beam_y = ship_y + 10 * sin(3 *(beam_x += 40)) + 10;
beam2_y = ship_y + 10 * sin(400 * (beam2_x += 40)) + 10;
////////////////////////////////////////////////////////////////
t++; //increase time
cout << "beam being fired" << endl;
}
//normal keyboard input movement, but only allow ship to move when not firing beam
if (key[KEY_UP] && ship_y >= 4.0 && shootBeam == false) {
ship_y -= 4.0;
}
if (key[KEY_DOWN] && ship_y <= SCREEN_H - ship_SIZE - 4.0 && shootBeam == false) {
ship_y += 4.0;
}
if (key[KEY_LEFT] && ship_x >= 4.0 && shootBeam == false) {
ship_x -= 4.0;
}
if (key[KEY_RIGHT] && ship_x <= SCREEN_W - ship_SIZE - 4.0 && shootBeam == false) {
ship_x += 4.0;
}
//when spacebar is let go, stop drawing beam and reset position
if (key[KEY_SPACE] == false) {
shootBeam = false;
beam_x = ship_x;
beam_y = ship_y;
beam2_x = ship_x;
beam2_y = ship_y;
}
redraw = true;
}
//kill game if window "x" is clicked with mouse
else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
break;
}
//basic allegro keyboard input
else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
switch (ev.keyboard.keycode) {
case ALLEGRO_KEY_UP:
key[KEY_UP] = true;
break;
case ALLEGRO_KEY_DOWN:
key[KEY_DOWN] = true;
break;
case ALLEGRO_KEY_LEFT:
key[KEY_LEFT] = true;
break;
case ALLEGRO_KEY_RIGHT:
key[KEY_RIGHT] = true;
break;
case ALLEGRO_KEY_SPACE:
key[KEY_SPACE] = true;
break;
}
}
else if (ev.type == ALLEGRO_EVENT_KEY_UP) {
switch (ev.keyboard.keycode) {
case ALLEGRO_KEY_UP:
key[KEY_UP] = false;
break;
case ALLEGRO_KEY_DOWN:
key[KEY_DOWN] = false;
break;
case ALLEGRO_KEY_LEFT:
key[KEY_LEFT] = false;
break;
case ALLEGRO_KEY_RIGHT:
key[KEY_RIGHT] = false;
break;
case ALLEGRO_KEY_SPACE:
key[KEY_SPACE] = false;
break;
case ALLEGRO_KEY_ESCAPE:
doexit = true;
break;
}
}
//RENDER SECTION
if (redraw && al_is_event_queue_empty(event_queue)) {
redraw = false;
//only redraw when beam is NOT being fired...
if (shootBeam == false)
al_clear_to_color(al_map_rgb(0, 0, 0));
//when not being fired, beam is behind ship
al_draw_bitmap(beam, beam_x, beam_y, 0);
al_draw_bitmap(beam2, beam2_x, beam2_y, 0);
//draw ship
al_draw_bitmap(ship, ship_x, ship_y, 0);
al_flip_display();
}//end render section
}//END GAME LOOP
al_destroy_bitmap(ship);
al_destroy_timer(timer);
al_destroy_display(display);
al_destroy_event_queue(event_queue);
return 0;
}//end main | [
"game110pm@605-110-STU05"
] | game110pm@605-110-STU05 |
715435273954bebf97f90b57e9e1abf1a2684ed3 | 45c0c17bcf2ebe763917d106aacefe09ec8ca138 | /easy/66. Plus One.cpp | 3d164c3f5fab59c05039b56a7c8265a683c6edac | [] | no_license | Juliiii/leetcode-everyday | 8d1b11bd6aa63e6f430524f81e88f786146e12af | 7bda1fc9ee9c58d3348ac0ce6176db7f43ede42e | refs/heads/master | 2021-09-05T06:08:27.055385 | 2018-01-24T16:32:18 | 2018-01-24T16:32:18 | 107,296,151 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
reverse(digits.begin(), digits.end());
int sum, carry = 0;
for (int i = 0; i < digits.size(); i++) {
sum = i == 0 ? digits[i] + carry + 1 : digits[i] + carry;
carry = sum / 10;
sum = sum % 10;
digits[i] = sum;
}
if (carry) {
digits.push_back(carry);
}
reverse(digits.begin(), digits.end());
return digits;
}
};
| [
"noreply@github.com"
] | Juliiii.noreply@github.com |
a4d05b9f0d82c3a2d026e184e66b7d0c423b027a | 69740a5b14d963b51ac0b8d956c205d3b7879353 | /contrib/CCF/CCF/IDL2/SemanticGraph/ValueType.hpp | 97a286cdb211f05d078425087463c3be6e8075c0 | [] | no_license | SEDS/OASIS | eba334ae59e69fc66d1e355fedb5ad5583b40695 | ddf365eea9874fa5938072fea1fad5b41c27f3e9 | refs/heads/master | 2020-12-24T15:51:12.761878 | 2013-12-03T20:30:21 | 2013-12-03T20:30:21 | 13,195,236 | 4 | 3 | null | 2015-10-24T09:40:39 | 2013-09-29T15:58:55 | C++ | UTF-8 | C++ | false | false | 3,550 | hpp | // file : CCF/IDL2/SemanticGraph/ValueType.hpp
// author : Boris Kolpackov <boris@dre.vanderbilt.edu>
// cvs-id : $Id: ValueType.hpp 74499 2006-09-22 10:02:37Z boris $
#ifndef CCF_IDL2_SEMANTIC_GRAPH_VALUE_TYPE_HPP
#define CCF_IDL2_SEMANTIC_GRAPH_VALUE_TYPE_HPP
#include "CCF/IDL2/SemanticGraph/Elements.hpp"
#include "CCF/IDL2/SemanticGraph/Operation.hpp"
#include "CCF/IDL2/SemanticGraph/Interface.hpp" // Supports
namespace CCF
{
namespace IDL2
{
namespace SemanticGraph
{
//
//
//
class ValueType : public virtual Type,
public virtual Scope
{
typedef
std::vector <Inherits*>
Inherits_;
typedef
std::vector <Supports*>
Supports_;
public:
typedef
Inherits_::const_iterator
InheritsIterator;
InheritsIterator
inherits_begin () const
{
return inherits_.begin ();
}
InheritsIterator
inherits_end () const
{
return inherits_.end ();
}
typedef
Supports_::const_iterator
SupportsIterator;
SupportsIterator
supports_begin () const
{
return supports_.begin ();
}
SupportsIterator
supports_end () const
{
return supports_.end ();
}
public:
virtual bool
complete () const
{
return true;
}
static Introspection::TypeInfo const&
static_type_info ();
protected:
friend class Graph<Node, Edge>;
ValueType () // For virtual inheritance only.
{
type_info (static_type_info ());
}
virtual
~ValueType () = 0;
using Type::add_edge_right;
using Scope::add_edge_left;
void
add_edge_left (Inherits& e)
{
inherits_.push_back (&e);
}
void
add_edge_right (Inherits&)
{
}
void
add_edge_left (Supports& e)
{
supports_.push_back (&e);
}
private:
Inherits_ inherits_;
Supports_ supports_;
};
//
//
//
class AbstractValueType : public virtual ValueType
{
public:
static Introspection::TypeInfo const&
static_type_info ();
protected:
friend class Graph<Node, Edge>;
AbstractValueType (Path const& path, unsigned long line)
: Node (path, line)
{
type_info (static_type_info ());
}
};
//
//
//
class ConcreteValueType : public virtual ValueType
{
public:
static Introspection::TypeInfo const&
static_type_info ();
protected:
friend class Graph<Node, Edge>;
ConcreteValueType (Path const& path, unsigned long line)
: Node (path, line)
{
type_info (static_type_info ());
}
};
//
//
//
class ValueTypeFactory : public virtual TwoWayOperation
{
public:
static Introspection::TypeInfo const&
static_type_info ();
protected:
friend class Graph<Node, Edge>;
ValueTypeFactory (Path const& path, unsigned long line)
: Node (path, line), TwoWayOperation (path, line)
{
type_info (static_type_info ());
}
};
}
}
}
#endif // CCF_IDL2_SEMANTIC_GRAPH_VALUE_TYPE_HPP
| [
"hillj@cs.iupui.edu"
] | hillj@cs.iupui.edu |
216fb3e3aa1b8308e286b0383a791ba22ee85c15 | b21a7616ec39e53c4c5d596c32fc2e6c6f3d5273 | /DiscrethMath/1 course/Combinatorics/num2choose.cpp | 8c865145f3bf97c4d291031fe1fad6edac8596b8 | [] | no_license | vladrus13/ITMO | d34fbd5feee0626c0fe5722b79dd928ee2a3f36a | c4ff564ea5f73e02354c0ae9248fee75df928b4e | refs/heads/master | 2022-02-23T03:13:36.794460 | 2022-02-10T22:24:16 | 2022-02-10T22:24:16 | 177,217,313 | 17 | 9 | null | 2020-08-07T15:06:37 | 2019-03-22T22:33:18 | Java | UTF-8 | C++ | false | false | 905 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <set>
#include <iomanip>
#include <cassert>
#include <fstream>
#include <bitset>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned int ui;
typedef unsigned long long ull;
ll c(int n, int k) {
if (k == 0) return 1;
if (n == k) return 1;
return c(n - 1, k) + c(n - 1, k - 1);
}
void rec(ll n, ll k, ll m) {
int num = 1;
while (k > 0) {
if (m < c(n - 1, k - 1)) {
cout << num << ' ';
k--;
} else {
m -= c(n - 1, k - 1);
}
n--;
num++;
}
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#else
freopen("num2choose.in", "r", stdin);
freopen("num2choose.out", "w", stdout);
#endif
ll n, k, m;
cin >> n >> k >> m;
rec(n, k, m);
return 0;
} | [
"vladrus13rus@yandex.ru"
] | vladrus13rus@yandex.ru |
6990e7da85c5e8c546136116e22a110809be3deb | 078695ff4f7cd90d7fa20352c17e172f3205aa9a | /src/InventoryManager.cpp | 5a0a72a95ac4374b18a321065bcb0648a2e7c9d6 | [
"MIT"
] | permissive | maca134/3den_inventory_manager | 73620f107958ea77148b4e5233411d0c26bd16c9 | 8a2227317bf1a462073049a078d86740d101d87f | refs/heads/master | 2021-01-21T12:12:05.524642 | 2017-08-31T22:18:21 | 2017-08-31T22:18:21 | 102,050,117 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,684 | cpp | /* #Soxeba
$[
1.063,
["inventory",[[0,0,1,1],0.025,0.04,"GUI_GRID"],0,0,0],
[-1000,"background",[2,"",["0 * GUI_GRID_W + GUI_GRID_X","0 * GUI_GRID_H + GUI_GRID_Y","40 * GUI_GRID_W","25 * GUI_GRID_H"],[-1,-1,-1,-1],[0,0,0,0.75],[-1,-1,-1,-1],"","-1"],[]],
[-1001,"title",[2,"Inventory Manager",["0 * GUI_GRID_W + GUI_GRID_X","0 * GUI_GRID_H + GUI_GRID_Y","40 * GUI_GRID_W","1 * GUI_GRID_H"],[-1,-1,-1,-1],[0,0,0,0.75],[-1,-1,-1,-1],"","-1"],[]],
[-1004,"sepV",[2,"",["19.76 * GUI_GRID_W + GUI_GRID_X","1.27 * GUI_GRID_H + GUI_GRID_Y","0.4 * GUI_GRID_W","23.5 * GUI_GRID_H"],[-1,-1,-1,-1],[0,0,0,0.75],[-1,-1,-1,-1],"","-1"],[]],
[-1006,"capacityBorder",[2,"",["20.5 * GUI_GRID_W + GUI_GRID_X","3.5 * GUI_GRID_H + GUI_GRID_Y","19 * GUI_GRID_W","1 * GUI_GRID_H"],[-1,-1,-1,-1],[0,0,0,0.75],[-1,-1,-1,-1],"","-1"],[]],
[-1008,"capacityBackground",[2,"",["21 * GUI_GRID_W + GUI_GRID_X","3.75 * GUI_GRID_H + GUI_GRID_Y","18 * GUI_GRID_W","0.5 * GUI_GRID_H"],[-1,-1,-1,-1],[1,1,1,0.25],[-1,-1,-1,-1],"","-1"],[]],
[-1005,"targetLbl",[2,"Target Vehicle: ",["0.5 * GUI_GRID_W + GUI_GRID_X","1.5 * GUI_GRID_H + GUI_GRID_Y","19 * GUI_GRID_W","1.5 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"","-1"],[]],
[-1002,"searchLbl",[2,"Search",["0.5 * GUI_GRID_W + GUI_GRID_X","3 * GUI_GRID_H + GUI_GRID_Y","3.5 * GUI_GRID_W","1 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"","-1"],[]],
[-1003,"currentInventoryLbl",[2,"Current Inventory",["32.5 * GUI_GRID_W + GUI_GRID_X","2.5 * GUI_GRID_H + GUI_GRID_Y","7 * GUI_GRID_W","1 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"","-1"],[]],
[1009,"capacityForeground",[2,"",["21 * GUI_GRID_W + GUI_GRID_X","3.75 * GUI_GRID_H + GUI_GRID_Y","9 * GUI_GRID_W","0.5 * GUI_GRID_H"],[-1,-1,-1,-1],[1,1,1,0.75],[-1,-1,-1,-1],"","-1"],[]],
[1501,"resultsTree",[2,"",["0.5 * GUI_GRID_W + GUI_GRID_X","6 * GUI_GRID_H + GUI_GRID_Y","19 * GUI_GRID_W","16.5 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"","-1"],[]],
[1500,"currentItemsList",[2,"",["20.5 * GUI_GRID_W + GUI_GRID_X","4.5 * GUI_GRID_H + GUI_GRID_Y","19 * GUI_GRID_W","15 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"","-1"],[]],
[1400,"searchInput",[2,"",["0.5 * GUI_GRID_W + GUI_GRID_X","4 * GUI_GRID_H + GUI_GRID_Y","15.5 * GUI_GRID_W","1.5 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Search Term","-1"],[]],
[1401,"amountInput",[2,"1",["0.5 * GUI_GRID_W + GUI_GRID_X","23 * GUI_GRID_H + GUI_GRID_Y","15.5 * GUI_GRID_W","1.5 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Amount of Items to Add","-1"],[]],
[1606,"clearSearchBtn",[2,"Clear",["16.5 * GUI_GRID_W + GUI_GRID_X","4 * GUI_GRID_H + GUI_GRID_Y","3 * GUI_GRID_W","1.5 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Clear Search","-1"],[]],
[1607,"addBtn",[2,"Add",["16.5 * GUI_GRID_W + GUI_GRID_X","23 * GUI_GRID_H + GUI_GRID_Y","3 * GUI_GRID_W","1.5 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Add X Items To Container","-1"],[]],
[1600,"deleteOneBtn",[2,"Delete 1",["20.5 * GUI_GRID_W + GUI_GRID_X","20 * GUI_GRID_H + GUI_GRID_Y","5.5 * GUI_GRID_W","2 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Delete 1 Item","-1"],[]],
[1601,"deleteAllBtn",[2,"Delete All",["27 * GUI_GRID_W + GUI_GRID_X","20 * GUI_GRID_H + GUI_GRID_Y","6 * GUI_GRID_W","2 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Delete All Selected Items","-1"],[]],
[1602,"clearBtn",[2,"Clear",["34 * GUI_GRID_W + GUI_GRID_X","20 * GUI_GRID_H + GUI_GRID_Y","5.5 * GUI_GRID_W","2 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Clear All Inventory","-1"],[]],
[1604,"exportBtn",[2,"Export",["20.5 * GUI_GRID_W + GUI_GRID_X","22.5 * GUI_GRID_H + GUI_GRID_Y","5.5 * GUI_GRID_W","2 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Export To Clipboard","-1"],[]],
[1605,"importBtn",[2,"Import",["27 * GUI_GRID_W + GUI_GRID_X","22.5 * GUI_GRID_H + GUI_GRID_Y","6 * GUI_GRID_W","2 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Import From Clipboard","-1"],[]],
[1603,"closeBtn",[2,"Close",["34 * GUI_GRID_W + GUI_GRID_X","22.5 * GUI_GRID_H + GUI_GRID_Y","5.5 * GUI_GRID_W","2 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"Close","-1"],[]]
]
*/
#define GUI_GRID_X (0)
#define GUI_GRID_Y (0)
#define GUI_GRID_W (0.025)
#define GUI_GRID_H (0.04)
class RscText;
class RscButton;
class RscListbox;
class RscEdit;
class RscTree;
class ctrlStaticBackgroundDisable;
class ctrlStaticBackgroundDisableTiles;
class EdenInventoryManager {
idd = 11548;
enableSimulation = 1;
enableDisplay = 1;
onLoad = "uiNamespace setVariable ['EdenInventoryManager', _this select 0]";
onUnload = "uiNamespace setVariable ['EdenInventoryManager', displayNull]";
class controlsBackground {
class BackgroundDisableTiles : ctrlStaticBackgroundDisableTiles {};
class BackgroundDisable : ctrlStaticBackgroundDisable {};
class background: RscText
{
idc = -1;
x = 0 * GUI_GRID_W + GUI_GRID_X;
y = 0 * GUI_GRID_H + GUI_GRID_Y;
w = 40 * GUI_GRID_W;
h = 25 * GUI_GRID_H;
colorBackground[] = {0,0,0,0.75};
};
class title: RscText
{
idc = -1;
text = "Inventory Manager"; //--- ToDo: Localize;
x = 0 * GUI_GRID_W + GUI_GRID_X;
y = 0 * GUI_GRID_H + GUI_GRID_Y;
w = 40 * GUI_GRID_W;
h = 1 * GUI_GRID_H;
colorBackground[] = {0,0,0,0.75};
};
class sepV: RscText
{
idc = -1;
x = 19.76 * GUI_GRID_W + GUI_GRID_X;
y = 1.27 * GUI_GRID_H + GUI_GRID_Y;
w = 0.4 * GUI_GRID_W;
h = 23.5 * GUI_GRID_H;
colorBackground[] = {0,0,0,0.75};
};
class capacityBorder: RscText
{
idc = -1;
x = 20.5 * GUI_GRID_W + GUI_GRID_X;
y = 3.5 * GUI_GRID_H + GUI_GRID_Y;
w = 19 * GUI_GRID_W;
h = 1 * GUI_GRID_H;
colorBackground[] = {0,0,0,0.75};
};
class capacityBackground: RscText
{
idc = -1;
x = 21 * GUI_GRID_W + GUI_GRID_X;
y = 3.75 * GUI_GRID_H + GUI_GRID_Y;
w = 18 * GUI_GRID_W;
h = 0.5 * GUI_GRID_H;
colorBackground[] = {1,1,1,0.25};
};
class targetLbl: RscText
{
idc = -1;
text = "Target Vehicle: "; //--- ToDo: Localize;
x = 0.5 * GUI_GRID_W + GUI_GRID_X;
y = 1.5 * GUI_GRID_H + GUI_GRID_Y;
w = 19 * GUI_GRID_W;
h = 1.5 * GUI_GRID_H;
};
class searchLbl: RscText
{
idc = -1;
text = "Search"; //--- ToDo: Localize;
x = 0.5 * GUI_GRID_W + GUI_GRID_X;
y = 3 * GUI_GRID_H + GUI_GRID_Y;
w = 3.5 * GUI_GRID_W;
h = 1 * GUI_GRID_H;
};
class currentInventoryLbl: RscText
{
idc = -1;
text = "Current Inventory"; //--- ToDo: Localize;
x = 32.5 * GUI_GRID_W + GUI_GRID_X;
y = 2.5 * GUI_GRID_H + GUI_GRID_Y;
w = 7 * GUI_GRID_W;
h = 1 * GUI_GRID_H;
};
};
class controls {
class capacityForeground: RscText
{
idc = 1009;
x = 21 * GUI_GRID_W + GUI_GRID_X;
y = 3.75 * GUI_GRID_H + GUI_GRID_Y;
w = 9 * GUI_GRID_W;
h = 0.5 * GUI_GRID_H;
colorBackground[] = {1,1,1,0.75};
};
class allItemsTree: RscTree
{
idc = 1501;
x = 0.5 * GUI_GRID_W + GUI_GRID_X;
y = 6 * GUI_GRID_H + GUI_GRID_Y;
w = 19 * GUI_GRID_W;
h = 16.5 * GUI_GRID_H;
};
class inventoryItemsTree: RscTree
{
idc = 1500;
x = 20.5 * GUI_GRID_W + GUI_GRID_X;
y = 4.5 * GUI_GRID_H + GUI_GRID_Y;
w = 19 * GUI_GRID_W;
h = 15 * GUI_GRID_H;
};
class searchInput: RscEdit
{
idc = 1400;
x = 0.5 * GUI_GRID_W + GUI_GRID_X;
y = 4 * GUI_GRID_H + GUI_GRID_Y;
w = 15.5 * GUI_GRID_W;
h = 1.5 * GUI_GRID_H;
tooltip = "Search Term"; //--- ToDo: Localize;
};
class amountInput: RscEdit
{
idc = 1401;
text = "1"; //--- ToDo: Localize;
x = 0.5 * GUI_GRID_W + GUI_GRID_X;
y = 23 * GUI_GRID_H + GUI_GRID_Y;
w = 15.5 * GUI_GRID_W;
h = 1.5 * GUI_GRID_H;
tooltip = "Amount of Items to Add"; //--- ToDo: Localize;
};
class clearSearchBtn: RscButton
{
idc = 1606;
text = "Clear"; //--- ToDo: Localize;
x = 16.5 * GUI_GRID_W + GUI_GRID_X;
y = 4 * GUI_GRID_H + GUI_GRID_Y;
w = 3 * GUI_GRID_W;
h = 1.5 * GUI_GRID_H;
tooltip = "Clear Search"; //--- ToDo: Localize;
onButtonClick = "[] spawn EIM_fnc_clearSearch";
};
class addBtn: RscButton
{
idc = 1607;
text = "Add"; //--- ToDo: Localize;
x = 16.5 * GUI_GRID_W + GUI_GRID_X;
y = 23 * GUI_GRID_H + GUI_GRID_Y;
w = 3 * GUI_GRID_W;
h = 1.5 * GUI_GRID_H;
tooltip = "Add X Items To Container"; //--- ToDo: Localize;
onButtonClick = "[] spawn EIM_fnc_addItem";
};
class deleteOneBtn: RscButton
{
idc = 1600;
text = "Delete 1"; //--- ToDo: Localize;
x = 20.5 * GUI_GRID_W + GUI_GRID_X;
y = 20 * GUI_GRID_H + GUI_GRID_Y;
w = 5.5 * GUI_GRID_W;
h = 2 * GUI_GRID_H;
tooltip = "Delete 1 Item"; //--- ToDo: Localize;
onButtonClick = "[] spawn EIM_fnc_deleteOne";
};
class deleteAllBtn: RscButton
{
idc = 1601;
text = "Delete All"; //--- ToDo: Localize;
x = 27 * GUI_GRID_W + GUI_GRID_X;
y = 20 * GUI_GRID_H + GUI_GRID_Y;
w = 6 * GUI_GRID_W;
h = 2 * GUI_GRID_H;
tooltip = "Delete All Selected Items"; //--- ToDo: Localize;
onButtonClick = "[] spawn EIM_fnc_deleteAll";
};
class clearBtn: RscButton
{
idc = 1602;
text = "Clear"; //--- ToDo: Localize;
x = 34 * GUI_GRID_W + GUI_GRID_X;
y = 20 * GUI_GRID_H + GUI_GRID_Y;
w = 5.5 * GUI_GRID_W;
h = 2 * GUI_GRID_H;
tooltip = "Clear All Inventory"; //--- ToDo: Localize;
onButtonClick = "[] spawn EIM_fnc_clearInventory";
};
class exportBtn: RscButton
{
idc = 1604;
text = "Export"; //--- ToDo: Localize;
x = 20.5 * GUI_GRID_W + GUI_GRID_X;
y = 22.5 * GUI_GRID_H + GUI_GRID_Y;
w = 5.5 * GUI_GRID_W;
h = 2 * GUI_GRID_H;
tooltip = "Export To Clipboard"; //--- ToDo: Localize;
onButtonClick = "[] spawn EIM_fnc_exportInventory";
};
class importBtn: RscButton
{
idc = 1605;
text = "Import"; //--- ToDo: Localize;
x = 27 * GUI_GRID_W + GUI_GRID_X;
y = 22.5 * GUI_GRID_H + GUI_GRID_Y;
w = 6 * GUI_GRID_W;
h = 2 * GUI_GRID_H;
tooltip = "Import From Clipboard"; //--- ToDo: Localize;
onButtonClick = "[] spawn EIM_fnc_importInventory";
};
class closeBtn: RscButton
{
idc = 1603;
text = "Close"; //--- ToDo: Localize;
x = 34 * GUI_GRID_W + GUI_GRID_X;
y = 22.5 * GUI_GRID_H + GUI_GRID_Y;
w = 5.5 * GUI_GRID_W;
h = 2 * GUI_GRID_H;
tooltip = "Close"; //--- ToDo: Localize;
onButtonClick = "((ctrlParent (_this select 0)) closeDisplay 1)";
};
};
}; | [
"maca134@googlemail.com"
] | maca134@googlemail.com |
6320f8e6cc934f58e811f3b3a351e8bf8d9fd9a8 | 5702eb53222af6e3e41672853c98e87c76fda0e3 | /util/cpp/Pipe.h | 4fbbb64a8a0db393e86f73402cc162649e3af158 | [] | no_license | agilecomputing/nomads | fe46464f62440d29d6074370c1750f69c75ea309 | 0c381bfe728fb24d170721367336c383f209d839 | refs/heads/master | 2021-01-18T11:12:29.670874 | 2014-12-13T00:46:40 | 2014-12-13T00:46:40 | 50,006,520 | 1 | 0 | null | 2016-01-20T05:19:14 | 2016-01-20T05:19:13 | null | UTF-8 | C++ | false | false | 1,829 | h | /*
* Pipe.h
*
* This file is part of the IHMC Util Library
* Copyright (c) 1993-2014 IHMC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 (GPLv3) as published by the Free Software Foundation.
*
* U.S. Government agencies and organizations may redistribute
* and/or modify this program under terms equivalent to
* "Government Purpose Rights" as defined by DFARS
* 252.227-7014(a)(12) (February 2014).
*
* Alternative licenses that allow for use within commercial products may be
* available. Contact Niranjan Suri at IHMC (nsuri@ihmc.us) for details.
*/
#ifndef INCL_PIPE_H
#define INCL_PIPE_H
#include <sys/stat.h>
#if defined (WIN32)
#include <fcntl.h>
#include <io.h>
#elif defined (UNIX)
#include <unistd.h>
#endif
namespace NOMADSUtil
{
class Pipe
{
public:
Pipe (void);
~Pipe (void);
int init (void);
// Get the file descriptor which can be used with read()
int getReadFileDescriptor (void);
// Get the file descriptor which can be used with write()
int getWriteFileDescriptor (void);
int sendBytes (void *pData, unsigned long ulSize);
int receive (void *pBuf, int iSize);
int receiveBytes (void *pBuf, unsigned long ulSize);
unsigned long bytesAvail (void);
protected:
Pipe (int fdRead, int fdWrite);
protected:
int _fdRead;
int _fdWrite;
struct stat statbuf;
};
inline int Pipe::getReadFileDescriptor (void)
{
return _fdRead;
}
inline int Pipe::getWriteFileDescriptor (void)
{
return _fdWrite;
}
}
#endif // #ifndef INCL_PIPE_H
| [
"giacomo.benincasa@gmail.com"
] | giacomo.benincasa@gmail.com |
d7f5abeaf1bc07391381afc90d2ab0451eccf88e | dcdf8a7edb8a765707459a540997750402f65bea | /src/qt/BitalGostrings.cpp | b94a58be9f8b6c0e9c5fa3aeb4b23a142e042e1e | [
"MIT"
] | permissive | ifinmakassar/BitalGO | a313fa0e2015cc02fa3dc8d63d8d3a692dd8b019 | f8f5e126a7c808f72ff85b32e28c09a45fe684ca | refs/heads/master | 2022-04-06T12:33:49.209408 | 2020-03-16T06:15:12 | 2020-03-16T06:15:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,995 | cpp |
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *BitalGo_strings[] = {
QT_TRANSLATE_NOOP("BitalGo-core", " mints deleted\n"),
QT_TRANSLATE_NOOP("BitalGo-core", " mints updated, "),
QT_TRANSLATE_NOOP("BitalGo-core", " unconfirmed transactions removed\n"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"(1 = keep tx meta data e.g. account owner and payment request information, 2 "
"= drop tx meta data)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Allow JSON-RPC connections from specified source. Valid for <ip> are a "
"single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or "
"a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Bind to given address and whitelist peers connecting to it. Use [host]:port "
"notation for IPv6"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Bind to given address to listen for JSON-RPC connections. Use [host]:port "
"notation for IPv6. This option can be specified multiple times (default: "
"bind to all interfaces)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Calculated accumulator checkpoint is not what is recorded by block index"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Cannot obtain a lock on data directory %s. BitalGo Core is probably already "
"running."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Change automatic finalized budget voting behavior. mode=auto: Vote for only "
"exact finalized budget match to my generated budget. (string, default: auto)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Continuously rate-limit free transactions to <n>*1000 bytes per minute "
"(default:%u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Create new files with system default permissions, instead of umask 077 (only "
"effective with disabled wallet functionality)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Delete all wallet transactions and only recover those parts of the "
"blockchain through -rescan on startup"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Delete all zerocoin spends and mints that have been recorded to the "
"blockchain database and reindex them (0-1, default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Disable all ALG specific functionality (Masternodes, Zerocoin, SwiftX, "
"Budgeting) (0-1, default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Distributed under the MIT software license, see the accompanying file "
"COPYING or <http://www.opensource.org/licenses/mit-license.php>."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Enable SwiftX, show confirmations for locked transactions (bool, default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Enable automatic Zerocoin minting from specific addresses (0-1, default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Enable automatic wallet backups triggered after each zALG minting (0-1, "
"default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Enable or disable staking functionality for ALG inputs (0-1, default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Enable or disable staking functionality for zALG inputs (0-1, default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Enable spork administration functionality with the appropriate private key."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Enter regression test mode, which uses a special chain in which blocks can "
"be solved instantly."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Error: Listening for incoming connections failed (listen returned error %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Error: The transaction is larger than the maximum allowed transaction size!"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Error: The transaction was rejected! This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds!"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Error: Unsupported argument -checklevel found. Checklevel must be level 4."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Error: Unsupported argument -socks found. Setting SOCKS version isn't "
"possible anymore, only SOCKS5 proxies are supported."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Execute command when a relevant alert is received or we see a really long "
"fork (%s in cmd is replaced by message)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Execute command when the best block changes and its size is over (%s in cmd "
"is replaced by block hash, %d with the block size)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Failed to find coin set amongst held coins with less than maxNumber of Spends"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Fees (in ALG/Kb) smaller than this are considered zero fee for relaying "
"(default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Fees (in ALG/Kb) smaller than this are considered zero fee for transaction "
"creation (default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Flush database activity from memory pool to disk log every <n> megabytes "
"(default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Found unconfirmed denominated outputs, will wait till they confirm to "
"continue."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"If paytxfee is not set, include enough fee so transactions begin "
"confirmation on average within n blocks (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"In rare cases, a spend with 7 coins exceeds our maximum allowable "
"transaction size, please retry spend using 6 or less coins"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"In this mode -genproclimit controls how many blocks are generated "
"immediately."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Insufficient or insufficient confirmed funds, you might need to wait a few "
"minutes and try again."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay "
"fee of %s to prevent stuck transactions)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Keep the specified amount available for spending at all times (default: 0)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Log transaction priority and fee per kB when mining blocks (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Maintain a full transaction index, used by the getrawtransaction rpc call "
"(default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Maximum average size of an index occurrence in the block spam filter "
"(default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Maximum size of data in data carrier transactions we relay and mine "
"(default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Maximum size of the list of indexes in the block spam filter (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Maximum total fees to use in a single wallet transaction, setting too low "
"may abort large transactions (default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Obfuscation uses exact denominated amounts to send funds, you might simply "
"need to anonymize some more coins."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Output debugging information (default: %u, supplying <category> is optional)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Preferred Denomination for automatically minted Zerocoin "
"(1/5/10/50/100/500/1000/5000), 0 for no preference. default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Query for peer addresses via DNS lookup, if low on addresses (default: 1 "
"unless -connect)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Randomize credentials for every proxy connection. This enables Tor stream "
"isolation (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Require high priority for relaying free or low-fee transactions (default:%u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Send trace/debug info to console instead of debug.log file (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Set the number of included blocks to precompute per cycle. (minimum: %d) "
"(maximum: %d) (default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = "
"leave that many cores free, default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Set the number of threads for coin generation if enabled (-1 = all cores, "
"default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Show N confirmations for a successfully locked transaction (0-9999, default: "
"%u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Specify custom backup path to add a copy of any automatic zALG backup. If "
"set as dir, every backup generates a timestamped file. If set as file, will "
"rewrite to that file every backup. If backuppath is set as well, 4 backups "
"will happen"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Specify custom backup path to add a copy of any wallet backup. If set as "
"dir, every backup generates a timestamped file. If set as file, will rewrite "
"to that file every backup."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Support filtering of blocks and transaction with bloom filters (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"SwiftX requires inputs with at least 6 confirmations, you might need to wait "
"a few minutes and try again."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"The block database contains a block which appears to be from the future. "
"This may be due to your computer's date and time being set incorrectly. Only "
"rebuild the block database if you are sure that your computer's date and "
"time are correct"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"staking or merchant applications!"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"This product includes software developed by the OpenSSL Project for use in "
"the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software "
"written by Eric Young and UPnP software written by Thomas Bernard."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Total length of network version string (%i) exceeds maximum length (%i). "
"Reduce the number or size of uacomments."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Unable to bind to %s on this computer. BitalGo Core is probably already running."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Unable to locate enough Obfuscation denominated funds for this transaction."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Unable to locate enough Obfuscation non-denominated funds for this "
"transaction that are not equal 10000 ALG."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Unable to locate enough funds for this transaction that are not equal 10000 "
"ALG."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: "
"%s)"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Warning: -maxtxfee is set very high! Fees this large could be paid on a "
"single transaction."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong BitalGo Core will not work properly."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Warning: The network does not appear to fully agree! Some miners appear to "
"be experiencing issues."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Warning: We do not appear to fully agree with our peers! You may need to "
"upgrade, or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Whitelist peers connecting from the given netmask or IP address. Can be "
"specified multiple times."),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"Whitelisted peers cannot be DoS banned and their transactions are always "
"relayed, even if they are already in the mempool, useful e.g. for a gateway"),
QT_TRANSLATE_NOOP("BitalGo-core", ""
"You must specify a masternodeprivkey in the configuration. Please see "
"documentation for help."),
QT_TRANSLATE_NOOP("BitalGo-core", "(9436 could be used only on mainnet)"),
QT_TRANSLATE_NOOP("BitalGo-core", "(default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "(default: 1)"),
QT_TRANSLATE_NOOP("BitalGo-core", "(must be 9436 for mainnet)"),
QT_TRANSLATE_NOOP("BitalGo-core", "<category> can be:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("BitalGo-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Accept public REST requests (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("BitalGo-core", "Adding Wrapped Serials supply..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("BitalGo-core", "Already have that input."),
QT_TRANSLATE_NOOP("BitalGo-core", "Always query for peer addresses via DNS lookup (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Append comment to the user agent string"),
QT_TRANSLATE_NOOP("BitalGo-core", "Attempt to force blockchain corruption recovery"),
QT_TRANSLATE_NOOP("BitalGo-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("BitalGo-core", "Automatically create Tor hidden service (default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Block creation options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Calculating missing accumulators..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Can't denominate: no compatible inputs left."),
QT_TRANSLATE_NOOP("BitalGo-core", "Can't find random Masternode."),
QT_TRANSLATE_NOOP("BitalGo-core", "Can't mix while sync in progress."),
QT_TRANSLATE_NOOP("BitalGo-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("BitalGo-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Cannot resolve -whitebind address: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("BitalGo-core", "CoinSpend: Accumulator witness does not verify"),
QT_TRANSLATE_NOOP("BitalGo-core", "CoinSpend: failed check"),
QT_TRANSLATE_NOOP("BitalGo-core", "Collateral not valid."),
QT_TRANSLATE_NOOP("BitalGo-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Connect through SOCKS5 proxy"),
QT_TRANSLATE_NOOP("BitalGo-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("BitalGo-core", "Connection options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"),
QT_TRANSLATE_NOOP("BitalGo-core", "Copyright (C) 2014-%i The Dash Core Developers"),
QT_TRANSLATE_NOOP("BitalGo-core", "Copyright (C) 2015-%i The BitalGo Core Developers"),
QT_TRANSLATE_NOOP("BitalGo-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("BitalGo-core", "Could not parse masternode.conf"),
QT_TRANSLATE_NOOP("BitalGo-core", "Couldn't generate the accumulator witness"),
QT_TRANSLATE_NOOP("BitalGo-core", "Debugging/Testing options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Delete blockchain folders and resync from scratch"),
QT_TRANSLATE_NOOP("BitalGo-core", "Disable OS notifications for incoming transactions (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Disable safemode, override a real safe mode event (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Display the stake modifier calculations in the debug.log file."),
QT_TRANSLATE_NOOP("BitalGo-core", "Display verbose coin stake messages in the debug.log file."),
QT_TRANSLATE_NOOP("BitalGo-core", "Do not load the wallet and disable wallet RPC calls"),
QT_TRANSLATE_NOOP("BitalGo-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("BitalGo-core", "Done loading"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable automatic Zerocoin minting (0-1, default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable precomputation of zALG spends and stakes (0-1, default %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable publish hash block in <address>"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable publish hash transaction (locked via SwiftX) in <address>"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable publish hash transaction in <address>"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable publish raw block in <address>"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable publish raw transaction (locked via SwiftX) in <address>"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable publish raw transaction in <address>"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable staking functionality (0-1, default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Enable the client to act as a masternode (0-1, default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Entries are full."),
QT_TRANSLATE_NOOP("BitalGo-core", "Error connecting to Masternode."),
QT_TRANSLATE_NOOP("BitalGo-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error loading block database"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error loading wallet.dat: Wallet requires newer version of BitalGo Core"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error opening block database"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error reading from database, shutting down."),
QT_TRANSLATE_NOOP("BitalGo-core", "Error recovering public key."),
QT_TRANSLATE_NOOP("BitalGo-core", "Error writing zerocoinDB to disk"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error: A fatal internal error occured, see debug.log for details"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error: A fatal internal error occurred, see debug.log for details"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error: Can't select current denominated inputs"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error: No valid utxo!"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error: Unsupported argument -tor found, use -onion."),
QT_TRANSLATE_NOOP("BitalGo-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("BitalGo-core", "Error: You already have pending entries in the Obfuscation pool"),
QT_TRANSLATE_NOOP("BitalGo-core", "Failed to calculate accumulator checkpoint"),
QT_TRANSLATE_NOOP("BitalGo-core", "Failed to create mint"),
QT_TRANSLATE_NOOP("BitalGo-core", "Failed to find Zerocoins in wallet.dat"),
QT_TRANSLATE_NOOP("BitalGo-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("BitalGo-core", "Failed to parse host:port string"),
QT_TRANSLATE_NOOP("BitalGo-core", "Failed to read block"),
QT_TRANSLATE_NOOP("BitalGo-core", "Failed to select a zerocoin"),
QT_TRANSLATE_NOOP("BitalGo-core", "Failed to wipe zerocoinDB"),
QT_TRANSLATE_NOOP("BitalGo-core", "Failed to write coin serial number into wallet"),
QT_TRANSLATE_NOOP("BitalGo-core", "Fee (in ALG/kB) to add to transactions you send (default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Finalizing transaction."),
QT_TRANSLATE_NOOP("BitalGo-core", "Force safe mode (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Found enough users, signing ( waiting %s )"),
QT_TRANSLATE_NOOP("BitalGo-core", "Found enough users, signing ..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Generate coins (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "How many blocks to check at startup (default: %u, 0 = all)"),
QT_TRANSLATE_NOOP("BitalGo-core", "If <category> is not supplied, output all debugging information."),
QT_TRANSLATE_NOOP("BitalGo-core", "Importing..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("BitalGo-core", "Include IP addresses in debug output (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Incompatible mode."),
QT_TRANSLATE_NOOP("BitalGo-core", "Incompatible version."),
QT_TRANSLATE_NOOP("BitalGo-core", "Incorrect or no genesis block found. Wrong datadir for network?"),
QT_TRANSLATE_NOOP("BitalGo-core", "Information"),
QT_TRANSLATE_NOOP("BitalGo-core", "Initialization sanity check failed. BitalGo Core is shutting down."),
QT_TRANSLATE_NOOP("BitalGo-core", "Input is not valid."),
QT_TRANSLATE_NOOP("BitalGo-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("BitalGo-core", "Insufficient funds."),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid -onion address or hostname: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid amount for -maxtxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid amount for -reservebalance=<amount>"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid amount"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid masternodeprivkey. Please see documenation."),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid netmask specified in -whitelist: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid port detected in masternode.conf"),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid private key."),
QT_TRANSLATE_NOOP("BitalGo-core", "Invalid script detected."),
QT_TRANSLATE_NOOP("BitalGo-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Last Obfuscation was too recent."),
QT_TRANSLATE_NOOP("BitalGo-core", "Last successful Obfuscation action was too recent."),
QT_TRANSLATE_NOOP("BitalGo-core", "Limit size of signature cache to <n> entries (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Line: %d"),
QT_TRANSLATE_NOOP("BitalGo-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Listen for connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Loading block index..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Loading budget cache..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Loading masternode cache..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Loading masternode payment cache..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Loading sporks..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Loading wallet... (%3.2f %%)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Location of the auth cookie (default: data dir)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Lock is already in place."),
QT_TRANSLATE_NOOP("BitalGo-core", "Lock masternodes from masternode configuration file (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Lookup(): Invalid -proxy address or hostname: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Maintain at most <n> connections to peers (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Masternode options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Masternode queue is full."),
QT_TRANSLATE_NOOP("BitalGo-core", "Masternode:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Mint did not make it into blockchain"),
QT_TRANSLATE_NOOP("BitalGo-core", "Missing input transaction information."),
QT_TRANSLATE_NOOP("BitalGo-core", "Mixing in progress..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Need address because change is not exact"),
QT_TRANSLATE_NOOP("BitalGo-core", "Need to specify a port with -whitebind: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "No Masternodes detected."),
QT_TRANSLATE_NOOP("BitalGo-core", "No compatible Masternode found."),
QT_TRANSLATE_NOOP("BitalGo-core", "No funds detected in need of denominating."),
QT_TRANSLATE_NOOP("BitalGo-core", "No matching denominations found for mixing."),
QT_TRANSLATE_NOOP("BitalGo-core", "Node relay options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Non-standard public key detected."),
QT_TRANSLATE_NOOP("BitalGo-core", "Not compatible with existing transactions."),
QT_TRANSLATE_NOOP("BitalGo-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("BitalGo-core", "Not in the Masternode list."),
QT_TRANSLATE_NOOP("BitalGo-core", "Number of automatic wallet backups (default: 10)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Number of custom location backups to retain (default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Obfuscation is idle."),
QT_TRANSLATE_NOOP("BitalGo-core", "Obfuscation request complete:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Obfuscation request incomplete:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Only accept block chain matching built-in checkpoints (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("BitalGo-core", "Percentage of automatically minted Zerocoin (1-100, default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Preparing for resync..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Prepend debug output with timestamp (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Print version and exit"),
QT_TRANSLATE_NOOP("BitalGo-core", "RPC server options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Randomly drop 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("BitalGo-core", "Randomly fuzz 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("BitalGo-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("BitalGo-core", "Recalculating ALG supply..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Recalculating minted ZALG..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Recalculating spent ZALG..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Receive and display P2P network alerts (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Reindex the ALG and zALG money supply statistics"),
QT_TRANSLATE_NOOP("BitalGo-core", "Reindex the accumulator database"),
QT_TRANSLATE_NOOP("BitalGo-core", "Reindexing zerocoin database..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Reindexing zerocoin failed"),
QT_TRANSLATE_NOOP("BitalGo-core", "Relay and mine data carrier transactions (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Relay non-P2SH multisig (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("BitalGo-core", "Rescanning..."),
QT_TRANSLATE_NOOP("BitalGo-core", "ResetMintZerocoin finished: "),
QT_TRANSLATE_NOOP("BitalGo-core", "ResetSpentZerocoin finished: "),
QT_TRANSLATE_NOOP("BitalGo-core", "Run a thread to flush wallet periodically (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("BitalGo-core", "Selected coins value is less than payment target"),
QT_TRANSLATE_NOOP("BitalGo-core", "Send transactions as zero-fee transactions if possible (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Session not complete!"),
QT_TRANSLATE_NOOP("BitalGo-core", "Session timed out."),
QT_TRANSLATE_NOOP("BitalGo-core", "Set database cache size in megabytes (%d to %d, default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Set external address:port to get to this masternode (example: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Set key pool size to <n> (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Set maximum block size in bytes (default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Set minimum block size in bytes (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Set the Maximum reorg depth (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Set the masternode private key"),
QT_TRANSLATE_NOOP("BitalGo-core", "Set the number of threads to service RPC calls (default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Show all debugging options (usage: --help -help-debug)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Signing failed."),
QT_TRANSLATE_NOOP("BitalGo-core", "Signing timed out."),
QT_TRANSLATE_NOOP("BitalGo-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("BitalGo-core", "Specify configuration file (default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Specify data directory"),
QT_TRANSLATE_NOOP("BitalGo-core", "Specify masternode configuration file (default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Specify pid file (default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("BitalGo-core", "Spend Valid"),
QT_TRANSLATE_NOOP("BitalGo-core", "Spend unconfirmed change when sending transactions (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Staking options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Stop running after importing blocks from disk (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Submitted following entries to masternode: %u / %d"),
QT_TRANSLATE_NOOP("BitalGo-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"),
QT_TRANSLATE_NOOP("BitalGo-core", "Submitted to masternode, waiting in queue %s"),
QT_TRANSLATE_NOOP("BitalGo-core", "Support the zerocoin light node protocol (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "SwiftX options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Synchronization failed"),
QT_TRANSLATE_NOOP("BitalGo-core", "Synchronization finished"),
QT_TRANSLATE_NOOP("BitalGo-core", "Synchronization pending..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Synchronizing budgets..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Synchronizing masternode winners..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Synchronizing masternodes..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Synchronizing sporks..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Syncing zALG wallet..."),
QT_TRANSLATE_NOOP("BitalGo-core", "The coin spend has been used"),
QT_TRANSLATE_NOOP("BitalGo-core", "The transaction did not verify"),
QT_TRANSLATE_NOOP("BitalGo-core", "This help message"),
QT_TRANSLATE_NOOP("BitalGo-core", "This is experimental software."),
QT_TRANSLATE_NOOP("BitalGo-core", "This is intended for regression testing tools and app development."),
QT_TRANSLATE_NOOP("BitalGo-core", "This is not a Masternode."),
QT_TRANSLATE_NOOP("BitalGo-core", "Threshold for disconnecting misbehaving peers (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Too many spends needed"),
QT_TRANSLATE_NOOP("BitalGo-core", "Tor control port password (default: empty)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Tor control port to use if onion listening enabled (default: %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Transaction Created"),
QT_TRANSLATE_NOOP("BitalGo-core", "Transaction Mint Started"),
QT_TRANSLATE_NOOP("BitalGo-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("BitalGo-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("BitalGo-core", "Transaction created successfully."),
QT_TRANSLATE_NOOP("BitalGo-core", "Transaction fees are too high."),
QT_TRANSLATE_NOOP("BitalGo-core", "Transaction not valid."),
QT_TRANSLATE_NOOP("BitalGo-core", "Transaction too large for fee policy"),
QT_TRANSLATE_NOOP("BitalGo-core", "Transaction too large"),
QT_TRANSLATE_NOOP("BitalGo-core", "Transmitting final transaction."),
QT_TRANSLATE_NOOP("BitalGo-core", "Trying to spend an already spent serial #, try again."),
QT_TRANSLATE_NOOP("BitalGo-core", "Unable to bind to %s on this computer (bind returned error %s)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Unable to find transaction containing mint"),
QT_TRANSLATE_NOOP("BitalGo-core", "Unable to sign spork message, wrong key?"),
QT_TRANSLATE_NOOP("BitalGo-core", "Unable to start HTTP server. See debug log for details."),
QT_TRANSLATE_NOOP("BitalGo-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "Unknown state: id = %u"),
QT_TRANSLATE_NOOP("BitalGo-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("BitalGo-core", "Use UPnP to map the listening port (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Use a custom max chain reorganization depth (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Use block spam filter (default: %u)"),
QT_TRANSLATE_NOOP("BitalGo-core", "Use the test network"),
QT_TRANSLATE_NOOP("BitalGo-core", "User Agent comment (%s) contains unsafe characters."),
QT_TRANSLATE_NOOP("BitalGo-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("BitalGo-core", "Value is below the smallest available denomination (= 1) of zALG"),
QT_TRANSLATE_NOOP("BitalGo-core", "Value more than Obfuscation pool maximum allows."),
QT_TRANSLATE_NOOP("BitalGo-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("BitalGo-core", "Wallet %s resides outside data directory %s"),
QT_TRANSLATE_NOOP("BitalGo-core", "Wallet is locked."),
QT_TRANSLATE_NOOP("BitalGo-core", "Wallet needed to be rewritten: restart BitalGo Core to complete"),
QT_TRANSLATE_NOOP("BitalGo-core", "Wallet options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Wallet window title"),
QT_TRANSLATE_NOOP("BitalGo-core", "Warning"),
QT_TRANSLATE_NOOP("BitalGo-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("BitalGo-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."),
QT_TRANSLATE_NOOP("BitalGo-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."),
QT_TRANSLATE_NOOP("BitalGo-core", "Will retry..."),
QT_TRANSLATE_NOOP("BitalGo-core", "You don't have enough Zerocoins in your wallet"),
QT_TRANSLATE_NOOP("BitalGo-core", "You need to rebuild the database using -reindex to change -txindex"),
QT_TRANSLATE_NOOP("BitalGo-core", "Your entries added successfully."),
QT_TRANSLATE_NOOP("BitalGo-core", "Your transaction was accepted into the pool!"),
QT_TRANSLATE_NOOP("BitalGo-core", "Zapping all transactions from wallet..."),
QT_TRANSLATE_NOOP("BitalGo-core", "ZeroMQ notification options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "Zerocoin options:"),
QT_TRANSLATE_NOOP("BitalGo-core", "could not get lock on cs_spendcache"),
QT_TRANSLATE_NOOP("BitalGo-core", "isValid(): Invalid -proxy address or hostname: '%s'"),
QT_TRANSLATE_NOOP("BitalGo-core", "on startup"),
QT_TRANSLATE_NOOP("BitalGo-core", "wallet.dat corrupt, salvage failed"),
};
| [
"kyzer@traebit.ca"
] | kyzer@traebit.ca |
54c8814db2d143243de8cbc4a1ac31c6de4ae2a5 | 66433c1b726dddfec94706d3dfa6a029c904b94b | /0.3/a1/tasks.cpp | a0d8c300c15f5139513d3dd5ded9f2485047a8b1 | [] | no_license | LeandroPerrotta/DarghosTFS04_87 | 2177feb1d288b1d0341c682d7d12ab28320683ec | 392291bd826cfd30e369c440303ad1588016606f | refs/heads/master | 2023-06-15T13:59:44.906677 | 2021-07-16T22:32:47 | 2021-07-16T22:32:47 | 386,390,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,441 | cpp | //////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
//////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////
#include "otpch.h"
#include "tasks.h"
#include "outputmessage.h"
#include "game.h"
extern Game g_game;
#if defined __EXCEPTION_TRACER__
#include "exception.h"
#endif
bool Dispatcher::m_shutdown = false;
Dispatcher::Dispatcher()
{
OTSYS_THREAD_LOCKVARINIT(m_taskLock);
OTSYS_THREAD_SIGNALVARINIT(m_taskSignal);
OTSYS_CREATE_THREAD(Dispatcher::dispatcherThread, NULL);
}
OTSYS_THREAD_RETURN Dispatcher::dispatcherThread(void* p)
{
#if defined __EXCEPTION_TRACER__
ExceptionHandler dispatcherExceptionHandler;
dispatcherExceptionHandler.InstallHandler();
#endif
srand((unsigned int)OTSYS_TIME());
while(!Dispatcher::m_shutdown)
{
Task* task = NULL;
// check if there are tasks waiting
OTSYS_THREAD_LOCK(getDispatcher().m_taskLock, "")
if(getDispatcher().m_taskList.empty())
{
//if the list is empty wait for signal
OTSYS_THREAD_WAITSIGNAL(getDispatcher().m_taskSignal, getDispatcher().m_taskLock);
}
if(!getDispatcher().m_taskList.empty() && !Dispatcher::m_shutdown)
{
// take the first task
task = getDispatcher().m_taskList.front();
getDispatcher().m_taskList.pop_front();
}
OTSYS_THREAD_UNLOCK(getDispatcher().m_taskLock, "");
// finally execute the task...
if(task)
{
OutputMessagePool::getInstance()->startExecutionFrame();
(*task)();
delete task;
OutputMessagePool::getInstance()->sendAll();
g_game.clearSpectatorCache();
}
}
#if defined __EXCEPTION_TRACER__
dispatcherExceptionHandler.RemoveHandler();
#endif
#ifndef WIN32
return NULL;
#endif
}
void Dispatcher::addTask(Task* task)
{
OTSYS_THREAD_LOCK(m_taskLock, "");
bool do_signal = false;
if(!Dispatcher::m_shutdown)
{
do_signal = m_taskList.empty();
m_taskList.push_back(task);
}
#ifdef _DEBUG
else
std::cout << "Error: [Dispatcher::addTask] Dispatcher thread is terminated." << std::endl;
#endif
OTSYS_THREAD_UNLOCK(m_taskLock, "");
// send a signal if the list was empty
if(do_signal)
OTSYS_THREAD_SIGNAL_SEND(m_taskSignal);
}
void Dispatcher::flush()
{
Task* task = NULL;
while(!m_taskList.empty())
{
task = getDispatcher().m_taskList.front();
m_taskList.pop_front();
(*task)();
delete task;
OutputMessagePool::getInstance()->sendAll();
g_game.clearSpectatorCache();
}
}
void Dispatcher::stop()
{
OTSYS_THREAD_LOCK(m_taskLock, "");
flush();
m_shutdown = true;
OTSYS_THREAD_UNLOCK(m_taskLock, "");
}
| [
"leandro_perrotta@hotmail.com"
] | leandro_perrotta@hotmail.com |
610504608efec634bd3ed68809a4ebeca4c6a66f | f821e40a2d0d8f3eed02f197a1e4007f4e1b9799 | /src/core/app/al_WindowApp.cpp | a5cf104456fc72b2025d33bdcef82a6f8fb7b794 | [] | no_license | worldmaking/allolib | e5235e4de66b862003e5b4343fd2e4f755d0fbb3 | 1585da0cc2ebb533865858142c9fec341aa39406 | refs/heads/master | 2021-05-14T12:22:07.464372 | 2018-01-05T17:00:14 | 2018-01-05T17:00:14 | 116,406,076 | 0 | 0 | null | 2018-01-05T16:42:19 | 2018-01-05T16:42:19 | null | UTF-8 | C++ | false | false | 1,773 | cpp | #include "al/core/app/al_WindowApp.hpp"
#include "al/core/graphics/al_GLFW.hpp"
#include "al/core/graphics/al_GPUObject.hpp"
using namespace al;
bool WindowApp::StandardWindowAppKeyControls::keyDown(const Keyboard& k){
if(k.ctrl()){
switch(k.key()){
case 'q': window().close(); return false;
// case 'h': window().hide(); return false;
// case 'm': window().iconify(); return false;
case 'c': window().cursorHideToggle(); return false;
default:;
}
}
else{
switch(k.key()){
case Keyboard::ESCAPE: window().fullScreenToggle(); return false;
default:;
}
}
return true;
}
WindowApp::WindowApp() {
append(stdControls);
append(windowEventHandler());
}
void WindowApp::open() {
glfw::init();
create();
onCreate();
}
void WindowApp::loop() {
onDraw();
refresh();
}
void WindowApp::closeApp() {
destroy(); // destroy window
glfw::terminate(); // this also closes existing windows
}
void WindowApp::start() {
open();
startFPS();
while (!shouldQuit()) {
loop();
tickFPS();
}
closeApp();
}
// call user event functions inside WindowEventHandler class
bool WindowApp::keyDown(const Keyboard& k) {
onKeyDown(k);
return true;
}
bool WindowApp::keyUp(const Keyboard& k) {
onKeyUp(k);
return true;
}
bool WindowApp::mouseDown(const Mouse& m) {
onMouseDown(m);
return true;
}
bool WindowApp::mouseDrag(const Mouse& m) {
onMouseDrag(m);
return true;
}
bool WindowApp::mouseMove(const Mouse& m) {
onMouseMove(m);
return true;
}
bool WindowApp::mouseUp(const Mouse& m) {
onMouseUp(m);
return true;
}
bool WindowApp::resize(int dw, int dh) {
onResize(dw, dh);
return true;
}
bool WindowApp::visibility(bool v) {
onVisibility(v);
return true;
} | [
"younkeehong@gmail.com"
] | younkeehong@gmail.com |
8c6870d4ea91942d97b726091c87216d592696df | ea537927ff592c52b8ae13ffff69f1b3c58e4d48 | /video/opengl/OpenGL_model.cpp | 06291b4edc2d523144323165c8e7d3929f76c612 | [
"MIT"
] | permissive | 124327288/YuYu | eacbcbd496ee5032dcf4fdc4fc2dbc4c7b767e1e | f3598899ae5e6892a6b5d546bb0849f5d6a3c5a8 | refs/heads/main | 2023-02-26T03:07:04.273960 | 2021-01-25T20:56:28 | 2021-01-25T20:56:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cpp | #include "yy.h"
#include "OpenGL.h"
#include "OpenGL_model.h"
OpenGLModel::OpenGLModel()
:
m_VAO(0),
m_vBuffer(0),
m_iBuffer(0),
m_iCount(0)
{
}
OpenGLModel::~OpenGLModel()
{
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &m_vBuffer);
glDeleteBuffers(1, &m_iBuffer);
glDeleteVertexArrays(1,&m_VAO);
}
| [
"artembasov@outlook.com"
] | artembasov@outlook.com |
b998bb618b8fdc5202d1eade78f7576bd24c77ff | 4797c7058b7157e3d942e82cf8ad94b58be488ae | /PlayerShip.cpp | f70fc2002f2cfb0b6a7261c671bdf0ac7d214a00 | [] | no_license | koguz/DirectX-Space-Game | 2d1d8179439870fd1427beb9624f1c5452546c39 | be672051fd0009cbd5851c92bd344d3b23645474 | refs/heads/master | 2020-05-18T02:11:47.963185 | 2011-05-25T14:35:26 | 2011-05-25T14:35:26 | 1,799,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,804 | cpp | #include "PlayerShip.h"
PlayerShip::PlayerShip():BaseObject()
{
speed = 0.0f;
lastShot = 0;
}
bool PlayerShip::Init(IDirect3DDevice9 *d, IDirectSound8 *s)
{
((MyMesh*)(this))->Init(d, "ship01.x");
Sound = s;
Engine.Init(Sound, "PSEngine.wav");
Fire.Init(Sound, "PSFire.wav");
Fire.SetLoop(false);
Scratch.Init(Sound, "Scratch.wav");
Scratch.SetLoop(false);
HitSound.Init(Sound, "hitship.wav");
HitSound.SetLoop(false);
/*
Mission1.Init(Sound, "mission01.wav");
Mission1.SetLoop(false);
Mission1.Play();
*/
Engine.SetVolume(-800);
Engine.Play();
maxSpeed = 6.0f;
minSpeed = 0.6f;
casSpeed = 2.0f;
laserInterval = 500;
health = 2000;
return true;
}
void PlayerShip::Scratched()
{
Scratch.setPosition(position);
Scratch.Play();
health -= 5;
}
void PlayerShip::Hit(int d)
{
health -= d;
HitSound.Play();
}
void PlayerShip::Update(float deltaTime)
{
if (health < 2000 && GetTickCount() - lastGen > 100 )
{
health++;
lastGen = GetTickCount();
}
time = deltaTime;
TranslateV(speed * look * deltaTime);
Engine.setPosition(position);
Fire.setPosition(position);
HitSound.setPosition(position);
// Mission1.setPosition(position);
std::vector<Laser>::iterator temp;
std::vector<Laser>::iterator toDel;
bool d = false;
for(temp = lasers.begin(); temp != lasers.end(); temp++)
{
(*temp).Update(time);
// (*temp).Draw();
if (abs((*temp).getPosition().x) > 200 || abs((*temp).getPosition().y) > 200 || abs((*temp).getPosition().z) > 200 )
{
toDel = temp;
d = true;
}
if ((*temp).getHit())
{
toDel = temp;
d = true;
}
}
if (d)
lasers.erase(toDel);
}
void PlayerShip::SpeedUp()
{
SetSpeed(maxSpeed);
}
void PlayerShip::SpeedDown()
{
SetSpeed(minSpeed);
}
void PlayerShip::SpeedNormal()
{
SetSpeed(casSpeed);
}
void PlayerShip::SetSpeed(float s)
{
if (s == speed) return;
if (s >= casSpeed && s < maxSpeed && speed != s)
Engine.setFrequency(0);
else if (s >= maxSpeed && speed != s)
Engine.setFrequency(24000);
else if (s >= minSpeed && s < casSpeed && speed != s)
Engine.setFrequency(20000);
speed = s;
}
void PlayerShip::FireLaser()
{
if (health < 0) return;
if (GetTickCount() - lastShot > laserInterval)
{
Laser laser1(Device, Laser::RED);
Laser laser2(Device, Laser::RED);
laser1.SetRotation(rotationMatrix);
laser1.TranslateV(position + (right * 0.6f));
laser1.SetOrientation(up, right, look);
laser2.SetRotation(rotationMatrix);
laser2.TranslateV(position - (right * 0.6f));
laser2.SetOrientation(up, right, look);
lasers.push_back(laser1);
lasers.push_back(laser2);
Fire.Play();
lastShot = GetTickCount();
}
else return;
}
| [
"kayaoguz@gmail.com"
] | kayaoguz@gmail.com |
a46b77f82879c308c052cfd25a4beeb404b8f76f | 77d707e44c708aeac4fe9271c77aebc7d2707180 | /src/main.cpp | 388696a1586940d2345d1919725eab5f798d180f | [] | no_license | aksoysamet/Minigames | d95db1d88ce251762468abe9e9cea77dbcf8a9ef | 264c88fd5a357c3d4abbb20cc1c3b2c4915e68fc | refs/heads/master | 2022-12-03T08:41:01.953770 | 2020-08-15T11:26:11 | 2020-08-15T11:26:11 | 287,731,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,828 | cpp | #include "main.h"
#include "lobby.h"
#include <set>
void **ppPluginData;
extern void *pAMXFunctions;
vector < lobby * > maplar;
vector < lobby * > yuklenecekler;
typedef void(*logprintf_t)(char* format, ...);
logprintf_t logprintf;
milliseconds uptime;
milliseconds nuptime;
std::chrono::duration<double> tmt;
int tickRate = 0;
std::set<AMX*> amxList;
bf_map* lastmap = nullptr;
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
return sampgdk::Supports() | SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)
{
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
bool load = sampgdk::Load(ppData);
sampgdk::logprintf("Minigames Loaded.");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload()
{
sampgdk::logprintf("Minigames unLoaded.");
sampgdk::Unload();
}
PLUGIN_EXPORT void PLUGIN_CALL ProcessTick()
{
if(yuklenecekler.size() > 0)
{
uptime = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);
if(yuklenecekler.front()->lobbymap->load()) {
maplar.push_back(yuklenecekler.front());
}
nuptime = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);
tmt = (nuptime - uptime);
tickRate += (int)(tmt.count()*1000);
yuklenecekler.erase(yuklenecekler.begin());
}
tickRate += 5;
if(tickRate >= 50)
{
if(maplar.size() > 0)
{
auto pMaps = maplar.begin();
for (; pMaps != maplar.end(); ++pMaps) {
(*pMaps)->ProcessTick();
}
}
tickRate = 0;
}
}
PLUGIN_FUNCTION LoadMap(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if (params[2] >= mLobby->dir->GetDirCount() || params[2] < 0)return 0;
cell mapid = (cell)mLobby->LoadLobbyMap(params[2], params[3]);
return mapid;
}
PLUGIN_FUNCTION LoadRandomMap(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
cell mapid = (cell)mLobby->LoadLobbyMapRandom(params[2]);
return mapid;
}
PLUGIN_FUNCTION UnLoadMap(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(std::find(maplar.begin(), maplar.end(), mLobby) != maplar.end() ||
std::find(yuklenecekler.begin(), yuklenecekler.end(), mLobby) != yuklenecekler.end() )
{
bf_map *cmap = mLobby->lobbymap;
if (cmap != nullptr)
{
if(cmap->m_bLoaded)
{
for (auto yukle = maplar.begin(); yukle != maplar.end(); ++yukle)
{
if (mLobby == (*yukle))
{
maplar.erase(yukle);
break;
}
}
cmap->destroy();
}
else
{
for (auto yukle = yuklenecekler.begin(); yukle != yuklenecekler.end(); ++yukle)
{
if (mLobby == (*yukle))
{
yuklenecekler.erase(yukle);
break;
}
}
}
if(!(mLobby->processrun))delete cmap;
else {
sampgdk::logprintf("Process Tick Calisirken Unload yapilamadi!");
return false;
}
mLobby->currentmapid = INVALID_MAP_ID;
mLobby->lobbymap = nullptr;
return true;
}
}
return false;
}
PLUGIN_FUNCTION CreateLobby(AMX* amx, cell* params)
{
char * file;
lobby * mLobby;
amx_StrParam(amx, params[1], file);
if(!file[0])
{
return (cell)0;
}else
{
mLobby = new lobby(file,params[2]);
if(mLobby->dir->GetDirCount() == 0)sampgdk::logprintf("Map bulunamadı!");
}
return (cell)mLobby;
}
PLUGIN_FUNCTION DestroyLobby(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
delete mLobby;
return true;
}
return false;
}
PLUGIN_FUNCTION AddPlayerLobby(AMX* amx, cell* params)
{
if(!IsPlayerConnected(params[1])) return 0;
lobby * mLobby = (lobby*)params[2];
if(mLobby != NULL)
{
return mLobby->AddPlayerToLobby(params[1]);
}
return false;
}
PLUGIN_FUNCTION DelPlayerLobby(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[2];
if(mLobby != NULL)
{
return mLobby->DelPlayerToLobby(params[1]);
}
return false;
}
PLUGIN_FUNCTION IsPlayerInLobby(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[2];
if(mLobby != NULL)
{
return mLobby->IsPlayerInLobby(params[1]);
}
return false;
}
PLUGIN_FUNCTION AddVehicleLobby(AMX* amx, cell* params)
{
if(!IsValidVehicle(params[1])) return 0;
lobby * mLobby = (lobby*)params[2];
if(mLobby != NULL)
{
return mLobby->AddVehicleToLobby(params[1]);
}
return false;
}
PLUGIN_FUNCTION DelVehicleLobby(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[2];
if(mLobby != NULL)
{
return mLobby->DelVehicleToLobby(params[1]);
}
return false;
}
PLUGIN_FUNCTION IsVehicleInLobby(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[2];
if(mLobby != NULL)
{
return mLobby->IsVehicleInLobby(params[1]);
}
return false;
}
PLUGIN_FUNCTION AddProjectile(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
return mLobby->AddProjectile(params[2],params[3]);
}
return false;
}
PLUGIN_FUNCTION AddTrap(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
return (cell)mLobby->AddTrap(params[2]);
}
return 0;
}
PLUGIN_FUNCTION DestroyTrap(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
Trap * trap = (Trap*)params[2];
if(trap != NULL)
{
return mLobby->DestroyTrap(trap);
}
}
return 0;
}
PLUGIN_FUNCTION DestroyAllTrap(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
mLobby->DestroyAllTrap();
return 1;
}
return 0;
}
PLUGIN_FUNCTION GetMapCount(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
return mLobby->GetMapCount();
}
return 0;
}
PLUGIN_FUNCTION SetLobbyCheckCol(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
mLobby->SetLobbyCheckCol((bool)params[2]);
return 1;
}
return 0;
}
PLUGIN_FUNCTION GetVehicleLastHit(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
return mLobby->GetVehicleLastHit(params[2]);
}
return 0;
}
PLUGIN_FUNCTION ResetVehicleLastHit(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
return mLobby->ResetVehicleLastHit(params[2]);
}
return 0;
}
PLUGIN_FUNCTION GetVehicleLastShooter(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
return mLobby->GetVehicleLastShooter(params[2]);
}
return 0;
}
PLUGIN_FUNCTION ResetVehicleLastShooter(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
return mLobby->ResetVehicleLastShooter(params[2]);
}
return 0;
}
PLUGIN_FUNCTION GetMapInfo(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
if (params[2] >= mLobby->dir->GetDirCount() || params[2] < 0)return 0;
cell* addr = NULL;
amx_GetAddr(amx, params[3], &addr);
amx_SetString(addr, mLobby->dir->dirlist.at(params[2])->GetMapName(), 0, 0, params[4]);
}
return 0;
}
PLUGIN_FUNCTION GetMapLocation(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
if (params[2] >= mLobby->dir->GetDirCount() || params[2] < 0)return 0;
cell* addr = NULL;
amx_GetAddr(amx, params[3], &addr);
amx_SetString(addr, mLobby->dir->dirlist.at(params[2])->GetMapLocation(), 0, 0, params[4]);
}
return 0;
}
PLUGIN_FUNCTION GetMapLastStart(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
if (params[2] >= mLobby->dir->GetDirCount() || params[2] < 0)return 0;
return (cell)mLobby->dir->dirlist.at(params[2])->GetLastStartTime();
}
return 0;
}
PLUGIN_FUNCTION GetCurrentMapID(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
return mLobby->currentmapid;
}
return INVALID_MAP_ID;
}
PLUGIN_FUNCTION DeleteMap(AMX* amx, cell* params)
{
lobby * mLobby = (lobby*)params[1];
if(mLobby != NULL)
{
return mLobby->DeleteMap(params[2]);
}
return 0;
}
//GetMapCheckPoint(cpid, checkpoints[], checkpoint_size);
PLUGIN_FUNCTION GetMapCheckPoint(AMX* amx, cell* params)
{
if (lastmap != nullptr)
{
cell *cptr = NULL;
int size = params[3];
size_t id = params[1];
amx_GetAddr(amx, params[2], &cptr);
if (lastmap->m_flags & FLAG_PICKUP)
{
if (id >= lastmap->m_vPickups.size() || size < 3)return false;
auto spInformation = lastmap->m_vPickups.at(id);
for(int i = 0; i < 3;i++)cptr[i] = amx_ftoc(spInformation[i]);
}
else if (lastmap->m_flags & FLAG_CHECKPS)
{
if (id >= lastmap->m_vRaceCheckps.size() || size < 5)return false;
auto scInformation = lastmap->m_vRaceCheckps.at(id);
for (int i = 0; i < 5; i++)cptr[i] = amx_ftoc(scInformation[i]);
}
return true;
}
return false;
}
//GetMapSpawnPoint(spid, spawnpoint[], spawnpoint_size);
PLUGIN_FUNCTION GetMapSpawnPoint(AMX* amx, cell* params)
{
if (lastmap != nullptr)
{
cell *cptr = NULL;
int size = params[3];
size_t id = params[1];
amx_GetAddr(amx, params[2], &cptr);
if (lastmap->m_flags & FLAG_PED)
{
if (id >= lastmap->m_vSpawnpoints.size() || size < 4)return false;
auto spInformation = lastmap->m_vSpawnpoints.at(id);
for (int i = 0; i < 4; i++)cptr[i] = amx_ftoc(spInformation[i]);
}
else
{
if (id >= lastmap->m_vSpawnpoints.size() || size < 5)return false;
auto spInformation = lastmap->m_vSpawnpoints.at(id);
for (int i = 0; i < 5; i++)cptr[i] = amx_ftoc(spInformation[i]);
}
return true;
}
return false;
}
const AMX_NATIVE_INFO ListNatives[] =
{
{ "LoadMap", LoadMap },
{ "LoadRandomMap", LoadRandomMap},
{ "UnLoadMap", UnLoadMap},
{ "CreateLobby", CreateLobby},
{ "DestroyLobby", DestroyLobby},
{ "AddPlayerLobby", AddPlayerLobby},
{ "DelPlayerLobby", DelPlayerLobby},
{ "IsPlayerInLobby", IsPlayerInLobby},
{ "GetMapCount", GetMapCount},
{ "AddVehicleLobby", AddVehicleLobby},
{ "DelVehicleLobby", DelVehicleLobby},
{ "IsVehicleInLobby", IsVehicleInLobby},
{ "AddProjectile", AddProjectile},
{ "SetLobbyCheckCol", SetLobbyCheckCol},
{ "GetVehicleLastHit", GetVehicleLastHit},
{ "ResetVehicleLastHit", ResetVehicleLastHit},
{ "GetVehicleLastShooter", GetVehicleLastShooter},
{ "ResetVehicleLastShooter", ResetVehicleLastShooter},
{ "AddTrap", AddTrap},
{ "DestroyTrap", DestroyTrap},
{ "DestroyAllTrap", DestroyAllTrap},
{ "GetMapInfo", GetMapInfo},
{ "GetMapLastStart", GetMapLastStart},
{ "GetCurrentMapID", GetCurrentMapID},
{ "DeleteMap", DeleteMap},
{ "GetMapLocation", GetMapLocation},
{ "GetMapCheckPoint", GetMapCheckPoint },
{ "GetMapSpawnPoint", GetMapSpawnPoint },
{ NULL, NULL }
};
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)
{
amxList.insert(amx);
return amx_Register(amx, ListNatives, -1);
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)
{
amxList.erase(amx);
return AMX_ERR_NONE;
}
| [
"aksoysamett@outlook.com"
] | aksoysamett@outlook.com |
09a6e28398f7b2c3db6eb431c9d9a3499eceb3c5 | 7eabf1ee7f6d64767dec4c44ce89f12812fd31a4 | /INTERVALTREE/intervaltree.h | cec9b116a072c06b939aacef34bf9e94e9660abe | [] | no_license | benjlouie/bl_library | ed2717521e2771e5267787d2509560be3e8ce01b | e7cd38ade5babe68f1d7f6702bbb7c4f58f3c1c8 | refs/heads/master | 2021-01-17T02:17:30.904155 | 2017-06-29T01:07:48 | 2017-06-29T01:07:48 | 43,112,542 | 2 | 0 | null | 2015-10-04T21:37:31 | 2015-09-25T06:02:33 | C | UTF-8 | C++ | false | false | 16,905 | h | //insert/delete cases used straight from wikipedia
#ifndef BL_INTERVALTREE_H
#define BL_INTERVALTREE_H
#include <functional>
#include <vector>
//TODO: remove debug dependencies
#include <iostream>
#include <queue>
//TODO: check if some allocator needs to be passed in
//TODO: make iterator for class
template<typename K>
struct Interval {
K low;
K high;
inline void operator= (const Interval<K> &rhs){ this->low = rhs.low; this->high = rhs.high; }
};
template<typename K> inline bool operator==(const Interval<K> &lhs, const Interval<K> &rhs){ return (lhs.low == rhs.low) && (lhs.high == rhs.high); }
template<typename K> inline bool operator!=(const Interval<K> &lhs, const Interval<K> &rhs){ return !operator==(lhs, rhs); }
template<typename K> inline bool operator< (const Interval<K> &lhs, const Interval<K> &rhs){ return lhs.low < rhs.low; }
template<typename K> inline bool operator> (const Interval<K> &lhs, const Interval<K> &rhs){ return operator< (rhs, lhs); }
template<typename K> inline bool operator<=(const Interval<K> &lhs, const Interval<K> &rhs){ return !operator> (lhs, rhs); }
template<typename K> inline bool operator>=(const Interval<K> &lhs, const Interval<K> &rhs){ return !operator< (lhs, rhs); }
template <typename K, typename T>
class IntervalTree
{
public:
IntervalTree(void);
~IntervalTree(void);
size_t size(void);
size_t count(const Interval<K> &key, const T *dataCmp = nullptr);
void clear(void);
bool empty(void);
T& insert(const Interval<K> &key, const T &data);
void remove(const Interval<K> &key, const T *dataCmp = nullptr);
std::vector<std::pair<const Interval<K> &, T&>> *intersect(const Interval<K> &key, std::vector<std::pair<const Interval<K> &, T&>> *list = nullptr);
std::vector<std::pair<const Interval<K> &, T&>> *within(const Interval<K> &key, std::vector<std::pair<const Interval<K> &, T&>> *list = nullptr);
T& operator[](const Interval<K> &key);
//TODO: remove debug method
void print(void);
private:
struct Node {
Interval<K> key;
K max;
T data;
enum Color { RED, BLACK } color;
Node *parent;
Node *left;
Node *right;
};
size_t size_;
Node *root_;
Node leaf_;
size_t count_(Node *root, const Interval<K> &key, const T *dataCmp = nullptr);
Node *peek(Node *root, const Interval<K> &key, const T *dataCmp = nullptr);
Node *grandparent(Node *n);
Node *uncle(Node *n);
Node *sibling(Node *n);
Node *predecessor(Node *n);
Node *successor(Node *n);
void rotate_right(Node *n);
void rotate_left(Node *n);
bool is_leaf(Node *n);
void replace_node(Node *n, Node *replacement);
void updateMax(Node *n);
void insert_case1(Node *n);
void insert_case2(Node *n);
void insert_case3(Node *n);
void insert_case4(Node *n);
void insert_case5(Node *n);
void remove_case0(Node *n);
void remove_case1(Node *n);
void remove_case2(Node *n);
void remove_case3(Node *n);
void remove_case4(Node *n);
void remove_case5(Node *n);
void remove_case6(Node *n);
std::vector<std::pair<const Interval<K> &, T&>> *intersect_(Node *root, const Interval<K> &key, std::vector<std::pair<const Interval<K> &, T&>> &intervals);
std::vector<std::pair<const Interval<K> &, T&>> *within_(Node *root, const Interval<K> &key, std::vector<std::pair<const Interval<K> &, T&>> &intervals);
void foreach_postorder(Node *root, std::function<void(Node *)> func);
};
template <typename K, typename T>
IntervalTree<K, T>::IntervalTree(void)
{
size_ = 0;
root_ = &leaf_;
leaf_.color = Node::BLACK;
leaf_.left = nullptr;
leaf_.right = nullptr;
}
template <typename K, typename T>
IntervalTree<K, T>::~IntervalTree(void)
{
clear();
}
template <typename K, typename T>
size_t IntervalTree<K, T>::size(void)
{
return size_;
}
template <typename K, typename T>
size_t IntervalTree<K, T>::count(const Interval<K> &key, const T *dataCmp)
{
return count_(root_, key, dataCmp);
}
//TODO: this method can be optimized
template <typename K, typename T>
size_t IntervalTree<K, T>::count_(Node *root, const Interval<K> &key, const T *dataCmp)
{
Node *cur = peek(root, key);
if (cur == &leaf_) {
return 0;
}
if (key == cur->key && (dataCmp == nullptr || cur->data == *dataCmp)) {
return (1 + count_(cur->left, key, dataCmp) + count_(cur->right, key, dataCmp));
}
return count_(cur->left, key, dataCmp) + count_(cur->right, key, dataCmp);
}
template <typename K, typename T>
void IntervalTree<K, T>::clear(void)
{
foreach_postorder(root_, [](Node *cur){ delete cur; });
root_ = &leaf_;
size_ = 0;
}
template <typename K, typename T>
bool IntervalTree<K, T>::empty(void)
{
return !size_;
}
/* HELPER section */
template <typename K, typename T>
typename IntervalTree<K, T>::Node *
IntervalTree<K, T>::peek(Node *root, const Interval<K> &key, const T *dataCmp)
{
Node *cur = root;
while (cur != &leaf_) {
if (key < cur->key) {
cur = cur->left;
}
else if (key > cur->key) {
cur = cur->right;
}
else { //key.high may not equal cur->key.high, be aware
Node *ret = cur;
if (dataCmp && cur->data != *dataCmp) {
//dataCmp not equal, check subtrees (left first)
ret = peek(cur->left, key, dataCmp);
if (ret == &leaf_) {
ret = peek(cur->right, key, dataCmp);
}
}
return ret;
}
}
return &leaf_;
}
template <typename K, typename T>
typename IntervalTree<K, T>::Node *
IntervalTree<K, T>::grandparent(Node *n)
{
if (n && n->parent) {
return n->parent->parent;
}
else {
return nullptr;
}
}
template <typename K, typename T>
typename IntervalTree<K, T>::Node *
IntervalTree<K, T>::uncle(Node *n)
{
Node *g = grandparent(n);
if (g == nullptr)
return nullptr; // No grandparent means no uncle
if (n->parent == g->left)
return g->right;
else
return g->left;
}
template <typename K, typename T>
typename IntervalTree<K, T>::Node *
IntervalTree<K, T>::sibling(Node *n)
{
if (!n || !n->parent) {
return nullptr;
}
if (n == n->parent->left) {
return n->parent->right;
}
else {
return n->parent->left;
}
}
template <typename K, typename T>
typename IntervalTree<K, T>::Node *
IntervalTree<K, T>::predecessor(Node *n)
{
if (n->left == &leaf_) {
return nullptr;
}
Node *cur = n->left;
while (cur->right != &leaf_) {
cur = cur->right;
}
return cur;
}
template <typename K, typename T>
typename IntervalTree<K, T>::Node *
IntervalTree<K, T>::successor(Node *n)
{
if (n->right == &leaf_) {
return nullptr;
}
Node *cur = n->right;
while (cur->left != &leaf_) {
cur = cur->left;
}
return cur;
}
template <typename K, typename T>
void IntervalTree<K, T>::rotate_right(Node *n)
{
Node *left = n->left;
Node *parent = nullptr;
Node **parentLink;
//get parentLink
if (n->parent) {
parent = n->parent;
if (n->parent->left == n) {
parentLink = &n->parent->left;
}
else {
parentLink = &n->parent->right;
}
}
else {
parentLink = &root_;
}
//rotate right
*parentLink = left;
n->left = left->right;
n->parent = left;
left->parent = parent;
if (left->right != &leaf_) {
left->right->parent = n;
}
left->right = n;
updateMax(n);
updateMax(left);
}
template <typename K, typename T>
void IntervalTree<K, T>::rotate_left(Node *n)
{
Node *right = n->right;
Node *parent = nullptr;
Node **parentLink;
//get parentLink
if (n->parent) {
parent = n->parent;
if (n->parent->left == n) {
parentLink = &n->parent->left;
}
else {
parentLink = &n->parent->right;
}
}
else {
parentLink = &root_;
}
//rotate left
*parentLink = right;
n->right = right->left;
n->parent = right;
right->parent = parent;
if (right->left != &leaf_) {
right->left->parent = n;
}
right->left = n;
updateMax(n);
updateMax(right);
}
template <typename K, typename T>
bool IntervalTree<K, T>::is_leaf(Node *n)
{
return n == &leaf_;
}
template <typename K, typename T>
void IntervalTree<K, T>::replace_node(Node *n, Node *replacement)
{
if (!n->parent) {
root_ = replacement;
replacement->parent = nullptr;
return;
}
replacement->parent = n->parent;
if (n->parent->left == n) {
n->parent->left = replacement;
}
else {
n->parent->right = replacement;
}
}
//TODO: this may be traversing more than necessary, think about it more
template <typename K, typename T>
void IntervalTree<K, T>::updateMax(Node *n)
{
if (n == &leaf_) {
return;
}
n->max = n->key.high;
bool changed = false;
if (n->left != &leaf_ && n->left->max > n->max) {
n->max = n->left->max;
changed = true;
}
if (n->right != &leaf_ && n->right->max > n->max) {
n->max = n->right->max;
changed = true;
}
if (n->parent && (changed || (n->max > n->parent->max))) {
updateMax(n->parent);
}
}
/* INSERT section */
template <typename K, typename T>
T& IntervalTree<K, T>::insert(const Interval<K> &key, const T &data)
{
Node *n = new Node{ key, key.high, data, Node::RED, nullptr, &leaf_, &leaf_ };
Node *prev = nullptr;
Node *cur = root_;
Node **prevLink = &root_;
//BST insert at leaf
while (cur != &leaf_) {
prev = cur;
if (key >= cur->key) {
prevLink = &cur->right;
cur = cur->right;
}
else {
prevLink = &cur->left;
cur = cur->left;
}
}
//insert node
n->parent = prev;
*prevLink = n;
insert_case1(n);
updateMax(n);
size_++;
return n->data;
}
template <typename K, typename T>
void IntervalTree<K, T>::insert_case1(Node *n)
{
if (n->parent == nullptr) {
n->color = Node::BLACK;
}
else {
insert_case2(n);
}
}
template <typename K, typename T>
void IntervalTree<K, T>::insert_case2(Node *n)
{
if (n->parent->color == Node::BLACK) {
return; /* Tree is still valid */
}
else {
insert_case3(n);
}
}
template <typename K, typename T>
void IntervalTree<K, T>::insert_case3(Node *n)
{
Node *g;
Node *u = uncle(n);
if ((u != nullptr) && (u->color == Node::RED)) {
n->parent->color = Node::BLACK;
u->color = Node::BLACK;
g = grandparent(n);
g->color = Node::RED;
insert_case1(g);
}
else {
insert_case4(n);
}
}
template <typename K, typename T>
void IntervalTree<K, T>::insert_case4(Node *n)
{
Node *g = grandparent(n);
if ((n == n->parent->right) && (n->parent == g->left)) {
rotate_left(n->parent);
n = n->left;
}
else if ((n == n->parent->left) && (n->parent == g->right)) {
rotate_right(n->parent);
n = n->right;
}
insert_case5(n);
}
template <typename K, typename T>
void IntervalTree<K, T>::insert_case5(Node *n)
{
Node *g = grandparent(n);
n->parent->color = Node::BLACK;
g->color = Node::RED;
if (n == n->parent->left)
rotate_right(g);
else
rotate_left(g);
}
/* REMOVE section */
template <typename K, typename T>
void IntervalTree<K, T>::remove(const Interval<K> &key, const T *dataCmp)
{
Node *cur = peek(root_, key, dataCmp);
if (cur != &leaf_) {
//BST delete, then correct
Node *removeNode = cur;
if (cur->left != &leaf_) {
removeNode = predecessor(cur);
}
else if (cur->right != &leaf_) {
removeNode = successor(cur);
}
//swap replacement(removeNode) with cur
if (removeNode != cur) {
cur->key = removeNode->key;
cur->data = removeNode->data;
}
remove_case0(removeNode);
updateMax(cur);
size_--;
}
}
template <typename K, typename T>
void IntervalTree<K, T>::remove_case0(Node *n)
{
// Precondition: n has at most one non-leaf child.
Node *child = is_leaf(n->right) ? n->left : n->right;
replace_node(n, child);
if (n->color == Node::BLACK) {
if (child->color == Node::RED) {
child->color = Node::BLACK;
}
else {
remove_case1(child);
}
}
delete n;
}
template <typename K, typename T>
void IntervalTree<K, T>::remove_case1(Node *n)
{
if (n->parent) {
remove_case2(n);
}
}
template <typename K, typename T>
void IntervalTree<K, T>::remove_case2(Node *n)
{
Node *s = sibling(n);
if (s->color == Node::RED) {
n->parent->color = Node::RED;
s->color = Node::BLACK;
if (n == n->parent->left) {
rotate_left(n->parent);
}
else {
rotate_right(n->parent);
}
}
remove_case3(n);
}
template <typename K, typename T>
void IntervalTree<K, T>::remove_case3(Node *n)
{
Node *s = sibling(n);
if ((n->parent->color == Node::BLACK)
&& (s->color == Node::BLACK)
&& (s->left->color == Node::BLACK)
&& (s->right->color == Node::BLACK)) {
s->color = Node::RED;
remove_case1(n->parent);
}
else {
remove_case4(n);
}
}
template <typename K, typename T>
void IntervalTree<K, T>::remove_case4(Node *n)
{
Node *s = sibling(n);
if ((n->parent->color == Node::RED)
&& (s->color == Node::BLACK)
&& (s->left->color == Node::BLACK)
&& (s->right->color == Node::BLACK)) {
s->color = Node::RED;
n->parent->color = Node::BLACK;
}
else {
remove_case5(n);
}
}
template <typename K, typename T>
void IntervalTree<K, T>::remove_case5(Node *n)
{
Node *s = sibling(n);
if (s->color == Node::BLACK) {
if ((n == n->parent->left)
&& (s->right->color == Node::BLACK)
&& (s->left->color == Node::RED)) {
s->color = Node::RED;
s->left->color = Node::BLACK;
rotate_right(s);
}
else if ((n == n->parent->right)
&& (s->left->color == Node::BLACK)
&& (s->right->color == Node::RED)) {
s->color = Node::RED;
s->right->color = Node::BLACK;
rotate_left(s);
}
}
remove_case6(n);
}
template <typename K, typename T>
void IntervalTree<K, T>::remove_case6(Node *n)
{
Node *s = sibling(n);
s->color = n->parent->color;
n->parent->color = Node::BLACK;
if (n == n->parent->left) {
s->right->color = Node::BLACK;
rotate_left(n->parent);
}
else {
s->left->color = Node::BLACK;
rotate_right(n->parent);
}
}
/* ACCESS section */
//TODO: check intersect/within and make sure the booleans work (x:x) intersects (x:x) and is within (x:x)
//TODO: elements of vector can still be changed (like with iterator), maybe copy instead of ref? (could be memory heavy)
template <typename K, typename T>
std::vector<std::pair<const Interval<K> &, T&>> *
IntervalTree<K, T>::intersect(const Interval<K> &key, std::vector<std::pair<const Interval<K> &, T&>> *intervals)
{
std::vector<std::pair<const Interval<K> &, T&>> *list = intervals;
if (list == nullptr) {
list = new std::vector<std::pair<const Interval<K> &, T&>>;
}
list = intersect_(root_, key, *list);
return list;
}
template <typename K, typename T>
std::vector<std::pair<const Interval<K> &, T&>> *
IntervalTree<K, T>::intersect_(Node *root, const Interval<K> &key, std::vector<std::pair<const Interval<K> &, T&>> &intervals)
{
if (root == &leaf_) {
return &intervals;
}
if (key.low <= root->max) {
intersect_(root->left, key, intervals);
}
if (key.low <= root->key.high && key.high >= root->key.low) {
intervals.push_back(std::pair<const Interval<K> &, T&>(root->key, root->data));
}
if (key.high >= root->key.low) {
intersect_(root->right, key, intervals);
}
return &intervals;
}
template <typename K, typename T>
std::vector<std::pair<const Interval<K> &, T&>> *
IntervalTree<K, T>::within(const Interval<K> &key, std::vector<std::pair<const Interval<K> &, T&>> *intervals)
{
std::vector<std::pair<const Interval<K> &, T&>> *list = intervals;
if (list == nullptr) {
list = new std::vector<std::pair<const Interval<K> &, T&>>;
}
list = within_(root_, key, *list);
return list;
}
template <typename K, typename T>
std::vector<std::pair<const Interval<K> &, T&>> *
IntervalTree<K, T>::within_(Node *root, const Interval<K> &key, std::vector<std::pair<const Interval<K> &, T&>> &intervals)
{
if (root == &leaf_) {
return &intervals;
}
if (key.low <= root->max && key.low <= root->key.low) { //TODO: check 2nd test
within_(root->left, key, intervals);
}
if (key.low <= root->key.low && key.high >= root->key.high) {
intervals.push_back(std::pair<const Interval<K> &, T&>(root->key, root->data));
}
if (key.high >= root->key.low) { //TODO: need extra test here? think more about intervals within others
within_(root->right, key, intervals);
}
return &intervals;
}
template <typename K, typename T>
T& IntervalTree<K, T>::operator[](const Interval<K> &key)
{
Node *node = peek(root_, key);
if (node != &leaf_) {
//key exists
return node->data;
}
T data; //TODO: does this work on types with complex allocation?
return insert(key, data);
}
template <typename K, typename T>
void IntervalTree<K, T>::foreach_postorder(Node *root, std::function<void(Node *)> func)
{
if (root == &leaf_) {
return;
}
foreach_postorder(root->left, func);
foreach_postorder(root->right, func);
func(root);
}
//TODO: remove debug method
template <typename K, typename T>
void IntervalTree<K, T>::print(void)
{
std::queue<Node *> q;
q.push(root_);
while (q.size() > 0) {
int size = q.size();
for (int i = 0; i < size; i++) {
Node *cur = q.front();
q.pop();
if (cur != &leaf_) {
std::cout << "(" << cur->key.low << ":" << cur->key.high << ")" << cur->max << "|" << cur->data << ", ";
q.push(cur->left);
q.push(cur->right);
}
else {
std::cout << "NULL, ";
}
}
std::cout << std::endl;
}
}
#endif // !BL_IntervalTree_H
| [
"benjlouie@gmail.com"
] | benjlouie@gmail.com |
86e1a52548ea87ab1e6008bfd122572696824392 | a3a2bccb492c513b75344cded0110e75bc17103d | /python/3.pyp/2.jisuanke_cainiao/data/787/简单算法入门/实现折半查找.cpp | 275ff6864a9336721713033ade499d8fb6e33cdc | [] | no_license | ldc0111/learn | abc40e0041b48a821935860be800a616d7dd0404 | e06d68437d5d1525cc6cee95fd99a9f2b90b17df | refs/heads/master | 2020-03-26T01:57:31.444390 | 2019-11-21T03:19:32 | 2019-11-21T03:19:32 | 144,390,234 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,253 | cpp | #include <cstdio>
#include <iostream>
using namespace std;
int main() {
int n;
int k;
int numbers[1000001];
int m;
int i,j;
int flag = 0;
// 反复读入数字和查找数字的数量
while (scanf("%d %d", &n, &k) != EOF) {
// 读入给定的数字
for (i = 0; i < n; i++) {
scanf("%d", &numbers[i]);
}
for (j = 0; j < k; j++) {
// 读入待查找的数字,
scanf("%d", &m);
flag = 0;
// 请在下面完成查找读入数字的功能
int head = 0,tail = n - 1;
while (head < tail){
int mid = (head + tail) >> 1;
//cout << numbers[mid] << m << endl;
if(numbers[mid] == m) {
cout << mid + 1;
flag = 1;
if(j != k - 1) cout << " ";
else cout << endl;
break;
} else if (numbers[mid] < m) head = mid + 1;
else tail = mid;
}
if (flag == 0) {
cout << "0";
if(j != k - 1) cout << " ";
else cout << endl;
}
}
}
return 0;
} | [
"15736818863@163.com"
] | 15736818863@163.com |
077602fc32230c1cef1c937d28a276a6aaa00016 | a627fc9abcfcf159b7de03e570a63d96b9324c38 | /11_flood_fill.cpp | 10951374ac241dc0f81e963ec6e5e54f6f5b53a8 | [] | no_license | jishnupramod/Leetcode-May-Challenge-2020 | 888fd08944cb53b3985cb8632826dc7f366f8367 | ca3a18e130c3e882f236d01b840a61ffebb0d33d | refs/heads/master | 2022-09-18T00:59:01.377052 | 2020-05-31T07:50:33 | 2020-05-31T07:50:33 | 260,855,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,185 | cpp | /*
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor,
"flood fill" the image.
To perform a "flood fill", consider the starting pixel,
plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel,
plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on.
Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
Note:
The length of image and image[0] will be in the range [1, 50].
The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
The value of each color in image[i][j] and newColor will be an integer in [0, 65535].
*/
class Solution {
private:
void dfs(vector<vector<int>>& img, int i, int j, int row, int col, int newColor, int origColor) {
if (i<0 or j<0 or i+1>row or j+1>col or img[i][j] != origColor)
return;
img[i][j] = newColor;
dfs(img, i+1, j, row, col, newColor, origColor);
dfs(img, i-1, j, row, col, newColor, origColor);
dfs(img, i, j+1, row, col, newColor, origColor);
dfs(img, i, j-1, row, col, newColor, origColor);
}
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int row = image.size();
int col = row > 0 ? image[0].size() : 0;
int origColor = image[sr][sc];
if (origColor == newColor)
return image;
dfs(image, sr, sc, row, col, newColor, origColor);
return image;
}
};
| [
"jishnumagnanimous@gmail.com"
] | jishnumagnanimous@gmail.com |
c31de8d466ebee2e4182ad8369d5f4a3896d0d80 | 14c2c9c0a6f8bf706c30e282c0a79e11ccc40e55 | /que II.cpp | d3d8a714eed28d6895ad30438bb4cdb115012857 | [] | no_license | Nalinswarup123/ds | 92654f7f0dc1fa5d54111b3d0fae213a0edd9f60 | 518add8e1f2a51c3442157d5aee4883682fb9e2a | refs/heads/master | 2022-03-11T08:46:36.701536 | 2019-02-12T11:53:38 | 2019-02-12T11:53:38 | 170,308,518 | 0 | 1 | null | 2022-03-02T19:23:13 | 2019-02-12T11:43:58 | C++ | UTF-8 | C++ | false | false | 1,443 | cpp | #include<iostream>
using namespace std;
struct queue
{
int front,rear,capacity;
int *array;
};
queue *q;
void create(int k)
{
q=new queue;
q->capacity=k;
q->array=new int[k];
q->front=q->rear=-1;
}
void enque()
{
int k;
if(((q->rear+1)%q->capacity)==q->front)
cout<<"queue is full";
else
{
cout<<"\nenter element in queue";
cin>>k;
q->rear=(q->rear+1)%q->capacity;
q->array[q->rear]=k;
if(q->front==-1)
q->front=q->rear;
}
}
void deque()
{
int data;
if(q->front==-1)
cout<<"queue is empty";
else
{
if(q->front==q->rear)
{
data=q->array[q->front];
q->array[q->front]=q->array[q->rear]=NULL;
q->front=q->rear=-1;
cout<<"\ndeleted item="<<data;
}
else
{
data=q->array[q->front];
q->array[q->front]=NULL;
q->front=(q->front+1)%q->capacity;
cout<<"\ndeleted item="<<data;
}
}
}
void display()
{
cout<<endl;
for(int i=0;i<q->capacity;i++)
cout<<q->array[i]<<ends;
}
main()
{
int n,v,a;
cout<<"enter size of queue";
cin>>n;
create(n);
for(int i=0;i<n;i++)
{
enque();
}
cout<<"\n1)enque\n2)deque\n3)display\n4)exit\n";
while(1)
{
cout<<"\nenter your choice";
cin>>a;
switch(a)
{
case 1:
enque();
break;
case 2:
deque();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
cout<<"\nenter valid choice";
}
}
}
| [
"noreply@github.com"
] | Nalinswarup123.noreply@github.com |
0f7a85f971b322d064a4e477bc3165059ad7ef3e | 9a7ed884412c559f7343329f8f08eb4ffa9cbdb0 | /Source/ChaliceAbilities/Private/ChaliceAbilities/System/ChaliceAbilitiesBlueprintLibrary.cpp | 295d45835ecdc5e951abc47813815a7946d85235 | [
"MIT"
] | permissive | spencer-melnick/Chalice | 696218357f76849fbeb1d6ea58e26a1129320e86 | fdb414d0620249af54b3b666222a8731e84d097e | refs/heads/main | 2021-06-22T21:42:56.718028 | 2021-01-23T04:19:11 | 2021-01-23T04:19:11 | 314,052,311 | 5 | 0 | MIT | 2021-01-23T04:19:12 | 2020-11-18T20:38:58 | C++ | UTF-8 | C++ | false | false | 1,143 | cpp | // Copyright (c) 2020 Spencer Melnick
#include "ChaliceAbilities/System/ChaliceAbilitiesBlueprintLibrary.h"
#include "ChaliceAbilities/System/ChaliceAbilityInterface.h"
#include "ChaliceAbilities/System/ChaliceAbilityComponent.h"
#include "ChaliceCore/Components/InteractionComponent.h"
// UChaliceAbilitiesBlueprintLibrary
UChaliceAbilityComponent* UChaliceAbilitiesBlueprintLibrary::GetAbilityComponent(const AActor* Actor)
{
const IChaliceAbilityInterface* AbilityInterface = Cast<IChaliceAbilityInterface>(Actor);
if (!AbilityInterface)
{
return nullptr;
}
return AbilityInterface->GetChaliceAbilityComponent();
}
FGameplayTagContainer UChaliceAbilitiesBlueprintLibrary::GetActorOwnedTags(const AActor* Actor)
{
FGameplayTagContainer Tags;
const UChaliceAbilityComponent* AbilityComponent = GetAbilityComponent(Actor);
if (AbilityComponent)
{
AbilityComponent->GetOwnedGameplayTags(Tags);
}
return Tags;
}
UInteractionComponent* UChaliceAbilitiesBlueprintLibrary::GetInteractionComponent(const AActor* Actor)
{
if (!Actor)
{
return nullptr;
}
return Actor->FindComponentByClass<UInteractionComponent>();
}
| [
"smelnick97@gmail.com"
] | smelnick97@gmail.com |
0b34fd63d46101c52c160ffd834e098e418a4ca5 | cdea526b9be1cdfd42e69fe1d49433bdf39c8906 | /src/ImplicitShape/Torus.cpp | 4389b9ce86dad8222a38db69a697aa0cc9bdd420 | [] | no_license | johannmeyer/ray-tracer | 0c628ec4293a90d4b1064706b0daf1dcebcb380d | 387deaeda95e1aaf2bfc9cf8797f775fed8b82cb | refs/heads/master | 2023-05-03T20:02:25.016984 | 2021-05-22T18:42:18 | 2021-05-22T18:42:18 | 361,144,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 483 | cpp | #include "ImplicitShape.h"
double Torus::get_distance(const Point3& p) const
{
Point3 q = p;
double x = sqrt(q.x()*q.x() + q.z()*q.z()) - radius_major;
double y = q.y();
return sqrt(x*x + y*y) - radius_minor;
}
void Torus::bounding_box(AABB& output_box) const
{
double max_radius_xz = radius_major + radius_minor;
double max_radius_y = radius_minor;
Vec3 delta = Vec3(max_radius_xz, max_radius_y, max_radius_xz);
output_box = AABB(-delta, delta);
} | [
"johann.meyer@gmail.com"
] | johann.meyer@gmail.com |
1876064c6ce5245ca5015c49c05e4376782abd95 | f2f74b28e4e49996d4df3a28d442e30983f3257d | /computadora.cpp | b40c865437cc258b0e6aac2085397fff5a7e05fc | [] | no_license | davidfranc/EDO_Actividad13 | 51de1747930ffc9e97b6da12b05251e0ee745c2e | 1905d7dc76bc92abf944c5c307769fe7e46e0b17 | refs/heads/main | 2023-01-06T11:09:29.354931 | 2020-11-02T05:58:45 | 2020-11-02T05:58:45 | 309,272,879 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | cpp | #include "computadora.h"
Computadora::Computadora()
{
}
Computadora::Computadora(const string &sistemaOperativo, const string &procesador, int memoriaRam, int almacenamiento)
{
this->sistemaOperativo = sistemaOperativo;
this->procesador = procesador;
this->memoriaRam = memoriaRam;
this->almacenamiento = almacenamiento;
}
void Computadora::setSistemaOperativo(const string &v)
{
sistemaOperativo = v;
}
string Computadora::getSistemaOperativo()
{
return sistemaOperativo;
}
void Computadora::setProcesador(const string &v)
{
procesador = v;
}
string Computadora::getProcesador()
{
return procesador;
}
void Computadora::setMemoriaRam(int v)
{
memoriaRam = v;
}
int Computadora::getMemoriaRam()
{
return memoriaRam;
}
void Computadora::setAlmacenamiento(int v)
{
almacenamiento = v;
}
int Computadora::getAlmacenamiento()
{
return almacenamiento;
}
| [
"david.andrade7477@alumnos.udg.mx"
] | david.andrade7477@alumnos.udg.mx |
4adc7cc8ec31850973654ef844db67e4e1a09dd1 | 4d77398fc24009f483f2b2abc028a135e09fc9eb | /Assignment4/Solid_plate/4.6/gradTz | 87c95012df331fd955deda67300fa4644c7502b6 | [] | permissive | Naveen-Surya/CFD-Lab-1 | 12c635b72c611d83080ed6dd316b1b0016f2f86f | c38b0bfe43c7135f4a10e744ea1ac6cf6e9d4a1a | refs/heads/master | 2020-04-05T16:43:39.651232 | 2018-08-23T12:10:06 | 2018-08-23T12:10:06 | 157,026,052 | 0 | 1 | MIT | 2018-11-10T22:11:51 | 2018-11-10T22:11:51 | null | UTF-8 | C++ | false | false | 1,376 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 5.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "4.6";
object gradTz;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 -1 0 1 0 0 0];
internalField uniform 0;
boundaryField
{
left
{
type calculated;
value uniform 0;
}
right
{
type calculated;
value uniform 0;
}
interface
{
type calculated;
value uniform 0;
}
bottom
{
type calculated;
value uniform 0;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"sarthakgarg1993@gmail.com"
] | sarthakgarg1993@gmail.com | |
b00e8fe2372a1490138b15332b3c00a32a455abf | aa0168a62f7629c08f4d30d8719fe4239e978cfb | /libVcf/test/testReadBCFByRange.cpp | ff1101bcca0c8b7d4792b7ec7ea47b84e3215fe3 | [] | no_license | Shicheng-Guo/rvtests | e41416785f42e4ff7da87f633ffff86dd64eaf60 | be1bd88b2bd663804bb8c2aff8a4d990a29850d2 | refs/heads/master | 2020-04-07T10:51:02.496565 | 2018-10-05T05:59:27 | 2018-10-05T05:59:27 | 158,302,712 | 1 | 0 | null | 2018-11-19T23:20:09 | 2018-11-19T23:20:08 | null | UTF-8 | C++ | false | false | 963 | cpp | #include "VCFUtil.h"
int main() {
VCFInputFile vin("test.bcf.gz");
vin.setRangeList("1:196341364-196341449");
while (vin.readRecord()){
VCFRecord& r = vin.getVCFRecord();
VCFPeople& people = r.getPeople();
VCFIndividual* indv;
printf("%s:%d\t", r.getChrom(), r.getPos());
bool tagMissing;
VCFInfo& info = r.getVCFInfo();
std::string anno = info.getTag("ANNO", &tagMissing).toStr();
printf("ANNO=%s\t", anno.c_str());
// assert(tagMissing); // all variant has tagMissing == true
bool missingGenotype; // missing indicator
int GTidx = r.getFormatIndex("GT");
for (int i = 0; i < people.size(); i++){
indv = people[i];
const VCFValue& gt = indv->justGet(GTidx);
missingGenotype = gt.isMissingGenotype();
if (!missingGenotype) {
printf("%d", gt.getGenotype());
} else {
printf("M");
}
printf("\t");
}
printf("\n");
}
return 0;
}
| [
"zhanxw@gmail.com"
] | zhanxw@gmail.com |
3a6aac0bc1c3d3400370e52ba0c910d3a51d11dc | c9b02ab1612c8b436c1de94069b139137657899b | /server/app/data/DataTimeLimitProp.cpp | 8ac6fb9d7df041dee55ff503aceb4b228daaf2f3 | [] | no_license | colinblack/game_server | a7ee95ec4e1def0220ab71f5f4501c9a26ab61ab | a7724f93e0be5c43e323972da30e738e5fbef54f | refs/heads/master | 2020-03-21T19:25:02.879552 | 2020-03-01T08:57:07 | 2020-03-01T08:57:07 | 138,948,382 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,650 | cpp | /*
* DataTimeLimitProp.cpp
*
* Created on: 2016-11-29
* Author: dawx62fac
*/
#include "DataTimeLimitProp.h"
DBCTimeLimitProp::DBCTimeLimitProp(unsigned uid_, unsigned id_)
: uid(uid_), id(id_), op_time(0)
{
}
DBCTimeLimitProp::DBCTimeLimitProp()
: uid(0), id(0), op_time(0)
{
}
/////////////////////////////////////////////////////////////
int DBCTimeLimitPropHandler::Get(DBCTimeLimitProp &data)
{
warn_log("unrealized_interface");
return -1;
}
int DBCTimeLimitPropHandler::Get(vector<DBCTimeLimitProp> &data)
{
if (data.empty())
{
return R_ERROR;
}
unsigned uid = data.begin()->uid;
data.clear();
DBCREQ_DECLARE(DBC::GetRequest, uid);
DBCREQ_SET_KEY(uid);
DBCREQ_NEED_BEGIN();
DBCREQ_NEED(uid);
DBCREQ_NEED(id);
DBCREQ_NEED(op_time);
DBCREQ_EXEC;
DBCREQ_ARRAY_GET_BEGIN(data);
DBCREQ_ARRAY_GET_INT(data, uid);
DBCREQ_ARRAY_GET_INT(data, id);
DBCREQ_ARRAY_GET_INT(data, op_time);
DBCREQ_ARRAY_GET_END();
return 0;
}
int DBCTimeLimitPropHandler::Add(DBCTimeLimitProp &data)
{
DBCREQ_DECLARE(DBC::InsertRequest, data.uid);
DBCREQ_SET_KEY(data.uid);
DBCREQ_SET_INT(data, id);
DBCREQ_SET_INT(data, op_time);
DBCREQ_EXEC;
return 0;
}
int DBCTimeLimitPropHandler::Set(DBCTimeLimitProp &data)
{
DBCREQ_DECLARE(DBC::UpdateRequest, data.uid);
DBCREQ_SET_KEY(data.uid);
DBCREQ_SET_CONDITION(EQ, id, data.id);
DBCREQ_SET_INT(data, id);
DBCREQ_SET_INT(data, op_time);
DBCREQ_EXEC;
return 0;
}
int DBCTimeLimitPropHandler::Del(DBCTimeLimitProp &data)
{
DBCREQ_DECLARE(DBC::DeleteRequest, data.uid);
DBCREQ_SET_KEY(data.uid);
DBCREQ_SET_CONDITION(EQ, id, data.id);
DBCREQ_EXEC;
return 0;
}
| [
"178370407@qq.com"
] | 178370407@qq.com |
8ac116a343ac0d9eff0bda6224c2ddd18fb97946 | 5013750dde6990bf5d384cfd806b0d411f04d675 | /leetcode/c++/941. Valid Mountain Array.cpp | c038656a4c6344bd5d0c2c63353edb62fe24a6f9 | [] | no_license | 543877815/algorithm | 2c403319f83630772ac94e67b35a27e71227d2db | 612b2e43fc6e1a2a746401288e1b89689e908926 | refs/heads/master | 2022-10-11T10:31:17.049279 | 2022-09-25T15:11:46 | 2022-09-25T15:11:46 | 188,680,726 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | // 线性扫描
// 时间复杂度:O(n)
// 空间复杂度:O(1)
class Solution {
public:
bool validMountainArray(vector<int> &A) {
if (A.size() <= 2) return false;
int up = -1;
for (int i = 0; i < A.size() - 1; i++) {
if (A[i] == A[i + 1]) return false;
if (up == -1) {
if (A[i] > A[i + 1]) up = i;
} else {
if (A[i] < A[i + 1]) return false;
}
}
return up > 0;
}
}; | [
"543877815@qq.com"
] | 543877815@qq.com |
4822cb55aa40d36fcd574063298cacd444977ed3 | 74e1da7487a93229fdc6fc4e4f61f4f8379f4d9d | /SoilSensing-Final-April2021.ino | d91ded5a04ed2eba9a6ef84ddd2b17e306bd29b0 | [] | no_license | saradaugbjerg/soilsensing | 0e8daed55d2549ed4e5ef920306da452e8d07497 | 9018a4987f98f438e297981564c5f598bbfb42dc | refs/heads/main | 2023-04-15T23:06:38.283016 | 2021-04-07T12:14:28 | 2021-04-07T12:14:28 | 355,532,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,480 | ino |
//temp sensor wiring: https://lastminuteengineers.com/ds18b20-arduino-tutorial/
//upload to TTGO 1 Board
//pint out esp32 ttgo https://raw.githubusercontent.com/LilyGO/ESP32-TTGO-T1/master/image/image4.jpg
//download file from sd : https://github.com/G6EJD/ESP32-8266-File-Download/blob/master/ESP_File_Download_v01.ino
//TODO: SOIL SENSING name netowrk, guide, time
#include <TinyGPS++.h>
#include "HardwareSerial.h";
// The TinyGPS++ object
TinyGPSPlus gps;
HardwareSerial SerialGPS(1);
#include <WiFi.h>
#include <WebServer.h>
/* Define data pins for the sensors */
#define TEMP_PIN 18
#define TEMP_PIN2 19
#define MOIST_PIN 33
#define GPS_RX 17
#define GPS_TX 16
/* Put your SSID & Password */
const char* ssid = "SoilSensing1"; // Enter SSID here
const char* password = "123456789"; //Enter Password here
int interval = 5000; //Reading interval
/* Put IP Address details */
IPAddress local_ip(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
WebServer server(80);
#include "FS.h"
#include "SD.h"
#include "SPI.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h> // Only needed for Arduino 1.6.5 and earlier
#define ONE_WIRE_BUS TEMP_PIN
#define ONE_WIRE_BUS2 TEMP_PIN2
OneWire oneWire(TEMP_PIN);
OneWire oneWire2(TEMP_PIN2);
DallasTemperature sensors(&oneWire);
DallasTemperature sensors2(&oneWire2);
int temp_value;
int temp_value2;
int moist_value;
String gps_date;
String gps_time;
unsigned long timer = 0;
String fileSize;
String lastDataSD;
#define LAST_DATA_ARRAY_SIZE 10 //size of array for last readings
String lastDataArray [LAST_DATA_ARRAY_SIZE];
void setup() {
Serial.begin(9600);
WiFi.softAP(ssid, password);
WiFi.softAPConfig(local_ip, gateway, subnet);
delay(100);
server.on("/", onConnect);
//server.on("/refresh", refresh);
server.on("/download", SD_file_download);
server.onNotFound(handle_NotFound);
server.begin();
Serial.println("HTTP server started");
SerialGPS.begin(9600, SERIAL_8N1, GPS_TX, GPS_RX); //GPS TX, RX
pinMode(MOIST_PIN, INPUT);
sensors.begin();
sensors2.begin();
if (!SD.begin()) {
Serial.println("Card Mount Failed");
return;
}
uint8_t cardType = SD.cardType();
if (cardType == CARD_NONE) {
Serial.println("No SD card attached");
return;
}
Serial.print("SD Card Type: ");
if (cardType == CARD_MMC) {
Serial.println("MMC");
} else if (cardType == CARD_SD) {
Serial.println("SDSC");
} else if (cardType == CARD_SDHC) {
Serial.println("SDHC");
} else {
Serial.println("UNKNOWN");
}
uint64_t cardSize = SD.cardSize() / (1024 * 1024);
Serial.printf("SD Card Size: %lluMB\n", cardSize);
//fs::FS &check = SD;
//const char * pathcheck = "/soil_sensing.txt";
File filecheck = SD.open("/soil_sensing.txt");
Serial.println("filecheck: ");
Serial.println(filecheck);
if (!filecheck) {
filecheck.close();
writeFile(SD, "/soil_sensing.txt", "Temperature1, Temperature2, Moisture, Time, Date\n"); //first row
} else {
Serial.println("file already exists");
filecheck.close();
}
}
void loop() {
server.handleClient();
while (SerialGPS.available() > 0) {
gps.encode(SerialGPS.read());
}
//Date
if (gps.date.isValid())
{
gps_date = gps.date.value() ;
}
else
{
//Serial.print(F("INVALID"));
}
//Time
if (gps.time.isValid())
{
gps_time = gps.time.value();
}
else
{
//Serial.print(F("INVALID"));
}
moist_value = analogRead(MOIST_PIN);
sensors.requestTemperatures();
sensors2.requestTemperatures();
//Float to String to char for temp
String str_temp = String(sensors.getTempCByIndex(0));
int str_len_temp = str_temp.length() + 1;
char char_array_temp[str_len_temp];
str_temp.toCharArray(char_array_temp, str_len_temp);
//Float to String to char for temp2
String str_temp2 = String(sensors2.getTempCByIndex(0));
int str_len_temp2 = str_temp2.length() + 1;
char char_array_temp2[str_len_temp2];
str_temp2.toCharArray(char_array_temp2, str_len_temp2);
//Float to String to char for moisture
String str_moist = String(moist_value);
int str_len_moist = str_moist.length() + 1;
char char_array_moist[str_len_moist];
str_moist.toCharArray(char_array_moist, str_len_moist);
//String to char for time
String str_time = gps_time;
int str_len_time = str_time.length() + 1;
char char_array_time[str_len_time];
str_time.toCharArray(char_array_time, str_len_time);
//String to char for moisture
String str_date = gps_date;
int str_len_date = str_date.length() + 1;
char char_array_date[str_len_date];
str_date.toCharArray(char_array_date, str_len_date);
if (millis() - timer > interval ) // do something every hour:3600000)
{
appendFile(SD, "/soil_sensing.txt", char_array_temp);
appendFile(SD, "/soil_sensing.txt", ",");
appendFile(SD, "/soil_sensing.txt", char_array_temp2);
appendFile(SD, "/soil_sensing.txt", ",");
appendFile(SD, "/soil_sensing.txt", char_array_moist);
appendFile(SD, "/soil_sensing.txt", ",");
appendFile(SD, "/soil_sensing.txt", char_array_time);
appendFile(SD, "/soil_sensing.txt", ",");
appendFile(SD, "/soil_sensing.txt", char_array_date);
appendFile(SD, "/soil_sensing.txt", "\n");
Serial.print("Temperature: ");
Serial.println(char_array_temp);
Serial.print("Temperature2: ");
Serial.println(char_array_temp2);
Serial.print("Moisture: ");
Serial.println(char_array_moist);
Serial.print("Time: ");
Serial.println(char_array_time);
Serial.print("Date: ");
Serial.println(char_array_date);
timer = millis();
String lastData = str_temp + ", " + str_temp2 + ", " + str_moist + ", " + str_time + ", " + str_date + "<br>\n";
for (int i = 0; i < LAST_DATA_ARRAY_SIZE - 1; i++) {
lastDataArray [i] = lastDataArray[i + 1];
}
lastDataArray [LAST_DATA_ARRAY_SIZE - 1] = lastData;
for (int i = 0; i < LAST_DATA_ARRAY_SIZE; i++) {
Serial.print(i);
Serial.print(" : ");
Serial.println(lastDataArray[i]);
}
}
}
void writeFile(fs::FS & fs, const char * path, const char * message) {
Serial.printf("Writing file: %s\n", path);
File file = fs.open(path, FILE_WRITE);
if (!file) {
Serial.println("Failed to open file for writing");
return;
}
if (file.print(message)) {
Serial.println("File written");
} else {
Serial.println("Write failed");
}
file.close();
}
void appendFile(fs::FS & fs, const char * path, const char * message) {
Serial.printf("Appending to file: %s\n", path);
File file = fs.open(path, FILE_APPEND);
if (!file) {
Serial.println("Failed to open file for appending");
return;
}
if (file.print(message)) {
Serial.println("Message appended");
} else {
Serial.println("Append failed");
}
file.close();
}
void readFile(fs::FS &fs, const char * path) {
Serial.printf("Reading file: %s\n", path);
File file = fs.open(path);
if (!file) {
Serial.println("Failed to open file for reading");
return;
}
Serial.print("Read from file: ");
while (file.available()) {
Serial.write(file.read());
}
file.close();
}
void onConnect() {
server.send(200, "text/html", SendHTML());
readFile(SD, "/soil_sensing.txt");
}
String SendHTML() {
String ptr = "<!DOCTYPE html> <html>\n";
ptr += "<head>\n";
ptr += "<title>Soil Sensing Data Device 1</title>\n";
ptr += "</head>\n";
ptr += "<body>\n";
ptr += "<br>\n";
ptr += "<p>Soil Sensing 1 </p>\n";
ptr += "<br>\n";
ptr += "<a href='/download'><button>Download</button></a>\n";
ptr += "<br>\n";
ptr += "<p>Last 10 readings: </p>\n";
ptr += "<br>\n";
for (int i = 0; i < LAST_DATA_ARRAY_SIZE; i++) {
ptr += lastDataArray[i];
// ptr += "<br>\n";
}
ptr += "</body>\n";
ptr += "</html>\n";
return ptr;
}
void handle_NotFound() {
server.send(404, "text/plain", "Not found");
}
void SD_file_download() {
File file = SD.open("/soil_sensing.txt");
if (!file) {
Serial.println("Failed to open file for reading");
return;
}
file = SD.open("/soil_sensing.txt");
if (file) {
server.sendHeader("Content-Type", "text/text");
server.sendHeader("Content-Disposition", "attachment; filename=soil_sensing.txt");
server.sendHeader("Connection", "close");
server.streamFile(file, "application/octet-stream");
file.close();
}
}
| [
"noreply@github.com"
] | saradaugbjerg.noreply@github.com |
1d34a4de9f54517b1bdea58238f41f206b568ef3 | 6f5890355a6b21cde87e4a847a9cc8fd7386dc4e | /eights.cpp | e97f72fe4643e0c07cf3ca770b24f5c9841ed5ff | [] | no_license | mjww3/algorithms | 1d5fc8ddc55f93b76a4cb4aff953753ceb7db380 | 95bbcf7fc433714051211cd9e58dd02a50950fa0 | refs/heads/master | 2021-01-19T23:57:00.863976 | 2017-07-01T19:51:50 | 2017-07-01T19:51:50 | 89,052,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 253 | cpp | #include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
int main()
{
long long int T,K;
cin>>T;
while(T--)
{
cin>>K;
long long int result = 192+(K-1)*250;
cout<<result<<endl;
}
return 0;
}
///solved | [
"mukuljainagro@gmail.com"
] | mukuljainagro@gmail.com |
762dac43ebf0eda69e4c19baf07e125e918d61e0 | eed2380fc14c3cc663afb353e5a5a65a820a8b64 | /trade_app/ib_client/IBJts/source/cppclient/client/Order.h | 1b7b30d77bb4249ce91b0596b106519a5a5c969b | [
"MIT"
] | permissive | lishin1980/dockerized_trade_exec | dd7c445c292ef631368425135a7836b1cde2b71c | 6eff2b075ebf79380de21c857b033b4edfad6147 | refs/heads/main | 2023-02-20T12:51:58.854649 | 2021-01-23T00:10:55 | 2021-01-23T00:10:55 | 332,207,247 | 2 | 0 | MIT | 2021-01-23T12:40:19 | 2021-01-23T12:40:18 | null | UTF-8 | C++ | false | false | 8,278 | h | /* Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
#pragma once
#ifndef TWS_API_CLIENT_ORDER_H
#define TWS_API_CLIENT_ORDER_H
#include "TagValue.h"
#include "OrderCondition.h"
#include "SoftDollarTier.h"
#include <float.h>
#include <limits.h>
#define UNSET_DOUBLE DBL_MAX
#define UNSET_INTEGER INT_MAX
#define UNSET_LONG LLONG_MAX
enum Origin { CUSTOMER,
FIRM,
UNKNOWN };
enum AuctionStrategy { AUCTION_UNSET = 0,
AUCTION_MATCH = 1,
AUCTION_IMPROVEMENT = 2,
AUCTION_TRANSPARENT = 3 };
enum UsePriceMmgtAlgo { DONT_USE = 0,
USE,
DEFAULT = UNSET_INTEGER };
struct OrderComboLeg
{
OrderComboLeg()
{
price = UNSET_DOUBLE;
}
double price;
bool operator==( const OrderComboLeg& other) const
{
return (price == other.price);
}
};
typedef std::shared_ptr<OrderComboLeg> OrderComboLegSPtr;
struct Order
{
// order identifier
long orderId = 0;
long clientId = 0;
int permId = 0;
// main order fields
std::string action;
double totalQuantity = 0;
std::string orderType;
double lmtPrice = UNSET_DOUBLE;
double auxPrice = UNSET_DOUBLE;
// extended order fields
std::string tif; // "Time in Force" - DAY, GTC, etc.
std::string activeStartTime = ""; // for GTC orders
std::string activeStopTime = ""; // for GTC orders
std::string ocaGroup; // one cancels all group name
int ocaType = 0; // 1 = CANCEL_WITH_BLOCK, 2 = REDUCE_WITH_BLOCK, 3 = REDUCE_NON_BLOCK
std::string orderRef; // order reference
bool transmit = true; // if false, order will be created but not transmited
long parentId = 0; // Parent order Id, to associate Auto STP or TRAIL orders with the original order.
bool blockOrder = false;
bool sweepToFill = false;
int displaySize = 0;
int triggerMethod = 0; // 0=Default, 1=Double_Bid_Ask, 2=Last, 3=Double_Last, 4=Bid_Ask, 7=Last_or_Bid_Ask, 8=Mid-point
bool outsideRth = false;
bool hidden = false;
std::string goodAfterTime; // Format: 20060505 08:00:00 {time zone}
std::string goodTillDate; // Format: 20060505 08:00:00 {time zone}
std::string rule80A; // Individual = 'I', Agency = 'A', AgentOtherMember = 'W', IndividualPTIA = 'J', AgencyPTIA = 'U', AgentOtherMemberPTIA = 'M', IndividualPT = 'K', AgencyPT = 'Y', AgentOtherMemberPT = 'N'
bool allOrNone = false;
int minQty = UNSET_INTEGER;
double percentOffset = UNSET_DOUBLE; // REL orders only
bool overridePercentageConstraints = false;
double trailStopPrice = UNSET_DOUBLE; // TRAILLIMIT orders only
double trailingPercent = UNSET_DOUBLE;
// financial advisors only
std::string faGroup;
std::string faProfile;
std::string faMethod;
std::string faPercentage;
// institutional (ie non-cleared) only
std::string openClose = ""; // O=Open, C=Close
Origin origin = CUSTOMER; // 0=Customer, 1=Firm
int shortSaleSlot = 0; // 1 if you hold the shares, 2 if they will be delivered from elsewhere. Only for Action="SSHORT
std::string designatedLocation; // set when slot=2 only.
int exemptCode = -1;
// SMART routing only
double discretionaryAmt = 0;
bool eTradeOnly = true;
bool firmQuoteOnly = true;
double nbboPriceCap = UNSET_DOUBLE;
bool optOutSmartRouting = false;
// BOX exchange orders only
int auctionStrategy = AUCTION_UNSET; // AUCTION_MATCH, AUCTION_IMPROVEMENT, AUCTION_TRANSPARENT
double startingPrice = UNSET_DOUBLE;
double stockRefPrice = UNSET_DOUBLE;
double delta = UNSET_DOUBLE;
// pegged to stock and VOL orders only
double stockRangeLower = UNSET_DOUBLE;
double stockRangeUpper = UNSET_DOUBLE;
bool randomizeSize = false;
bool randomizePrice = false;
// VOLATILITY ORDERS ONLY
double volatility = UNSET_DOUBLE;
int volatilityType = UNSET_INTEGER; // 1=daily, 2=annual
std::string deltaNeutralOrderType = "";
double deltaNeutralAuxPrice = UNSET_DOUBLE;
long deltaNeutralConId = 0;
std::string deltaNeutralSettlingFirm = "";
std::string deltaNeutralClearingAccount = "";
std::string deltaNeutralClearingIntent = "";
std::string deltaNeutralOpenClose = "";
bool deltaNeutralShortSale = false;
int deltaNeutralShortSaleSlot = 0;
std::string deltaNeutralDesignatedLocation = "";
bool continuousUpdate = false;
int referencePriceType = UNSET_INTEGER; // 1=Average, 2 = BidOrAsk
// COMBO ORDERS ONLY
double basisPoints = UNSET_DOUBLE; // EFP orders only
int basisPointsType = UNSET_INTEGER; // EFP orders only
// SCALE ORDERS ONLY
int scaleInitLevelSize = UNSET_INTEGER;
int scaleSubsLevelSize = UNSET_INTEGER;
double scalePriceIncrement = UNSET_DOUBLE;
double scalePriceAdjustValue = UNSET_DOUBLE;
int scalePriceAdjustInterval = UNSET_INTEGER;
double scaleProfitOffset = UNSET_DOUBLE;
bool scaleAutoReset = false;
int scaleInitPosition = UNSET_INTEGER;
int scaleInitFillQty = UNSET_INTEGER;
bool scaleRandomPercent = false;
std::string scaleTable = "";
// HEDGE ORDERS
std::string hedgeType; // 'D' - delta, 'B' - beta, 'F' - FX, 'P' - pair
std::string hedgeParam; // 'beta=X' value for beta hedge, 'ratio=Y' for pair hedge
// Clearing info
std::string account; // IB account
std::string settlingFirm;
std::string clearingAccount; // True beneficiary of the order
std::string clearingIntent; // "" (Default), "IB", "Away", "PTA" (PostTrade)
// ALGO ORDERS ONLY
std::string algoStrategy;
TagValueListSPtr algoParams;
TagValueListSPtr smartComboRoutingParams;
std::string algoId;
// What-if
bool whatIf = false;
// Not Held
bool notHeld = false;
bool solicited = false;
// models
std::string modelCode;
// order combo legs
typedef std::vector<OrderComboLegSPtr> OrderComboLegList;
typedef std::shared_ptr<OrderComboLegList> OrderComboLegListSPtr;
OrderComboLegListSPtr orderComboLegs;
TagValueListSPtr orderMiscOptions;
//VER PEG2BENCH fields:
int referenceContractId = UNSET_INTEGER;
double peggedChangeAmount = UNSET_DOUBLE;
bool isPeggedChangeAmountDecrease = false;
double referenceChangeAmount = UNSET_DOUBLE;
std::string referenceExchangeId;
std::string adjustedOrderType;
double triggerPrice = UNSET_DOUBLE;
double adjustedStopPrice = UNSET_DOUBLE;
double adjustedStopLimitPrice = UNSET_DOUBLE;
double adjustedTrailingAmount = UNSET_DOUBLE;
int adjustableTrailingUnit = UNSET_INTEGER;
double lmtPriceOffset = UNSET_DOUBLE;
std::vector<std::shared_ptr<OrderCondition>> conditions;
bool conditionsCancelOrder = false;
bool conditionsIgnoreRth = false;
// ext operator
std::string extOperator = "";
SoftDollarTier softDollarTier = SoftDollarTier("", "", "");
// native cash quantity
double cashQty = UNSET_DOUBLE;
std::string mifid2DecisionMaker = "";
std::string mifid2DecisionAlgo = "";
std::string mifid2ExecutionTrader = "";
std::string mifid2ExecutionAlgo = "";
// don't use auto price for hedge
bool dontUseAutoPriceForHedge = false;
bool isOmsContainer = false;
bool discretionaryUpToLimitPrice = false;
std::string autoCancelDate = "";
double filledQuantity = UNSET_DOUBLE;
int refFuturesConId = UNSET_INTEGER;
bool autoCancelParent = false;
std::string shareholder = "";
bool imbalanceOnly = false;
bool routeMarketableToBbo = false;
long long parentPermId = UNSET_LONG;
UsePriceMmgtAlgo usePriceMgmtAlgo = UsePriceMmgtAlgo::DEFAULT;
public:
// Helpers
static void CloneOrderComboLegs(OrderComboLegListSPtr& dst, const OrderComboLegListSPtr& src);
};
inline void
Order::CloneOrderComboLegs(OrderComboLegListSPtr& dst, const OrderComboLegListSPtr& src)
{
if (!src.get())
return;
dst->reserve(src->size());
OrderComboLegList::const_iterator iter = src->begin();
const OrderComboLegList::const_iterator iterEnd = src->end();
for (; iter != iterEnd; ++iter) {
const OrderComboLeg* leg = iter->get();
if (!leg)
continue;
dst->push_back(OrderComboLegSPtr(new OrderComboLeg(*leg)));
}
}
#endif
| [
"trb5me@virginia.edu"
] | trb5me@virginia.edu |
69700b2276f8a6dc175bec8c750d3757be9ec78a | 74441dee7a5b6c7560e300d30fc97279687ce1e4 | /main.cc | 7841e178ad36f200cfd46de640047e79a73e1d1e | [] | no_license | golegen/MayanCalculator | ddc8d5416cb97315bdd9a4f1b874684e15a9e76f | b3fc44ed7aff4ce651d2f174e24c656147093099 | refs/heads/master | 2021-01-09T11:50:19.757473 | 2015-03-11T02:46:00 | 2015-03-11T02:46:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,303 | cc | /*
* main.cc
*
* Created on: Apr 17, 2012
* Author: jonathan
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <sstream>
#include <cstdio>
#include <cmath>
using namespace std;
/*******************************************************************************
*
*
*
* Helper Functions
*
*
*
*******************************************************************************/
/**
* Function that validates the mayan date to make sure the values
* don't go above or below the bounds.
*/
string validateMayanDate(unsigned int baktun, unsigned int katun, unsigned tun, unsigned int uinal, unsigned int kin) {
while(1) {
if (baktun > 19) {
cout << "date out of bounds.\n";
exit(1);
}
if (katun >= 20) {
katun -= 20;
baktun++;
}
if (tun >= 20) {
tun -= 20;
katun++;
}
if (uinal >= 18) {
uinal -= 18;
tun++;
}
if (kin >= 20) {
kin -= 20;
uinal++;
}
if (baktun < 0 || katun < 0 || tun < 0 || uinal < 0 || kin < 0) {
cout << "date out of bounds.\n";
exit(1);
}
if (kin < 20 && uinal < 18 && tun < 20 && katun < 20 && baktun < 20) {
std::ostringstream oss;
oss << "" << baktun;
oss << "." << katun;
oss << "." << tun;
oss << "." << uinal;
oss << "." << kin;
return oss.str();
}
}
return "error validating date.\n";
}
/**
* Function that validates the gregorian date to make sure the values
* don't go above or below the bounds.
*/
void validateGregorianDate(unsigned int month, unsigned int day, int year) {
if (year > 4772 || year < -3113) {
cout << "date out of bounds.\n";
exit(1);
}
if (year == 4772) {
if (month == 10) {
if (day >= 13) {
cout << "date out of bounds.\n";
exit(1);
}
} else if (month > 10) {
cout << "date out of bounds.\n";
exit(1);
}
}
if (year == -3113) {
if (month == 8) {
if (day <= 10) {
cout << "date out of bounds.\n";
exit(1);
}
} else if (month < 8) {
cout << "date out of bounds.\n";
exit(1);
}
}
}
/**
* Converts the Gregorian Date into a number of days
* Returns the number of days that correspond to the gregorian date
*/
unsigned int convertToDays(unsigned int month, unsigned int day, int year) {
unsigned int days = 0;
int base = -3113;
int monthDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
validateGregorianDate(month, day, year);
if (year > base)
days+= 142;
if (year == base) {
if (month <= 8 && day < 11) {
cout << "Not a valid mayan date.";
} else {
if (month == 8) {
days += day;
days -= 11;
} else {
for (unsigned int i = 8; i < month; i++) {
days += monthDays[i];
}
days += day;
}
return days;
}
} else {
for (;;) {
if ((base % 4 == 0 && !(base % 100 == 0)) || (base % 400 == 0))
days++;
base++;
if (base == year)
break;
days += 365;
}
if ((year % 4 == 0 && !(year % 100 == 0)) || (year % 400 == 0))
monthDays[2] = 29;
for (unsigned int i = 1; i < month; i++) {
days += monthDays[i];
}
days += day;
return days;
}
return 0;
}
/**
* Converts the Mayan Date into a number of days
* Returns the number of days that correspond to the mayan date
*/
unsigned int convertToDays(unsigned int baktun, unsigned int katun, unsigned tun, unsigned int uinal, unsigned int kin) {
unsigned int a, b, c, d, e;
a = 144000 * baktun;
b = 7200 * katun;
c = 360 * tun;
d = 20 * uinal;
e = kin;
string result = validateMayanDate(baktun, katun, tun, uinal, kin);
unsigned int days = a + b + c + d + e;
return days;
}
/**
* Converts the specified days into a mayan date
*/
string convertToMayan(unsigned int dayArg) {
unsigned int days = dayArg;
unsigned int baktun = 0, katun = 0, tun = 0, uinal = 0, kin = 0;
while (days > 0) {
if (days >= 144000) {
baktun++;
days -= 144000;
}
if (days >= 7200) {
days -= 7200;
katun++;
}
if (days >= 360) {
days -= 360;
tun++;
}
if (days >= 20) {
days -= 20;
uinal++;
}
if (days <= 20) {
kin += days;
days = 0;
}
}
string result = validateMayanDate(baktun, katun, tun, uinal, kin);
return result;
}
/**
* Converts the specified days into a gregorian date
*/
string convertToGregorian(unsigned int dayArg) {
unsigned int days = dayArg;
unsigned int month = 1, day = 1;
unsigned int monthDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
string monthNames[13] = {"", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
string dayOfTheWeek[7] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"};
int year = -3113;
if (days < 142) {
for (month = 8; days > monthDays[month]; month++) {
days -= monthDays[month];
}
days += 11;
if (days > monthDays[month]) {
days -= monthDays[month];
month++;
}
day = days;
} else {
days -= 142;
for (;;) {
year++;
if ((year % 4 == 0 && !(year % 100 == 0)) || (year % 400 == 0))
days--;
if (days < 365)
break;
days -= 365;
}
for (month = 1; days > monthDays[month]; month++) {
days -= monthDays[month];
}
day = days;
}
validateGregorianDate(month, day, year);
std::ostringstream oss;
oss << dayOfTheWeek[dayArg % 7] << " ";
oss << monthNames[month] << " ";
oss << day << ", ";
if (year < 0) {
oss << abs (year-1) << " B.C.\n";
} else {
oss << year << " A.D.\n";
}
return oss.str();
}
/*******************************************************************************
*
*
*
* Main Functions
*
*
*
*******************************************************************************/
/*
* Adds a number of days to a mayan date
* Returns the mayan date with the # of days added
*/
void MayanPlus(char* dateArg, char* daysArg) {
unsigned int days, baktun, katun, tun, uinal, kin;
if (sscanf(dateArg, "%u.%u.%u.%u.%u", &baktun, &katun, &tun, &uinal, &kin) != 5) {
cout << "invalid argument for mayan date or days.\n";
exit(1);
}
if (sscanf(daysArg, "%u", &days) != 1) {
cout << "invalid argument for days.\n";
exit(1);
}
unsigned int mayanDays = convertToDays(baktun, katun, tun, uinal, kin);
mayanDays += days;
string result = convertToMayan(mayanDays);
std::cout << result << "\n";
}
/**
* Subtracts a number of days from a mayan date
* Returns the mayan date with the # of days subtracted
*/
void MayanMinus(char* dateArg, char* daysArg) {
unsigned int days, baktun, katun, tun, uinal, kin;
if (sscanf(dateArg, "%u.%u.%u.%u.%u", &baktun, &katun, &tun, &uinal, &kin) != 5) {
cout << "invalid argument for days or mayan date.\n";
exit(1);
}
if (sscanf(daysArg, "%u", &days) != 1) {
cout << "invalid argument for days.\n";
exit(1);
}
unsigned int mayanDays = convertToDays(baktun, katun, tun, uinal, kin);
mayanDays -= days;
string result = convertToMayan(mayanDays);
std::cout << result << "\n";
}
/**
* Compares two mayan dates and
* Returns the number of days in between them.
*/
void MayanCompare(char* dateOne, char* dateTwo) {
unsigned int baktun, katun, tun, uinal, kin;
unsigned int daysOne = 0, daysTwo = 0;
if( sscanf(dateOne, "%u.%u.%u.%u.%u", &baktun, &katun, &tun, &uinal, &kin) != 5) {
cout << "invalid mayan date for second or third argument\n";
exit(1);
} else {
daysOne = convertToDays(baktun, katun, tun, uinal, kin);
}
if( sscanf(dateTwo, "%u.%u.%u.%u.%u", &baktun, &katun, &tun, &uinal, &kin) != 5) {
cout << "invalid mayan date for third argument\n";
exit(1);
} else {
daysTwo = convertToDays(baktun, katun, tun, uinal, kin);
}
int days = daysOne-daysTwo;
if (days >= 0) {
cout << "Day Difference: " << days << " ";
string result = convertToGregorian(days);
std::cout << "\nDate Conversion: " << result << "\n";
} else {
days = daysTwo - daysOne;
cout << "Day Difference: " << days << " ";
string result = convertToGregorian(days);
std::cout << "\nDate Conversion: " << result << "\n";
}
}
/*
* Adds a number of days to a gregoran date
* Returns the gregorian date with the # of days added
*/
void GregorianPlus(char* dateArg, char* daysArg) {
unsigned int days, month, day, year;
if (sscanf(dateArg, "%u/%u/%d", &month, &day, &year) != 3) {
cout << "invalid gregorian date entered.\n";
exit(1);
}
if (sscanf(daysArg, "%u", &days) != 1) {
cout << "invalid argument for days.\n";
exit(1);
}
unsigned int gregorianDays = convertToDays(month, day, year);
gregorianDays += days;
string result = convertToGregorian(gregorianDays);
std::cout << result << "\n";
}
/*
* Subtracts a number of days from a gregoran date
* Returns the gregorian date with the # of days subtracted
*/
void GregorianMinus(char* dateArg, char* daysArg) {
unsigned int days, month, day, year;
if (sscanf(dateArg, "%u/%u/%d", &month, &day, &year) != 3) {
cout << "invalid gregorian date entered.\n";
exit(1);
}
if (sscanf(daysArg, "%u", &days) != 1) {
cout << "invalid argument for days.\n";
exit(1);
}
unsigned int gregorianDays = convertToDays(month, day, year);
gregorianDays -= days;
string result = convertToGregorian(gregorianDays);
std::cout << result << "\n";
}
/**
* Compares two gregorian dates and
* Returns the number of days in between them in gregorian form.
*/
void GregorianCompare(char* dateOne, char* dateTwo) {
unsigned int month, day, year;
unsigned int daysOne = 0, daysTwo = 0;
if (sscanf(dateOne, "%u/%u/%d", &month, &day, &year) != 3) {
cout << "invalid gregorian date for second or third argument.\n";
exit(1);
} else {
daysOne = convertToDays(month, day, year);
}
if (sscanf(dateTwo, "%u/%u/%d", &month, &day, &year) != 3) {
cout << "invalid gregorian date for third argument.\n";
exit(1);
} else {
daysTwo = convertToDays(month, day, year);
}
int days = daysOne-daysTwo;
if (days >= 0) {
cout << "Day Difference: " << days << " ";
string result = convertToGregorian(days);
std::cout << "\nDate Conversion: " << result << "\n";
} else {
days = daysTwo - daysOne;
cout << "Day Difference: " << days << " ";
string result = convertToGregorian(days);
std::cout << "\nDate Conversion: " << result << "\n";
}
}
/**
* Used for testing multiple test cases for gregorian input.
*/
void testFunction(unsigned int month, unsigned int day, int year) {
unsigned int days = convertToDays(month, day, year);
string result = convertToMayan(days);
std::cout << result << "\n";
}
/**
* Used for testing multiple test cases for mayan input.
*/
void testFunction(unsigned int baktun, unsigned int katun, unsigned int tun, unsigned int uinal, unsigned int kin) {
unsigned int days = convertToDays(baktun, katun, tun, uinal, kin);
string result = convertToGregorian(days);
std::cout << result << "\n";
}
/**
* Takes a gregorian date, outputs a mayan date
*/
void GregorianConvert(char* gDate) {
unsigned int month, day;
int year;
if (sscanf(gDate, "%u/%u/%d", &month, &day, &year) != 3)
cout << "invalid gregorian date entered.\n";
else
testFunction(month, day, year);
}
/**
* Takes a mayan date, outputs a gregorian date
*/
void MayanConvert(char* mDate) {
unsigned int baktun, katun, tun, uinal, kin;
if (sscanf(mDate, "%u.%u.%u.%u.%u", &baktun, &katun, &tun, &uinal, &kin) != 5)
cout << "invalid mayan date entered.\n";
else
testFunction(baktun, katun, tun, uinal, kin);
}
/*******************************************************************************
*
*
*
* Start Function
*
*
*
*******************************************************************************/
/*
* main function that checks the arguments and calls the corresponding main function
*/
int main(int argc, char** argv) {
if (argv[1] == NULL) {
cout << "no arguments entered.\n";
exit(1);
}
if (strcmp(argv[1],"m+d") == 0) {
if (argv[2] == NULL || argv[3] == NULL) {
cout << "second or third argument is null\n";
exit(1);
}
MayanPlus(argv[2], argv[3]);
} else if (strcmp(argv[1],"m-d") == 0) {
if (argv[2] == NULL || argv[3] == NULL) {
cout << "second or third argument is null\n";
exit(1);
}
MayanMinus(argv[2], argv[3]);
} else if (strcmp(argv[1],"m-m") == 0) {
if (argv[2] == NULL || argv[3] == NULL) {
cout << "second or third argument is null\n";
exit(1);
}
MayanCompare(argv[2], argv[3]);
} else if (strcmp(argv[1],"g+d") == 0) {
if (argv[2] == NULL || argv[3] == NULL) {
cout << "second or third argument is null\n";
exit(1);
}
GregorianPlus(argv[2], argv[3]);
} else if (strcmp(argv[1],"g-d") == 0) {
if (argv[2] == NULL || argv[3] == NULL) {
cout << "second or third argument is null\n";
exit(1);
}
GregorianMinus(argv[2], argv[3]);
} else if (strcmp(argv[1],"g-g") == 0) {
if (argv[2] == NULL || argv[3] == NULL) {
cout << "second or third argument is null\n";
exit(1);
}
GregorianCompare(argv[2], argv[3]);
} else if (strcmp(argv[1],"g=") == 0) {
if (argv[2] == NULL) {
cout << "second argument is null\n";
exit(1);
}
GregorianConvert(argv[2]);
} else if (strcmp(argv[1],"m=") == 0) {
if (argv[2] == NULL) {
cout << "second argument is null\n";
exit(1);
}
MayanConvert(argv[2]);
} else {
cout << "invalid 1st argument.\n";
}
return 0;
}
| [
"JonAlvarez22@gmail.com"
] | JonAlvarez22@gmail.com |
aec852ff378105a0bcc8f6858cdb4a5e422db39b | ffb03571bad61884bc5b52732426c0c4af5a5192 | /test/test_stringcs/test_strcs_functional_abstracts__contains_cstr.hpp | 845476f1408a1e46c61dd3e98c677f9695afbec8 | [
"MIT"
] | permissive | skrzj-dev/libxccc | 62c1a85fde78921b3febb0bbb0dbafaecad00b5f | 621ce71dcc0ad8fb7a13460aeb3dc250188fb5d2 | refs/heads/master | 2021-01-05T10:07:13.137975 | 2020-11-12T23:42:18 | 2020-11-12T23:42:18 | 240,985,730 | 0 | 0 | MIT | 2020-11-12T22:41:48 | 2020-02-16T23:56:20 | C++ | UTF-8 | C++ | false | false | 18,560 | hpp | /*
* Copyright block:
*
* Source file of libxccc project
*
* Copyright (c) 2019 Jakub Skrzyniarz, skrzj-dev@protonmail.com
*
* Licensed under: MIT license; See the file "LICENSE" of libxccc project for more information.
*
* Copyright block: end
*/
#ifndef _TEST_STRINGCS_ABSTRACTS_CONTAINS_HPP_
#define _TEST_STRINGCS_ABSTRACTS_CONTAINS_HPP_
/* --- */
#include "xcc/test/xcc_test2.hpp"
#include "xcc/test/xcc_test2_paramrow.hpp"
#include "xcc/common/xcc_cpp.hpp"
/* --- */
#include "test_strcs_functional_abstracts__shared.hpp"
/* --- */
template<typename TPL_STROBJ>
class subtest_containsCstr_tplt: public test_xcStringS_testStaticStr_sub_I<TPL_STROBJ>
{
protected: test_xcStringS_testStaticStr_intfs_tpl<TPL_STROBJ>* intfs;
protected: virtual int testedOp_cstr(test_xcStringS_I_abstract<TPL_STROBJ>* intf, TPL_STROBJ* ref_self, const char* param1)=0;
typedef xcc_test3_DATAROW5_DECLT(
xcc_test2_failureDetails_t*
, test_xcStringS_I_abstract<TPL_STROBJ>*
, testParamValued01<TPL_STROBJ>
, const char*
, int
) test_contains_cstr_paramsError_expectRetv_paramRow_t;
protected: int test_contains_cstr_paramsError_expectRetv(
xcc_test2_failureDetails_t* failInfo
, test_xcStringS_I_abstract<TPL_STROBJ>* strIntf
, testParamValued01<TPL_STROBJ> target1
, const char* cstr_param1
, int resultval
)
{
xcc_test2_scope_disconnected();
do
{
xcc_test2_case("checking internal state");
if(1)
{
test_xcStringS_state<TPL_STROBJ> self_state;
test_xcStringS_state<TPL_STROBJ>* ptr_self_state=&self_state;
xcc_test2_expect( 0 == target1.intf->prepareState2(*failInfo, ptr_self_state, target1.value) );
xcc_test2_expect( resultval == testedOp_cstr(strIntf, ptr_self_state->refp_obj_operational, cstr_param1) );
xcc_test2_expect( 0 == target1.intf->verifyState(*failInfo, ptr_self_state, target1.value.c_str()) );
xcc_test2_expect( 0 == target1.intf->deinit(*failInfo, ptr_self_state) );
}
xcc_test2_case_end();
} while(0);
xcc_test2_scope_end();
}
typedef xcc_test3_DATAROW4_DECLT(
xcc_test2_failureDetails_t*
, test_xcStringS_I_abstract<TPL_STROBJ>*
, testParamValued01<TPL_STROBJ>
, int
) test_contains_cstr_againstItself_expectRetv_paramRow_t;
private: int test_contains_cstr_againstItself_expectRetv(
xcc_test2_failureDetails_t* failInfo
, test_xcStringS_I_abstract<TPL_STROBJ>* strIntf
, testParamValued01<TPL_STROBJ> self
, int resultval
)
{
xcc_test2_scope_disconnected();
do
{
xcc_test2_case("checking internal state");
if(1)
{
test_xcStringS_state<TPL_STROBJ> self_state;
test_xcStringS_state<TPL_STROBJ>* ptr_self_state=&self_state;
xcc_test2_expect( 0 == self.intf->prepareState2(*failInfo, ptr_self_state, self.value) );
xcc_test2_expect( resultval == testedOp_cstr(
strIntf
, ptr_self_state->refp_obj_operational
, strIntf->cstr( ptr_self_state->refp_obj_operational)
)
);
xcc_test2_expect( 0 == self.intf->verifyState(*failInfo, ptr_self_state, self.value.c_str() ) );
xcc_test2_expect( 0 == self.intf->deinit(*failInfo, ptr_self_state) );
}
xcc_test2_case_end();
} while(0);
xcc_test2_scope_end();
}
public: subtest_containsCstr_tplt(
test_xcStringS_testStaticStr_intfs_tpl<TPL_STROBJ>* ref_intfs
)
{
this->intfs=ref_intfs;
}
public: int test_contains_strc_ANYCASE(xcc_test2_param_list)
{
xcc_test2_scope("[CSTRD]-[contains-cstr-anycase]");
test_xcStringS_param_I_Set_tplt<TPL_STROBJ>* ref_set=this->intfs->INTF_SET;
xcc_test2_failureDetails_t* refp_failReport=xcc_test2_case_referp_customFailInfo();
/* errors: */
if(1)
{
if(1)
{
test_contains_cstr_paramsError_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsNull->value(), NULL, 0
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsNull->value(), "", 0
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var3"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsNull->value(), "abcd123", 0
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow5(
"contains-cstr-[err-param.01,null self]"
, "FALSE_RETVV-ANY-PARAM-NULL"
, test_contains_cstr_paramsError_expectRetv_paramRow_t
, test_contains_cstr_paramsError_expectRetv
, rows
);
}
if(1)
{
test_contains_cstr_paramsError_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsUninitZero->value(), NULL, 0
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsUninitZero->value(), "", 0
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var3"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsUninitZero->value(), "abcd123", 0
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow5(
"contains-cstr-[err-param.02,uninit-zero-self]"
, "FALSE_RETVV-ANY-PARAM-NULL"
, test_contains_cstr_paramsError_expectRetv_paramRow_t
, test_contains_cstr_paramsError_expectRetv
, rows
);
}
if(1)
{
test_contains_cstr_paramsError_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsUninitNonZero->value(), NULL, 0
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsUninitNonZero->value(), "", 0
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var3"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsUninitNonZero->value(), "abcd123", 0
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow5(
"contains-cstr-[err-param.03,uninit-non-zero-self]"
, "FALSE_RETVV-ANY-PARAM-NULL"
, test_contains_cstr_paramsError_expectRetv_paramRow_t
, test_contains_cstr_paramsError_expectRetv
, rows
);
}
if(1)
{
test_contains_cstr_paramsError_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitEmpty->value(), NULL, 0
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow5(
"contains-cstr-[err-param.04,init-empty.self]"
, "FALSE_RETVV-ANY-PARAM-NULL"
, test_contains_cstr_paramsError_expectRetv_paramRow_t
, test_contains_cstr_paramsError_expectRetv
, rows
);
}
if(1)
{
test_contains_cstr_paramsError_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("qwerty386"), NULL, 0
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow5(
"contains-cstr-[err-param.05,init-non-empty.self]"
, "FALSE_RETVV-ANY-PARAM-NULL"
, test_contains_cstr_paramsError_expectRetv_paramRow_t
, test_contains_cstr_paramsError_expectRetv
, rows
);
}
}
/* errors: done */
/* itself x itself: */
if(1)
{
if(1)
{
test_contains_cstr_againstItself_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW4_ITZ_T(test_contains_cstr_againstItself_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsUninitZero->value(), 0
)
, xcc_test3_DATAROW4_ITZ_T(test_contains_cstr_againstItself_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsUninitNonZero->value(), 0
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow4(
"contains-cstr-[err-param.01,self-against-self]"
, "TODO"
, test_contains_cstr_againstItself_expectRetv_paramRow_t
, test_contains_cstr_againstItself_expectRetv
, rows
);
}
if(1)
{
test_contains_cstr_againstItself_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW4_ITZ_T(test_contains_cstr_againstItself_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitEmpty->value(), 0
)
, xcc_test3_DATAROW4_ITZ_T(test_contains_cstr_againstItself_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("qwerty123"), 1
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow4(
"contains-cstr-[ok-param.01,self-against-self]"
, "TODO"
, test_contains_cstr_againstItself_expectRetv_paramRow_t
, test_contains_cstr_againstItself_expectRetv
, rows
);
}
}
/* itself x itself: done */
/* ok params: */
if(1)
{
if(1)
{
test_contains_cstr_paramsError_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitEmpty->value(), "", 0
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("qwerty386"), "qwerty386", 1
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("xxx.qwerty386"), "qwerty386", 1
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("zxcvby386"), "qwerty386", 0
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow5(
"contains-cstr-[ok-param.01,exact-match]"
, "FALSE_RETVV-ANY-PARAM-NULL"
, test_contains_cstr_paramsError_expectRetv_paramRow_t
, test_contains_cstr_paramsError_expectRetv
, rows
);
}
}
/* ok params: done */
xcc_test2_scope_end();
}
public: int test_contains_cstr_okParamsMatchCaseInsensitive(xcc_test2_param_list)
{
xcc_test2_scope("[CSTRD]-[contains-cstr-matchCaseInsensitive]");
test_xcStringS_param_I_Set_tplt<TPL_STROBJ>* ref_set=this->intfs->INTF_SET;
xcc_test2_failureDetails_t* refp_failReport=xcc_test2_case_referp_customFailInfo();
if(1)
{
test_contains_cstr_paramsError_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz123ABCDZ!@#$%^&*()"), "abcdz123ABCDZ!@#$%^&*()", 1
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz123ABCDZ!@#$%^&*()"), "ABCDZ123abcdz!@#$%^&*()", 1
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var3"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz123abcdz!@#$%^&*()"), "ABCDZ123ABCDZ!@#$%^&*()", 1
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var4"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("ABCDZ123ABCDZ!@#$%^&*()"), "abcdz123abcdz!@#$%^&*()", 1
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow5(
"contains-cstr-[err-param.210.case-insensitive-match]"
, "FALSE_RETVV-ANY-PARAM-NULL"
, test_contains_cstr_paramsError_expectRetv_paramRow_t
, test_contains_cstr_paramsError_expectRetv
, rows
);
}
xcc_test2_scope_end();
}
};
template<typename TPL_STROBJ>
class subtest_containsCstr_eqCaseSensitive_tplt: public subtest_containsCstr_tplt<TPL_STROBJ>
{
/* --- --- --- --- */
/* --- --- --- --- */
/* --- --- --- --- */
using typename subtest_containsCstr_tplt<TPL_STROBJ>::test_contains_cstr_paramsError_expectRetv_paramRow_t;
using subtest_containsCstr_tplt<TPL_STROBJ>::intfs;
using subtest_containsCstr_tplt<TPL_STROBJ>::test_contains_cstr_paramsError_expectRetv;
/* --- --- --- --- */
/* --- --- --- --- */
/* --- --- --- --- */
public: subtest_containsCstr_eqCaseSensitive_tplt(test_xcStringS_testStaticStr_intfs_tpl<TPL_STROBJ>* ref_intfs): subtest_containsCstr_tplt<TPL_STROBJ>(ref_intfs)
{
}
protected: int testedOp_cstr(test_xcStringS_I_abstract<TPL_STROBJ>* intf, TPL_STROBJ* ref_self, const char* param1)
{
return intf->contains_cstr(ref_self, param1);
}
public: int perform(xcc_test2_param_list)
{
int x=0;
x+=this->test_contains_strc_ANYCASE(xcc_test2_param_list_forward);
x+=this->test_contains_cstr_okParamsMatchCaseSensitive(xcc_test2_param_list_forward);
return x;
}
public: int test_contains_cstr_okParamsMatchCaseSensitive(xcc_test2_param_list)
{
xcc_test2_scope("[CSTRD]-[contains-cstr-matchCaseInsensitive]");
test_xcStringS_param_I_Set_tplt<TPL_STROBJ>* ref_set=this->intfs->INTF_SET;
xcc_test2_failureDetails_t* refp_failReport=xcc_test2_case_referp_customFailInfo();
if(1)
{
test_contains_cstr_paramsError_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz.123ABCZ.!@#$%^&*().zyx"), "abcdz.123ABCZ.!@#$%^&*().zyx", 1
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz.123ABCZ.!@#$%^&*().zyx"), "ABCDZ.123abcz.!@#$%^&*().zyx", 0
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var3"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz.123abcz.!@#$%^&*().zyx"), "ABCZ", 0
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var4"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz.123abcz.!@#$%^&*().zyx"), "abcz", 1
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow5(
"contains-cstr-[ok-param.10110.case-insensitive-match-of-entire-string]"
, "FALSE_RETVV-ANY-PARAM-NULL"
, test_contains_cstr_paramsError_expectRetv_paramRow_t
, test_contains_cstr_paramsError_expectRetv
, rows
);
}
xcc_test2_scope_end();
}
};
template<typename TPL_STROBJ>
class subtest_containsCstr_eqCaseInSensitive_tplt: public subtest_containsCstr_tplt<TPL_STROBJ>
{
/* --- --- --- --- */
/* --- --- --- --- */
/* --- --- --- --- */
using typename subtest_containsCstr_tplt<TPL_STROBJ>::test_contains_cstr_paramsError_expectRetv_paramRow_t;
using subtest_containsCstr_tplt<TPL_STROBJ>::intfs;
using subtest_containsCstr_tplt<TPL_STROBJ>::test_contains_cstr_paramsError_expectRetv;
/* --- --- --- --- */
/* --- --- --- --- */
/* --- --- --- --- */
public: subtest_containsCstr_eqCaseInSensitive_tplt(test_xcStringS_testStaticStr_intfs_tpl<TPL_STROBJ>* ref_intfs): subtest_containsCstr_tplt<TPL_STROBJ>(ref_intfs)
{
}
protected: int testedOp_cstr(test_xcStringS_I_abstract<TPL_STROBJ>* intf, TPL_STROBJ* ref_self, const char* param1)
{
return intf->containsNC_cstr(ref_self, param1);
}
public: int perform(xcc_test2_param_list)
{
int x=0;
x+=this->test_contains_strc_ANYCASE(xcc_test2_param_list_forward);
x+=this->test_containsObj_cstr_okParamsMatchCaseInsensitive(xcc_test2_param_list_forward);
return x;
}
/* --- --- --- --- */
/* --- --- --- --- */
/* --- --- --- --- */
public: int test_containsObj_cstr_okParamsMatchCaseInsensitive(xcc_test2_param_list)
{
xcc_test2_scope("[CSTRD]-[contains-obj-matchCaseInsensitive]");
test_xcStringS_param_I_Set_tplt<TPL_STROBJ>* ref_set=this->intfs->INTF_SET;
xcc_test2_failureDetails_t* refp_failReport=xcc_test2_case_referp_customFailInfo();
if(1)
{
test_contains_cstr_paramsError_expectRetv_paramRow_t rows[]=
{
xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var1"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz.123ABCZ.!@#$%^&*().zyx"), "abcdz.123ABCZ.!@#$%^&*().zyx", 1
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var2"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz.123ABCZ.!@#$%^&*().zyx"), "ABCDZ.123abcz.!@#$%^&*().zyx", 1
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var3"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz.123abcz.!@#$%^&*().zyx"), "ABCZ", 1
)
, xcc_test3_DATAROW5_ITZ_T(test_contains_cstr_paramsError_expectRetv_paramRow_t, "var4"
, refp_failReport, intfs->INTF_STATICSTR
, intfs->INTF_SET->strcsInitNonEmpty->value("abcdz.123abcz.!@#$%^&*().zyx"), "abcz", 1
)
, xcc_test3_DATAROWX_ITZ_TERM()
};
xcc_test3_case_forDataRow5(
"contains-cstr-[ok-param.10110.case-insensitive-match-of-entire-string]"
, "FALSE_RETVV-ANY-PARAM-NULL"
, test_contains_cstr_paramsError_expectRetv_paramRow_t
, test_contains_cstr_paramsError_expectRetv
, rows
);
}
xcc_test2_scope_end();
}
};
#endif
| [
"58396303+skrzj-dev@users.noreply.github.com"
] | 58396303+skrzj-dev@users.noreply.github.com |
e6f9b51cecbdb6102c2a6cbfb9d83f826cac5670 | a8c5043594e5540b6a31939626474289ac45fe3b | /ExampleFramework/ExampleFramework/core/Name/Model/NameModel.cpp | 43ee85697b71a0882f3e917732c4000fdb95515d | [] | no_license | rexcosta/Example-Swift-Obj-C-and-C-plus-plus | 1c90a5ddeb7b89782fab952caea4db4254ee24bb | ac45bb8aa29e6a75f7d10e52a3588de208e3b31e | refs/heads/master | 2022-06-18T09:46:45.623291 | 2020-05-03T11:36:13 | 2020-05-03T11:36:13 | 260,894,189 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,942 | cpp | //
// The MIT License (MIT)
//
// Copyright (c) 2020 Effective Like ABoss, David Costa Gonçalves
//
// 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 "NameModel.hpp"
using namespace std;
using namespace example;
NameModel::NameModel() {
this->name = "";
this->nameHistory = "";
this->id = 0;
}
NameModel::NameModel(string name, string nameHistory, int id) {
this->name = name;
this->nameHistory = nameHistory;
this->id = id;
}
NameModel::~NameModel() {
}
void NameModel::setName(string name) {
this->name = name;
}
string NameModel::getName() const {
return name;
}
void NameModel::setNameHistory(string nameHistory) {
this->nameHistory = nameHistory;
}
string NameModel::getNameHistory() const {
return nameHistory;
}
int NameModel::getId() const {
return id;
}
bool NameModel::operator==(const NameModel &rhs) const {
return id == rhs.getId();
}
| [
"david.1991@live.com"
] | david.1991@live.com |
ff6b21d2996e9d884c2152c78b14e2ef0d5530f4 | 63a381d90124527f8dd7d833f3da70b3160f1869 | /src/Underworld/Conv/CodeVM.hpp | 8e4ce818bd5c0b9a9ba7b145e8716ea42febadda | [] | no_license | zengnotes/MultiplayerOnlineGame | f75fe82c1ce53c631466c209db7c397ecbff27e2 | 31561dedb03d77d69dff0ea2853aa666ec4c7751 | refs/heads/master | 2021-01-20T06:32:50.570693 | 2014-11-11T20:02:43 | 2014-11-11T20:02:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,296 | hpp | //
// Underworld - an Ultima Underworld remake project
// Copyright (C) 2002-2014 Michael Fink
//
/// \file Underworld/Conv/CodeVM.hpp Conversation code virtual machine
//
#pragma once
// includes
#include <string>
#include <vector>
#include "Savegame.hpp"
#include "ConvStack.hpp"
#include "ConvGlobals.hpp"
/// for more info about the underworld conversation assembler script, look in
/// the file docs/uw-formats.txt
/// a gnu-gdb style debugger named "cnvdbg" and a disassembler and experimental
/// decompiler (produces C-like code) is available in the "tools" folder.
// forward references
namespace Underworld
{
class ConvGlobals;
}
namespace Conv
{
// enums
/// function types
enum T_enDataType
{
dataTypeUnknown, ///< unknown data type
dataTypeVoid, ///< void data type
dataTypeInt, ///< integer data type
dataTypeString, ///< string data type
};
// structs
/// imported item info
typedef struct
{
/// type of the function/global memory location
T_enDataType m_enDataType;
/// name of imported item
std::string m_strName;
} ImportedItem;
// classes
class CodeCallback
{
public:
/// ctor
CodeCallback() throw() {}
/// prints "say" string
virtual void Say(Uint16 index) = 0;
/// shows menu, with possible answers
virtual Uint16 BablMenu(const std::vector<Uint16>& uiAnswerStringIds) = 0;
/// executes external function
virtual Uint16 ExternalFunc(const char* pszFuncName, ConvStack& stack) = 0;
};
/// \brief Conversation code virtual machine
/// \details Virtual machine to run conversation code loaded from cnv.ark files.
/// It emulates a forth-like stack-based opcode language with intrinsic functions
/// (called imported functions). The code segment contains 16-bit opcodes that
/// are executed one by one using the step() method. It returns false when the
/// execution is stopped due to an error or when conversation has finished.
/// The class uses the CodeCallback to let the user respond to
/// higher-level actions in the virtual machine.
///
/// The conversation code first has to be loaded using
/// Import::ConvLoader, then Init() can be called. When exiting,
/// Done() should be called to write back conversation globals for the given
/// conversation.
class CodeVM
{
public:
/// ctor
CodeVM();
/// dtor
virtual ~CodeVM() {}
/// inits virtual machine after filling code segment
void Init(CodeCallback* pCodeCallback, const Underworld::ConvGlobals& cg);
/// does a step in code; returns false when program has stopped
bool Step();
/// writes back conv globals
void Done(Underworld::ConvGlobals& cg);
/// replaces all @ placeholder in the given string
void ReplacePlaceholder(std::string& str);
// get functions
/// returns code segment
std::vector<Uint16>& CodeSegment(){ return m_code; }
/// returns map with imported functions
std::map<Uint16, ImportedItem>& ImportedFuncs(){ return m_mapImportedFuncs; }
/// returns map with imported globals
std::map<Uint16, ImportedItem>& ImportedGlobals(){ return m_mapImportedGlobals; }
/// returns string block to use for this conversation
Uint16 StringBlock() const { return m_uiStringBlock; }
/// returns number of reserved global variables
Uint16 GlobalsReserved() const { return m_uiGlobalsReserved; }
/// returns local string value
virtual std::string GetLocalString(Uint16 uiStrNum);
// set functions
/// sets result register
void SetResultRegister(Uint16 val);
/// sets conversation slot
void ConvSlot(Uint16 uiConvSlot){ m_uiConvSlot = uiConvSlot; }
/// sets string block to use
void StringBlock(Uint16 uiStringBlock){ m_uiStringBlock = uiStringBlock; }
/// sets number of globals reserved at start of memory
void GlobalsReserved(Uint16 uiGlobalsReserved){ m_uiGlobalsReserved = uiGlobalsReserved; }
protected:
/// called when saying a string
void SayOp(Uint16 uiStringId);
/// executes an imported function
virtual void ImportedFunc(const char* pszFuncName);
/// queries for a global variable value
virtual Uint16 GetGlobal(const char* pszGlobName);
/// sers global variable value
virtual void SetGlobal(const char* pszGlobName, Uint16 val);
/// called when storing a value to the stack
void StoreValue(Uint16 at, Uint16 val);
/// called when fetching a value from stack
void FetchValue(Uint16 at);
protected:
/// conversation slot number
Uint16 m_uiConvSlot;
/// number of string block to use
Uint16 m_uiStringBlock;
/// code bytes
std::vector<Uint16> m_code;
/// instruction pointer
Uint16 m_uiInstrPtr;
/// base (frame) pointer
Uint16 m_uiBasePtr;
/// stack
ConvStack m_stack;
/// number of values for globals reserved on stack
Uint16 m_uiGlobalsReserved;
/// tracks call/ret level
unsigned int m_uiCallLevel;
/// result register for (imported) functions
Uint16 m_uiResultRegister;
/// indicates if conversation has finished
bool m_bFinished;
/// all imported functions
std::map<Uint16, ImportedItem> m_mapImportedFuncs;
/// names of all imported globals
std::map<Uint16, ImportedItem> m_mapImportedGlobals;
/// code callback pointer
CodeCallback* m_pCodeCallback;
};
} // namespace Conv
| [
"michael.fink@asamnet.de"
] | michael.fink@asamnet.de |
caa7369cef122e29e93ca6dcdd9419d8e597a464 | 8e9e2ef1eec0393bca595ce7c703006b52b566bc | /CENG315/THE2/test.cpp | 99756e8437aa86ebec0b1091111dcc70073afcd4 | [] | no_license | aralyekta/METU | 964c45b08a7d9b3a12cff18280f211b38991f0f1 | 3643841facd8e90d3525ecafa3d94751852e7f25 | refs/heads/master | 2023-04-06T04:00:39.595100 | 2023-03-22T13:25:15 | 2023-03-22T13:25:15 | 289,202,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,964 | cpp | //This file is entirely for your test purposes.
//This will not be evaluated, you can change it and experiment with it as you want.
#include <iostream>
#include <fstream>
#include <random>
#include <ctime>
#include <algorithm> // DELET THIS
#include "the2.h"
//the2.h only contains declaration of the function quickSort and quickSort3 which are:
//void quickSort(unsigned short* arr, long &swap, double & avg_dist, double & max_dist, bool hoare, int size);
//void quickSort3(unsigned short *arr, long &swap, long &comparison, int size);
using namespace std;
void randomFill(unsigned short*& arr, unsigned short*& arr2, int size, unsigned short minval, unsigned short interval)
{
arr = new unsigned short [size];
arr2 = new unsigned short [size];
for (int i=0; i <size; i++)
{
unsigned short curNum = minval + (random() % interval);
arr[i] = curNum;
arr2[i] = curNum;
}
}
void print_to_file(unsigned short* arr, int size)
{
ofstream ofile;
ofile.open("sorted.txt");
ofile<<size<<endl;
for(int i=0;i<size; i++)
ofile<<arr[i]<<endl;
}
void read_from_file(unsigned short*& arr, int& size)
{
char addr[]= "in01.txt"; //You can test from in01.txt to in04.txt
ifstream infile (addr);
if (!infile.is_open())
{
cout << "File \'"<< addr
<< "\' can not be opened. Make sure that this file exists." <<endl;
return;
}
infile >> size;
arr = new unsigned short [size];
for (int i=0; i<size;i++) {
infile >> arr[i];
}
}
void test()
{
clock_t begin, end;
double duration;
char f_select='3'; // c tests for quicksort with classical partitioning, h for quicksort with hoare partitioning, 3 for 3-way quicksort
//data generation and initialization- you may test with your own data
long comparison=0;
long swap=0;
double avg_dist=0;
double max_dist=0;
bool hoare, q3;
bool rand_fill=true;
switch(f_select) {
case '3':
q3=true;
break;
case 'h':
q3=false;
hoare=true;
break;
case 'c':
q3=false;
hoare=false;
break;
default:
cout<<"Invalid argument for function selection."<<endl;
return;
}
int size= 1 << 21; // for maximum see the "boundaries for test cases" part
unsigned short minval=0;
unsigned short interval= (unsigned short)((1<<16)-1); // unsigned short 65535 in maximum , you can try to minimize interval for data generation to make your code test more equality conditions
unsigned short *arr;
unsigned short *arr2;
/*
BOUNDARIES FOR TEST CASES. THESE ARE THE MOST DIFFICULT INPUTS TO BE TESTED
***QUICKSORT WITH CLASSICAL PARTITIONING *** NOTE THAT IT PERFORMS BETTER WHEN THERE ARE LESS EQUALITY CONDITIONS IN OUR CASE LARGER INTERVAL FOR NUMBERS TO BE GENERATED
size <= 2^16 when interval == 2^16-1
size <= 2^20 when interval >= 2^13-1
size <= 2^19 when interval >= 2^11-1
size <= 2^18 when interval >= 2^9 -1
size <= 2^17 when interval >= 2^7 -1
size <= 2^16 when interval >= 2^5 -1
********************************
***QUICKSORT WITH HOARE PARTITIONING *** INTERVAL HAS NO EFFECT
size <= 2^22
********************************
***3-WAY QUICKSORT *** IT PERFORMS BETTER WHEN THERE ARE MORE EQUALITY CONDITIONS IN OUR CASE SMALLER INTERVAL FOR NUMBERS TO BE GENERATED
size <=2^25 when interval <= 2^2-1
size <=2^24 when interval <= 2^5-1
size <=2^23 when interval <= 2^10-1
size <=2^22 when interval <= 2^16-1
********************************
*/
if(rand_fill)
randomFill(arr, arr2, size, minval, interval); //Randomly generate initial array
else
read_from_file(arr, size); //Read the test inputs. in01.txt through in04.txt exists. Due to the limitation of the system larger inputs are not stored but generated on evaluation.
//data generation or read end
if ((begin = clock() ) ==-1)
cerr << "clock error" << endl;
//Function call for the solution
if(q3) {
std::cout << "Quicksort 3\n";
quickSort3(arr, swap, comparison, size);
}
else {
std::cout << "Quicksort with hoare:" << hoare << "\n";
quickSort(arr, swap, avg_dist, max_dist, hoare, size);
}
sort(arr2, arr2+size, greater<unsigned short>());
//Function end
if ((end = clock() ) ==-1)
cerr << "clock error" << endl;
//Calculate duration and print output
cout<<"Number of Swaps: " << swap <<endl;
duration = ((double) end - begin) / CLOCKS_PER_SEC;
cout << "Duration: " << duration << " seconds." <<endl;
if(q3)
cout<<"Number of Comparisons: " << comparison <<endl;
else
{
cout<<"Average Distance of Swaps(0 for quickSort3): " << avg_dist <<endl;
cout<<"Maximum Distance of Swaps(0 for quickSort3): " << max_dist <<endl;
}
bool wrong = false;
cout <<"Size of the array:"<< size << endl;
for (int i = 0; i < size; i++) {
if (arr[i] != arr2[i]) {
std::cout << "There was a mistake with index:" << i << "\n";
std::cout << "In first it is:" << arr[i] << " and on the other it is:" << arr2[i] << "\n";
wrong = true;
break;
}
}
cout << "\n";
if (!wrong) {
std::cout << "It was correct\n";
}
else {
std::cout << "It was wrong\n";
}
//print_to_file(arr,size);
delete [] arr;
delete [] arr2;
//Calculation and output end
}
int main()
{
srandom(time(0));
test();
// // Case:
// unsigned short arr[8] = {1,2,1,3,4,1,5,6};
// int size = 8;
// // unsigned short arr[] = {1,2,1,3,4,1,5};
// // int size = 7;
// // unsigned short arr[] = {2,4,3};
// // int size = 3;
// long swap = 0;
// long comparison = 0;
// double avg_dist = 0;
// double max_dist = 0;
// bool hoare = true;
// //quickSort(arr, swap, avg_dist, max_dist, hoare, size);
// quickSort3(arr, swap, comparison, size);
// for (int i = 0; i < size; i++) {
// cout << arr[i] << " ";
// }
// cout << "\n";
// //cout << "swap:" << swap << " avg_dist:" << avg_dist << " max_dist:" << max_dist << "\n";
// cout << "swap:" << swap << " comparison:" << comparison << "\n";
return 0;
}
| [
"aralyektayarimca@gmail.com"
] | aralyektayarimca@gmail.com |
d5c8f516c92ef8f9868ed377e9d40ee2b450db74 | 1af49694004c6fbc31deada5618dae37255ce978 | /cc/trees/ukm_manager.cc | b3761e46d3d4a81e7f1d25f83828fe42f0342513 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 13,434 | 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 "cc/trees/ukm_manager.h"
#include <algorithm>
#include <utility>
#include "cc/metrics/compositor_frame_reporter.h"
#include "cc/metrics/throughput_ukm_reporter.h"
#include "components/viz/common/quads/compositor_frame.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
namespace cc {
UkmManager::UkmManager(std::unique_ptr<ukm::UkmRecorder> recorder)
: recorder_(std::move(recorder)) {
DCHECK(recorder_);
}
UkmManager::~UkmManager() {
RecordCheckerboardUkm();
RecordRenderingUkm();
}
void UkmManager::SetSourceId(ukm::SourceId source_id) {
// If we accumulated any metrics, record them before resetting the source.
RecordCheckerboardUkm();
RecordRenderingUkm();
source_id_ = source_id;
}
void UkmManager::SetUserInteractionInProgress(bool in_progress) {
if (user_interaction_in_progress_ == in_progress)
return;
user_interaction_in_progress_ = in_progress;
if (!user_interaction_in_progress_)
RecordCheckerboardUkm();
}
void UkmManager::AddCheckerboardStatsForFrame(int64_t checkerboard_area,
int64_t num_missing_tiles,
int64_t total_visible_area) {
DCHECK_GE(total_visible_area, checkerboard_area);
if (source_id_ == ukm::kInvalidSourceId || !user_interaction_in_progress_)
return;
checkerboarded_content_area_ += checkerboard_area;
num_missing_tiles_ += num_missing_tiles;
total_visible_area_ += total_visible_area;
num_of_frames_++;
}
void UkmManager::AddCheckerboardedImages(int num_of_checkerboarded_images) {
if (user_interaction_in_progress_) {
num_of_images_checkerboarded_during_interaction_ +=
num_of_checkerboarded_images;
}
total_num_of_checkerboarded_images_ += num_of_checkerboarded_images;
}
void UkmManager::RecordCheckerboardUkm() {
// Only make a recording if there was any visible area from PictureLayers,
// which can be checkerboarded.
if (num_of_frames_ > 0 && total_visible_area_ > 0) {
DCHECK_NE(source_id_, ukm::kInvalidSourceId);
ukm::builders::Compositor_UserInteraction(source_id_)
.SetCheckerboardedContentArea(checkerboarded_content_area_ /
num_of_frames_)
.SetNumMissingTiles(num_missing_tiles_ / num_of_frames_)
.SetCheckerboardedContentAreaRatio(
(checkerboarded_content_area_ * 100) / total_visible_area_)
.SetCheckerboardedImagesCount(
num_of_images_checkerboarded_during_interaction_)
.Record(recorder_.get());
}
checkerboarded_content_area_ = 0;
num_missing_tiles_ = 0;
num_of_frames_ = 0;
total_visible_area_ = 0;
num_of_images_checkerboarded_during_interaction_ = 0;
}
void UkmManager::RecordRenderingUkm() {
if (source_id_ == ukm::kInvalidSourceId)
return;
ukm::builders::Compositor_Rendering(source_id_)
.SetCheckerboardedImagesCount(total_num_of_checkerboarded_images_)
.Record(recorder_.get());
total_num_of_checkerboarded_images_ = 0;
}
void UkmManager::RecordThroughputUKM(
FrameSequenceTrackerType tracker_type,
FrameSequenceMetrics::ThreadType thread_type,
int64_t throughput) const {
ukm::builders::Graphics_Smoothness_PercentDroppedFrames builder(source_id_);
switch (thread_type) {
case FrameSequenceMetrics::ThreadType::kMain: {
switch (tracker_type) {
#define CASE_FOR_MAIN_THREAD_TRACKER(name) \
case FrameSequenceTrackerType::k##name: \
builder.SetMainThread_##name(throughput); \
break;
CASE_FOR_MAIN_THREAD_TRACKER(CompositorAnimation);
CASE_FOR_MAIN_THREAD_TRACKER(MainThreadAnimation);
CASE_FOR_MAIN_THREAD_TRACKER(PinchZoom);
CASE_FOR_MAIN_THREAD_TRACKER(RAF);
CASE_FOR_MAIN_THREAD_TRACKER(ScrollbarScroll);
CASE_FOR_MAIN_THREAD_TRACKER(TouchScroll);
CASE_FOR_MAIN_THREAD_TRACKER(Video);
CASE_FOR_MAIN_THREAD_TRACKER(WheelScroll);
CASE_FOR_MAIN_THREAD_TRACKER(CanvasAnimation);
CASE_FOR_MAIN_THREAD_TRACKER(JSAnimation);
#undef CASE_FOR_MAIN_THREAD_TRACKER
default:
NOTREACHED();
break;
}
break;
}
case FrameSequenceMetrics::ThreadType::kCompositor: {
switch (tracker_type) {
#define CASE_FOR_COMPOSITOR_THREAD_TRACKER(name) \
case FrameSequenceTrackerType::k##name: \
builder.SetCompositorThread_##name(throughput); \
break;
CASE_FOR_COMPOSITOR_THREAD_TRACKER(CompositorAnimation);
CASE_FOR_COMPOSITOR_THREAD_TRACKER(MainThreadAnimation);
CASE_FOR_COMPOSITOR_THREAD_TRACKER(PinchZoom);
CASE_FOR_COMPOSITOR_THREAD_TRACKER(RAF);
CASE_FOR_COMPOSITOR_THREAD_TRACKER(ScrollbarScroll);
CASE_FOR_COMPOSITOR_THREAD_TRACKER(TouchScroll);
CASE_FOR_COMPOSITOR_THREAD_TRACKER(Video);
CASE_FOR_COMPOSITOR_THREAD_TRACKER(WheelScroll);
#undef CASE_FOR_COMPOSITOR_THREAD_TRACKER
default:
NOTREACHED();
break;
}
break;
}
case FrameSequenceMetrics::ThreadType::kUnknown:
NOTREACHED();
break;
}
builder.Record(recorder_.get());
}
void UkmManager::RecordAggregateThroughput(AggregationType aggregation_type,
int64_t throughput_percent) const {
ukm::builders::Graphics_Smoothness_PercentDroppedFrames builder(source_id_);
switch (aggregation_type) {
case AggregationType::kAllAnimations:
builder.SetAllAnimations(throughput_percent);
break;
case AggregationType::kAllInteractions:
builder.SetAllInteractions(throughput_percent);
break;
case AggregationType::kAllSequences:
builder.SetAllSequences(throughput_percent);
break;
}
builder.Record(recorder_.get());
}
void UkmManager::RecordCompositorLatencyUKM(
CompositorFrameReporter::FrameReportType report_type,
const std::vector<CompositorFrameReporter::StageData>& stage_history,
const CompositorFrameReporter::ActiveTrackers& active_trackers,
const viz::FrameTimingDetails& viz_breakdown) const {
using StageType = CompositorFrameReporter::StageType;
ukm::builders::Graphics_Smoothness_Latency builder(source_id_);
if (report_type == CompositorFrameReporter::FrameReportType::kDroppedFrame) {
builder.SetMissedFrame(true);
}
// Record each stage
for (const CompositorFrameReporter::StageData& stage : stage_history) {
switch (stage.stage_type) {
#define CASE_FOR_STAGE(name) \
case StageType::k##name: \
builder.Set##name((stage.end_time - stage.start_time).InMicroseconds()); \
break;
CASE_FOR_STAGE(BeginImplFrameToSendBeginMainFrame);
CASE_FOR_STAGE(SendBeginMainFrameToCommit);
CASE_FOR_STAGE(Commit);
CASE_FOR_STAGE(EndCommitToActivation);
CASE_FOR_STAGE(Activation);
CASE_FOR_STAGE(EndActivateToSubmitCompositorFrame);
CASE_FOR_STAGE(TotalLatency);
#undef CASE_FOR_STAGE
// Break out kSubmitCompositorFrameToPresentationCompositorFrame to report
// the viz breakdown.
case StageType::kSubmitCompositorFrameToPresentationCompositorFrame:
builder.SetSubmitCompositorFrameToPresentationCompositorFrame(
(stage.end_time - stage.start_time).InMicroseconds());
if (viz_breakdown.received_compositor_frame_timestamp.is_null())
break;
builder
.SetSubmitCompositorFrameToPresentationCompositorFrame_SubmitToReceiveCompositorFrame(
(viz_breakdown.received_compositor_frame_timestamp -
stage.start_time)
.InMicroseconds());
if (viz_breakdown.draw_start_timestamp.is_null())
break;
builder
.SetSubmitCompositorFrameToPresentationCompositorFrame_ReceivedCompositorFrameToStartDraw(
(viz_breakdown.draw_start_timestamp -
viz_breakdown.received_compositor_frame_timestamp)
.InMicroseconds());
if (viz_breakdown.swap_timings.is_null())
break;
builder
.SetSubmitCompositorFrameToPresentationCompositorFrame_StartDrawToSwapStart(
(viz_breakdown.swap_timings.swap_start -
viz_breakdown.draw_start_timestamp)
.InMicroseconds());
builder
.SetSubmitCompositorFrameToPresentationCompositorFrame_SwapStartToSwapEnd(
(viz_breakdown.swap_timings.swap_end -
viz_breakdown.swap_timings.swap_start)
.InMicroseconds());
builder
.SetSubmitCompositorFrameToPresentationCompositorFrame_SwapEndToPresentationCompositorFrame(
(viz_breakdown.presentation_feedback.timestamp -
viz_breakdown.swap_timings.swap_end)
.InMicroseconds());
break;
default:
NOTREACHED();
break;
}
}
// Record the active trackers
for (size_t type = 0; type < active_trackers.size(); ++type) {
if (!active_trackers.test(type))
continue;
const auto frame_sequence_tracker_type =
static_cast<FrameSequenceTrackerType>(type);
switch (frame_sequence_tracker_type) {
#define CASE_FOR_TRACKER(name) \
case FrameSequenceTrackerType::k##name: \
builder.Set##name(true); \
break;
CASE_FOR_TRACKER(CompositorAnimation);
CASE_FOR_TRACKER(MainThreadAnimation);
CASE_FOR_TRACKER(PinchZoom);
CASE_FOR_TRACKER(RAF);
CASE_FOR_TRACKER(ScrollbarScroll);
CASE_FOR_TRACKER(TouchScroll);
CASE_FOR_TRACKER(Video);
CASE_FOR_TRACKER(WheelScroll);
CASE_FOR_TRACKER(CanvasAnimation);
CASE_FOR_TRACKER(JSAnimation);
#undef CASE_FOR_TRACKER
default:
NOTREACHED();
break;
}
}
builder.Record(recorder_.get());
}
void UkmManager::RecordEventLatencyUKM(
const EventMetrics::List& events_metrics,
const std::vector<CompositorFrameReporter::StageData>& stage_history,
const viz::FrameTimingDetails& viz_breakdown) const {
using StageType = CompositorFrameReporter::StageType;
for (const auto& event_metrics : events_metrics) {
ukm::builders::Graphics_Smoothness_EventLatency builder(source_id_);
builder.SetEventType(static_cast<int64_t>(event_metrics->type()));
if (event_metrics->scroll_type()) {
builder.SetScrollInputType(
static_cast<int64_t>(*event_metrics->scroll_type()));
if (!viz_breakdown.swap_timings.is_null()) {
builder.SetTotalLatencyToSwapBegin(
(viz_breakdown.swap_timings.swap_start -
event_metrics->time_stamp())
.InMicroseconds());
}
}
// It is possible for an event to arrive in the compositor in the middle of
// a frame (e.g. the browser received the event *after* renderer received a
// begin-impl, and the event reached the compositor before that frame
// ended). To handle such cases, find the first stage that happens after the
// event's arrival in the browser.
auto stage_it = std::find_if(
stage_history.begin(), stage_history.end(),
[&event_metrics](const CompositorFrameReporter::StageData& stage) {
return stage.start_time > event_metrics->time_stamp();
});
// TODO(crbug.com/1079116): Ideally, at least the start time of
// SubmitCompositorFrameToPresentationCompositorFrame stage should be
// greater than the event time stamp, but apparently, this is not always the
// case (see crbug.com/1093698). For now, skip to the next event in such
// cases. Hopefully, the work to reduce discrepancies between the new
// EventLatency and the old Event.Latency metrics would fix this issue. If
// not, we need to reconsider investigating this issue.
if (stage_it == stage_history.end())
continue;
builder.SetBrowserToRendererCompositor(
(stage_it->start_time - event_metrics->time_stamp()).InMicroseconds());
for (; stage_it != stage_history.end(); ++stage_it) {
// Total latency is calculated since the event timestamp.
const base::TimeTicks start_time =
stage_it->stage_type == StageType::kTotalLatency
? event_metrics->time_stamp()
: stage_it->start_time;
switch (stage_it->stage_type) {
#define CASE_FOR_STAGE(name) \
case StageType::k##name: \
builder.Set##name((stage_it->end_time - start_time).InMicroseconds()); \
break;
CASE_FOR_STAGE(BeginImplFrameToSendBeginMainFrame);
CASE_FOR_STAGE(SendBeginMainFrameToCommit);
CASE_FOR_STAGE(Commit);
CASE_FOR_STAGE(EndCommitToActivation);
CASE_FOR_STAGE(Activation);
CASE_FOR_STAGE(EndActivateToSubmitCompositorFrame);
CASE_FOR_STAGE(SubmitCompositorFrameToPresentationCompositorFrame);
CASE_FOR_STAGE(TotalLatency);
#undef CASE_FOR_STAGE
default:
NOTREACHED();
break;
}
}
builder.Record(recorder_.get());
}
}
} // namespace cc
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
28c0b5cf4e30a19d80ebbd7a2353070951a558a5 | e4b596b8a84c8b486b6b9f9e7651d6975acee195 | /test/std/numerics/numeric.ops/numeric.ops.midpoint/midpoint.pointer.pass.cpp | def76084835b0be32d6f34cf51b570cbe69af5e7 | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0"
] | permissive | apple/swift-libcxx | d82de71cb3995135915dd98fc1c6b8727070a692 | 67f490a99c007a333b6395f7499808c1279e5d32 | refs/heads/stable | 2023-03-16T10:52:36.522814 | 2019-10-25T22:47:30 | 2019-10-25T22:47:30 | 159,257,562 | 23 | 20 | Apache-2.0 | 2019-10-25T22:47:31 | 2018-11-27T01:32:35 | C++ | UTF-8 | C++ | false | false | 2,811 | cpp | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: c++98, c++03, c++11, c++14, c++17
// <numeric>
// template <class _Tp>
// _Tp* midpoint(_Tp* __a, _Tp* __b) noexcept
//
#include <numeric>
#include <cassert>
#include "test_macros.h"
template <typename T>
constexpr void constexpr_test()
{
constexpr T array[1000] = {};
ASSERT_SAME_TYPE(decltype(std::midpoint(array, array)), const T*);
ASSERT_NOEXCEPT( std::midpoint(array, array));
static_assert(std::midpoint(array, array) == array, "");
static_assert(std::midpoint(array, array + 1000) == array + 500, "");
static_assert(std::midpoint(array, array + 9) == array + 4, "");
static_assert(std::midpoint(array, array + 10) == array + 5, "");
static_assert(std::midpoint(array, array + 11) == array + 5, "");
static_assert(std::midpoint(array + 9, array) == array + 5, "");
static_assert(std::midpoint(array + 10, array) == array + 5, "");
static_assert(std::midpoint(array + 11, array) == array + 6, "");
}
template <typename T>
void runtime_test()
{
T array[1000] = {}; // we need an array to make valid pointers
ASSERT_SAME_TYPE(decltype(std::midpoint(array, array)), T*);
ASSERT_NOEXCEPT( std::midpoint(array, array));
assert(std::midpoint(array, array) == array);
assert(std::midpoint(array, array + 1000) == array + 500);
assert(std::midpoint(array, array + 9) == array + 4);
assert(std::midpoint(array, array + 10) == array + 5);
assert(std::midpoint(array, array + 11) == array + 5);
assert(std::midpoint(array + 9, array) == array + 5);
assert(std::midpoint(array + 10, array) == array + 5);
assert(std::midpoint(array + 11, array) == array + 6);
}
template <typename T>
void pointer_test()
{
runtime_test< T>();
runtime_test<const T>();
runtime_test< volatile T>();
runtime_test<const volatile T>();
// The constexpr tests are always const, but we can test them anyway.
constexpr_test< T>();
constexpr_test<const T>();
// GCC 9.0.1 (unreleased as of 2019-03) barfs on this, but we have a bot for it.
// Uncomment when gcc 9.1 is released
#ifndef TEST_COMPILER_GCC
constexpr_test< volatile T>();
constexpr_test<const volatile T>();
#endif
}
int main(int, char**)
{
pointer_test<char>();
pointer_test<int>();
pointer_test<double>();
return 0;
}
| [
"mclow.lists@gmail.com"
] | mclow.lists@gmail.com |
ad2b3ac322d712e65b9a386396bb7583b8e6f3ba | 22af93db463774bfa5810ccc26193d91354849b9 | /3rd/flash_sdk_src/core/graphics/fla_transToImage.cpp | 3cb3709d41c68cd9c10e84c3f8d5223f36052d92 | [] | no_license | adroitly/boom | f5ba38c1360e315cfc79a602ca787208f244b87c | 57bb7f29ba2da552e7d47ac5d2dd9691539ad78e | refs/heads/master | 2016-08-12T07:41:34.105425 | 2016-03-08T07:16:13 | 2016-03-08T07:16:13 | 53,380,550 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,307 | cpp | //=============================================================================
// FlashFire
//
// Copyright (C) 2015 PatGame. All rights reserved.
//
// Created by HJC
//
//=============================================================================
#include "fla_transToImage.h"
#include "../definition/fla_DefinitionUtils.h"
#include "../base/fla_ColorTransform.h"
#include "../base/fla_utils.h"
#include "../platform/fla_PlatformTraits.h"
#include "fla_RenderOfDefinition.h"
namespace fla
{
Image::Ptr Definition_transToImage(const Definition& definition, PixelFormat pixelFormat, float scale)
{
auto rt = adjustRectForRender(definition.getBounds(), scale);
PlatformTraits::BitmapGraphics bitmapGraphics(rt.width, rt.height, pixelFormat);
bitmapGraphics.flipAndScale(scale);
// 设置缩放比例,和位置调整
bitmapGraphics.translateCTM(-rt.x, -rt.y);
RenderOfDefinition<PlatformTraits::Graphics> renderVisitor(bitmapGraphics, ColorTransform::identity());
definition.accept(renderVisitor);
return bitmapGraphics.createImage();
}
void Definition_render(const Definition& definition, PlatformTraits::Graphics& graphics, const Size& size)
{
Rect rt = definition.getBounds();
auto scale = std::min(size.width / rt.width, size.height / rt.height);
Point offset;
offset.x = (size.width - rt.width * scale) * 0.5;
offset.y = (size.height - rt.height * scale) * 0.5;
graphics.clipToRect(Rect(offset.x, offset.y, rt.width * scale, rt.height * scale));
graphics.translateCTM(offset.x, offset.y);
graphics.scaleCTM(scale, scale);
// 设置缩放比例,和位置调整
graphics.translateCTM(-rt.x, -rt.y);
RenderOfDefinition<PlatformTraits::Graphics> renderVisitor(graphics, ColorTransform::identity());
definition.accept(renderVisitor);
}
Image::Ptr Definition_transToImage(const Definition& definition, PixelFormat pixelFormat, const Size& size)
{
PlatformTraits::BitmapGraphics bitmapGraphics(size.width, size.height, pixelFormat);
bitmapGraphics.flipAndScale(1.0);
Definition_render(definition, bitmapGraphics, size);
return bitmapGraphics.createImage();
}
}
| [
"adroitly@163.com"
] | adroitly@163.com |
51701841b9ad3dbeffc5689453edc22f2528d803 | 38e8b77a3aa96999965777a55142174f19fe4247 | /deflation_Synthetic.cpp | 92e7c95c364f473a36da3930164f93e773b091af | [] | no_license | shabnajL/Numeric-Methods | 0770e11b0d483331180ca9876fea98ecd556cc41 | 9241fd39c00520af9bb9947e2f27ab4b9dfdde04 | refs/heads/master | 2023-07-08T16:23:15.524679 | 2023-06-24T16:51:19 | 2023-06-24T16:51:19 | 245,870,584 | 0 | 0 | null | 2023-06-24T16:51:20 | 2020-03-08T18:57:50 | C++ | UTF-8 | C++ | false | false | 1,635 | cpp | #include<bits/stdc++.h>
using namespace std;
void writeQ(int n,int b[]) //this function is just to show the equation Q(x)
{
printf("\nQ(x) : ");
for(int i=n-1; i>=0; i--)
{
if(b[i]!=0)
{
if(i==n-1)
{
printf("%dX^%d ",b[i],i);
}
else if(i==0)
{
if(b[i]>0)
{
printf("+");
}
printf("%d ",b[i]);
}
else if(i==1)
{
if(b[i]>0)
{
printf("+");
}
printf("%dX ",b[i]);
}
else
{
if(b[i]>0)
{
printf("+");
}
printf("%dX^%d ",b[i],i);
}
}
}
printf("= 0\n\n");
}
int main()
{
int n,x,a[105],b[105];
int T;
cin>>T;
while(T--)
{
printf("Enter N : ");
cin>>n;
printf("\n");
for(int i=n; i>=0; i--)
{
printf("Enter A[%d] : ",i);
cin>>a[i];
}
printf("\nEnter X : ");
cin>>x;
b[n] = 0;
printf("\nB[%d] = %d\n",n,b[n]);
for(int i=n-1; i>=0; i--)
{
b[i] = (a[i+1] + (b[i+1] * x));
printf("B[%d] = %d\n",i,b[i]);
}
writeQ(n,b); //showing the equation Q(x)
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
}
return 0;
}
| [
"noreply@github.com"
] | shabnajL.noreply@github.com |
21c81415639ffc62519e9609474d63c55fe2cc4b | e1522f45a46820f6ddbfcc699379821e7eb660af | /codeforces.com/Codeforces Ladder 1600-1699/0363C.cpp | 55205e004134fb2b2c8c7c6d69736afb86d9b8fd | [] | no_license | dmkz/competitive-programming | 1b8afa76eefbdfd9d5766d5347e99b1bfc50761b | 8d02a5db78301cf34f5fdffd3fdf399c062961cb | refs/heads/master | 2023-08-21T00:09:21.754596 | 2023-08-13T13:21:48 | 2023-08-13T13:21:48 | 130,999,150 | 21 | 12 | null | 2023-02-16T17:43:53 | 2018-04-25T11:54:48 | C++ | UTF-8 | C++ | false | false | 1,184 | cpp | /*
Problem: 363C. Fixing Typos
Solution: strings, greedy, implementation, O(n)
Author: Dmitry Kozyrev, github: dmkz, e-mail: dmkozyrev@rambler.ru
*/
#include <iostream>
#include <string>
#include <vector>
struct Pair { char item; int count; };
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(0); std::cout.tie(0); std::cerr.tie(0);
std::string s;
while (std::cin >> s) {
std::vector<Pair> arr{Pair{s[0], 0}};
for (auto& it : s) {
if (it == arr.back().item) {
arr.back().count++;
} else {
arr.push_back(Pair{it, 1});
}
}
for (int i = 0; i < (int)arr.size(); ++i) {
auto& curr = arr[i];
curr.count = std::min(curr.count, 2);
if (i > 0 && curr.count == 2) {
const auto& prev = arr[i-1];
if (prev.count == 2) {
curr.count = 1;
}
}
}
s.clear();
for (const auto& it : arr) {
s += std::string(it.count, it.item);
}
std::cout << s << std::endl;
}
return 0;
} | [
"dmkozyrev@rambler.ru"
] | dmkozyrev@rambler.ru |
333d22c28abdb02c905799693ca51d965cb505ec | 3e4f11467f3aa3b0b5439ea052db0024c590924e | /src/freetypelib.h | 4b86fb50385333cd89bde4c231dc20fc28a9d06c | [
"MIT"
] | permissive | if1live/harfbuzz-example | 5ae799352eb580ad1aaffa315348ec32dcd9e435 | 84bdfd47567d0dad5df6295ad84a8bf74a87e355 | refs/heads/master | 2021-01-15T20:33:44.528264 | 2016-02-01T08:09:55 | 2016-02-01T08:09:55 | 50,823,893 | 1 | 0 | null | 2016-02-01T07:58:29 | 2016-02-01T07:58:29 | null | UTF-8 | C++ | false | false | 610 | h | #pragma once
#include <ft2build.h>
#include FT_FREETYPE_H
#include <iostream>
#include <cassert>
#include <cmath>
using namespace std;
typedef struct {
unsigned char* buffer;
unsigned int width;
unsigned int height;
float bearing_x;
float bearing_y;
} Glyph;
class FreeTypeLib {
public:
FreeTypeLib();
~FreeTypeLib();
FT_Face* loadFace(const string& fontName, int ptSize, int deviceHDPI, int deviceVDPI);
void freeFace(FT_Face* face);
Glyph* rasterize(FT_Face* face, uint32_t glyphIndex) const;
void freeGlyph(Glyph* glyph);
private:
FT_Library lib;
int force_ucs2_charmap(FT_Face ftf);
};
| [
"karim.naaji@gmail.com"
] | karim.naaji@gmail.com |
fce24bafdc4cc79c8e2b27830f4c334705fa8c65 | 200d924e3a24343f057919cb46b39516c3b228cd | /src/app/AttributeAccessInterface.cpp | e9ca4325b1f3d267d28e00209ace516bd320f928 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ARMmbed/connectedhomeip | 4a992fb91019eb4106ced03944d2669fd735d697 | 81310d6b73c5d3415c9f76972698a9c3185c127e | refs/heads/master | 2023-03-11T03:49:03.271328 | 2022-08-26T13:54:13 | 2022-08-26T13:54:13 | 330,608,139 | 10 | 9 | Apache-2.0 | 2023-03-06T16:05:41 | 2021-01-18T08:57:27 | C++ | UTF-8 | C++ | false | false | 4,200 | cpp | /*
*
* Copyright (c) 2021 Project CHIP 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 <app/AttributeAccessInterface.h>
namespace chip {
namespace app {
CHIP_ERROR AttributeReportBuilder::PrepareAttribute(AttributeReportIBs::Builder & aAttributeReportIBsBuilder,
const ConcreteDataAttributePath & aPath, DataVersion aDataVersion)
{
AttributeReportIB::Builder & attributeReportIBBuilder = aAttributeReportIBsBuilder.CreateAttributeReport();
ReturnErrorOnFailure(aAttributeReportIBsBuilder.GetError());
AttributeDataIB::Builder & attributeDataIBBuilder = attributeReportIBBuilder.CreateAttributeData();
ReturnErrorOnFailure(attributeReportIBBuilder.GetError());
attributeDataIBBuilder.DataVersion(aDataVersion);
AttributePathIB::Builder & attributePathIBBuilder = attributeDataIBBuilder.CreatePath();
ReturnErrorOnFailure(attributeDataIBBuilder.GetError());
attributePathIBBuilder.Endpoint(aPath.mEndpointId).Cluster(aPath.mClusterId).Attribute(aPath.mAttributeId);
if (aPath.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem)
{
// An append to a list (or a data chunk consisting just one list entry that's part of a bigger list) is represented by a
// null list index in the path.
attributePathIBBuilder.ListIndex(DataModel::Nullable<ListIndex>());
}
ReturnErrorOnFailure(attributePathIBBuilder.EndOfAttributePathIB().GetError());
return attributeDataIBBuilder.GetError();
}
CHIP_ERROR AttributeReportBuilder::FinishAttribute(AttributeReportIBs::Builder & aAttributeReportIBsBuilder)
{
ReturnErrorOnFailure(aAttributeReportIBsBuilder.GetAttributeReport().GetAttributeData().EndOfAttributeDataIB().GetError());
return aAttributeReportIBsBuilder.GetAttributeReport().EndOfAttributeReportIB().GetError();
}
CHIP_ERROR AttributeValueEncoder::EnsureListStarted()
{
if (mCurrentEncodingListIndex == kInvalidListIndex)
{
if (mEncodeState.mCurrentEncodingListIndex == kInvalidListIndex)
{
// Clear mAllowPartialData flag here since this encode procedure is not atomic.
// The most common error in this function is CHIP_ERROR_NO_MEMORY / CHIP_ERROR_BUFFER_TOO_SMALL, just revert and try
// next time is ok.
mEncodeState.mAllowPartialData = false;
// Spec 10.5.4.3.1, 10.5.4.6 (Replace a list w/ Multiple IBs)
// Put an empty array before encoding the first array element for list chunking.
AttributeReportBuilder builder;
mPath.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll;
ReturnErrorOnFailure(builder.PrepareAttribute(mAttributeReportIBsBuilder, mPath, mDataVersion));
ReturnErrorOnFailure(builder.EncodeValue(mAttributeReportIBsBuilder, DataModel::List<uint8_t>()));
ReturnErrorOnFailure(builder.FinishAttribute(mAttributeReportIBsBuilder));
mEncodeState.mCurrentEncodingListIndex = 0;
}
mCurrentEncodingListIndex = 0;
}
// After encoding the empty list, the remaining items are atomically encoded into the buffer. Tell report engine to not
// revert partial data.
mEncodeState.mAllowPartialData = true;
// For all elements in the list, a report with append operation will be generated. This will not be changed during encoding
// of each report since the users cannot access mPath.
mPath.mListOp = ConcreteDataAttributePath::ListOperation::AppendItem;
return CHIP_NO_ERROR;
}
} // namespace app
} // namespace chip
| [
"noreply@github.com"
] | ARMmbed.noreply@github.com |
cf523c557bfa8886ed6a31dd931ea92f9e009b24 | f15413586e7aaa664fca4d8c9b5b855c2079ca5c | /A_Neopixel/A_Neopixel.ino | d3cea135707bd829b57b34408293974442143841 | [] | no_license | Mantve/Neopixel-Compilation | 26415bbf8024aaf57324b01f15071725cadc5906 | 7a73f3b15ac07a608a2974e7764e901fd6f1643e | refs/heads/master | 2022-11-15T08:21:18.715878 | 2020-07-15T22:17:35 | 2020-07-15T22:17:35 | 269,668,321 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 163 | ino | /*
* Don't forget to plug in the ground wire first!
*
* Compilation of Neopixel based animations
* Includes mode and color changing with hardware buttons
*/
| [
"mantvydasri99@gmail.com"
] | mantvydasri99@gmail.com |
e24d1a4195d1e40ea067c48d5f12ac478b4904dc | c8944016308a0049becaee8567a08328389ac9cd | /climbot5d/src/test/kine_test.cpp | cc8fa4d74bc37387156427fe17eb24a03f12ca4e | [] | no_license | Jiongyu/birl-module-robot-1.0 | 75cb4c66afcb3dec28daddef0c6dc6b32306e40a | d0be500d47bf8de3dab0101807a4ddc5695c28c9 | refs/heads/master | 2020-06-19T19:47:14.521984 | 2019-10-24T01:55:22 | 2019-10-24T01:55:22 | 196,848,066 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,586 | cpp | #include "./../kinematics/Kine.h"
#include "ros/ros.h"
#include "std_msgs/Int64MultiArray.h"
int main(int argc, char **argv)
{
void Current_joint_Rad_to_Deg(double (&joint_value)[5]);
double New_joint_value[5];//unit:degree
double Robot_Link_Len[6] = {0.1764,0.2568,0.2932,0.2932,0.2568,0.1764}; //robot link length
Kine_CR_FiveDoF_G1 Climbot_G1; // robot based on the gripper1 to get inverse solution
Kine_CR_FiveDoF_G2 Climbot_G2; // robot based on the gripper6 to get inverse solution
Climbot_G1.Set_Length(Robot_Link_Len);
Climbot_G2.Set_Length(Robot_Link_Len);
double Current_joint_value[5] = {0,0,0,0,0}; //unit:degree
double New_point[6]; //new cartesian point (xyzwpr(RxRyRz)) unit:(meter,degree)
///end
double Top_point[6];
Climbot_G1.FKine(Current_joint_value,Top_point);
for(int i = 0; i < 6; i++){
std::cout<<Top_point[i]<<std::endl;
}
std::cout<<"-------------------------------------"<<std::endl;
Climbot_G2.FKine(Current_joint_value,Top_point);
for(int i = 0; i < 6; i++){
std::cout<<Top_point[i]<<std::endl;
}
std::cout<<"-----------inversion position--------------------------"<<std::endl;
New_point[0] = 0.57;
New_point[1] = 0;
New_point[2] = 0;
New_point[3] = 0;
New_point[4] = 0;
New_point[5] = 180;
// Current_joint_Rad_to_Deg(Current_joint_value);
Climbot_G1.IKine(New_point,Current_joint_value,New_joint_value);
for(int i = 0; i < 5; i++){
std::cout<<New_joint_value[i]<<std::endl;
}
double current_top_velocity[6] = {-0.06,0,0,0,0,0}; // m/s,degree/s
double new_joint_velocity[5] = {0,0,0,0,0}; // degree/s
std::cout<<"velocity_inverse-----------------------------"<<std::endl;
Climbot_G1.Vel_IKine(New_joint_value,current_top_velocity,new_joint_velocity);
for(int i = 0; i < 5; i++){
std::cout<<new_joint_velocity[i]<<std::endl;
}
std::cout<<"velocity_positive-----------------------------"<<std::endl;
new_joint_velocity[0] = 0;
new_joint_velocity[1] = 8.32102;
new_joint_velocity[2] = -16.642;
new_joint_velocity[3] = 8.32102;
new_joint_velocity[4] = 0;
Climbot_G1.Vel_FKine(New_joint_value,new_joint_velocity,current_top_velocity);
for(int i = 0; i < 6; i++){
std::cout<<current_top_velocity[i]<<std::endl;
}
return 0;
}
void Current_joint_Rad_to_Deg(double (&joint_value)[5]){
joint_value[0]*=PI_DEG;
joint_value[1]*=PI_DEG;
joint_value[2]*=PI_DEG;
joint_value[3]*=PI_DEG;
joint_value[4]*=PI_DEG;
} | [
"35024339@qq.com"
] | 35024339@qq.com |
361ce8a085426136eb4de308bf776d21b4d3ee1f | 1593b8975b5ac78c9e00d199aa0bf3c2de40f155 | /gazebo/common/ColladaLoader_TEST.cc | 16eef80dd466e0076a0985554309b89629711ca7 | [
"Apache-2.0"
] | permissive | kesaribath47/gazebo-deb | 3e0da13ec54f33cc8036623bb8bba2d4a4f46150 | 456da84cfb7b0bdac53241f6c4e86ffe1becfa7d | refs/heads/master | 2021-01-22T23:15:52.075857 | 2013-07-12T18:22:26 | 2013-07-12T18:22:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,661 | cc | /*
* Copyright 2013 Open Source Robotics Foundation
*
* 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 <gtest/gtest.h>
#include "test_config.h"
#include "gazebo/common/Mesh.hh"
#include "gazebo/common/ColladaLoader.hh"
using namespace gazebo;
/////////////////////////////////////////////////
TEST(ColladaLoader, LoadBox)
{
common::ColladaLoader loader;
common::Mesh *mesh = loader.Load(
std::string(PROJECT_SOURCE_PATH) + "/test/data/box.dae");
EXPECT_STREQ("unknown", mesh->GetName().c_str());
EXPECT_EQ(math::Vector3(1, 1, 1), mesh->GetMax());
EXPECT_EQ(math::Vector3(-1, -1, -1), mesh->GetMin());
EXPECT_EQ(36u, mesh->GetVertexCount());
EXPECT_EQ(36u, mesh->GetNormalCount());
EXPECT_EQ(36u, mesh->GetIndexCount());
EXPECT_EQ(0u, mesh->GetTexCoordCount());
EXPECT_EQ(1u, mesh->GetSubMeshCount());
EXPECT_EQ(1u, mesh->GetMaterialCount());
// Make sure we can read a submesh name
EXPECT_STREQ("Cube", mesh->GetSubMesh(0)->GetName().c_str());
}
/////////////////////////////////////////////////
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"thomas.moulard@gmail.com"
] | thomas.moulard@gmail.com |
21bbe264f860da3da9e207276ddbaef1cf957294 | 7a8635c9e1f6664cf5f6b10b8708d5bc70c609d4 | /battery_parametres.h | 5918532296161ae5aba67a3b969cbebbf8d377d5 | [] | no_license | EgorSidorov/Run_tracker | d6a20c0c66e303eca06e9fcaf8556e2d4ee31404 | ceb1d4bd4a7f7c1deb23429d4f8c3b3a6e4bf9a3 | refs/heads/master | 2020-03-26T02:31:09.396269 | 2019-01-27T18:04:24 | 2019-01-27T18:04:24 | 144,413,922 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | h | #ifndef BATTERY_PARAMETRES_H
#define BATTERY_PARAMETRES_H
#include <QObject>
#if defined(Q_OS_ANDROID)
#include <QtAndroidExtras/QAndroidJniObject>
#endif
class battery_parametres : public QObject
{
Q_OBJECT
public:
explicit battery_parametres(QObject *parent = nullptr);
Q_INVOKABLE void set_battery_ignore();
Q_INVOKABLE QString get_battery_parametres();
Q_INVOKABLE void release_battery_ignore();
signals:
public slots:
private:
QAndroidJniObject main_activity;
};
#endif // BATTERY_PARAMETRES_H
| [
"sega-96@mail.ru"
] | sega-96@mail.ru |
ab71c18276c4425e677b8c72f37c445b6da9adfc | 5515d24784c2505a9b0c2f743a6d8656e8c35b03 | /code/c++/349.两个数组的交集.cpp | 35ffd4f990233378b664d1913c59df6a77e3d0b3 | [] | no_license | wangcy6/leetcode | 0eb160afb0bcfb9fa3f542b1a96670c4a16c9cb0 | a4129ac84419cdd6c38c12a70154f7043a4ec50a | refs/heads/master | 2021-06-09T19:06:38.215155 | 2021-04-12T07:58:52 | 2021-04-12T07:58:52 | 164,075,525 | 5 | 1 | null | 2020-10-13T23:29:05 | 2019-01-04T07:45:48 | C++ | UTF-8 | C++ | false | false | 1,687 | cpp | /*
* @lc app=leetcode.cn id=349 lang=cpp
*
* [349] 两个数组的交集
*
* https://leetcode-cn.com/problems/intersection-of-two-arrays/description/
*
* algorithms
* Easy (69.49%)
* Likes: 212
* Dislikes: 0
* Total Accepted: 82.9K
* Total Submissions: 118.2K
* Testcase Example: '[1,2,2,1]\n[2,2]'
*
* 给定两个数组,编写一个函数来计算它们的交集。
*
*
*
* 示例 1:
*
* 输入:nums1 = [1,2,2,1], nums2 = [2,2]
* 输出:[2]
*
*
* 示例 2:
*
* 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
* 输出:[9,4]
*
*
*
* 说明:
*
*
* 输出结果中的每个元素一定是唯一的。
* 我们可以不考虑输出结果的顺序。
*
* 上来一看就梦了,心慌 然后感觉不太好
* 但是我还是标准算法分析去思考这个题目,get it
*
*/
// @lc code=start
class Solution
{
public:
vector<int> intersection(vector<int> &nums1, vector<int> &nums2)
{
vector<int> res;
map<int, int> hash;
//for循环遍历
for (int i = 0; i < nums1.size(); i++)
{
for (int j = 0; j < nums2.size(); j++)
{
//判断是否相等
if (nums1[i] == nums2[j])
{
if (hash.count(nums1[i]) == 1)
{
//有重复
}
else
{
res.push_back(nums1[i]);
hash[nums1[i]] = nums1[i];
}
break;
}
}
}
return res;
}
};
// @lc code=end
| [
"wang_cyi@163.com"
] | wang_cyi@163.com |
0b495fc9d47e41580231aca51546d7875d2b8fb6 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_573_collectd-4.3.3.cpp | b27c4e1eb39ec12bbc59973e95064f3821a4675a | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,506 | cpp | int main (int argc, char **argv)
{
int collectd_argc = 0;
char *collectd = NULL;
char **collectd_argv = NULL;
struct sigaction sa;
int i = 0;
/* parse command line options */
while (42) {
int c = getopt (argc, argv, "hc:P:");
if (-1 == c)
break;
switch (c) {
case 'c':
collectd = optarg;
break;
case 'P':
pidfile = optarg;
break;
case 'h':
default:
exit_usage (argv[0]);
}
}
for (i = optind; i < argc; ++i)
if (0 == strcmp (argv[i], "-f"))
break;
/* i < argc => -f already present */
collectd_argc = 1 + argc - optind + ((i < argc) ? 0 : 1);
collectd_argv = (char **)calloc (collectd_argc + 1, sizeof (char *));
if (NULL == collectd_argv) {
fprintf (stderr, "Out of memory.");
return 3;
}
collectd_argv[0] = (NULL == collectd) ? "collectd" : collectd;
if (i == argc)
collectd_argv[collectd_argc - 1] = "-f";
for (i = optind; i < argc; ++i)
collectd_argv[i - optind + 1] = argv[i];
collectd_argv[collectd_argc] = NULL;
openlog ("collectdmon", LOG_CONS | LOG_PID, LOG_DAEMON);
if (-1 == daemonize ())
return 1;
sa.sa_handler = sig_int_term_handler;
sa.sa_flags = 0;
sigemptyset (&sa.sa_mask);
if (0 != sigaction (SIGINT, &sa, NULL)) {
syslog (LOG_ERR, "Error: sigaction() failed: %s", strerror (errno));
return 1;
}
if (0 != sigaction (SIGTERM, &sa, NULL)) {
syslog (LOG_ERR, "Error: sigaction() failed: %s", strerror (errno));
return 1;
}
sa.sa_handler = sig_hup_handler;
if (0 != sigaction (SIGHUP, &sa, NULL)) {
syslog (LOG_ERR, "Error: sigaction() failed: %s", strerror (errno));
return 1;
}
sigaddset (&sa.sa_mask, SIGCHLD);
if (0 != sigprocmask (SIG_BLOCK, &sa.sa_mask, NULL)) {
syslog (LOG_ERR, "Error: sigprocmask() failed: %s", strerror (errno));
return 1;
}
while (0 == loop) {
int status = 0;
if (0 != collectd_start (collectd_argv)) {
syslog (LOG_ERR, "Error: failed to start collectd.");
break;
}
assert (0 < collectd_pid);
while ((collectd_pid != waitpid (collectd_pid, &status, 0))
&& (EINTR == errno))
if ((0 != loop) || (0 != restart))
collectd_stop ();
collectd_pid = 0;
log_status (status);
check_respawn ();
if (0 != restart) {
syslog (LOG_INFO, "Info: restarting collectd");
restart = 0;
}
else if (0 == loop)
syslog (LOG_WARNING, "Warning: restarting collectd");
}
syslog (LOG_INFO, "Info: shutting down collectdmon");
pidfile_delete ();
closelog ();
free (collectd_argv);
return 0;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
2d8cc961332a1502dc2074be219f10ab878beba7 | 27fa98581735c1cc3dc22514108c630c80aee651 | /ConsoleApplication11/includes.h | db602e2bcc1159f064f22c454f9461114f22a04c | [] | no_license | p41z3/p41z3-test | 6b24ed002181a4f89c0ad1ac3be91d4bd29bd387 | 9c13d5d80f6166aed10a35e9512e3eb622f8a63d | refs/heads/master | 2021-06-16T04:25:22.917011 | 2021-04-07T13:05:39 | 2021-04-07T13:05:39 | 20,646,734 | 0 | 0 | null | 2021-04-07T13:05:39 | 2014-06-09T13:06:23 | C++ | UTF-8 | C++ | false | false | 61 | h | #include <iostream>
using namespace std;
#define MODULE 100 | [
"p42z3@gmail.com"
] | p42z3@gmail.com |
289f30787d165ca9b235f4fb7de455a3a4f40442 | 2124d0b0d00c3038924f5d2ad3fe14b35a1b8644 | /source/GamosCore/GamosScoring/Scorers/include/GmPSDose_LET.hh | 52f9f975fe589acefe74f19fdf2fda4a7b80c607 | [] | no_license | arceciemat/GAMOS | 2f3059e8b0992e217aaf98b8591ef725ad654763 | 7db8bd6d1846733387b6cc946945f0821567662b | refs/heads/master | 2023-07-08T13:31:01.021905 | 2023-06-26T10:57:43 | 2023-06-26T10:57:43 | 21,818,258 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | hh |
#ifndef GmPSDose_LET_h
#define GmPSDose_LET_h 1
#include "GamosCore/GamosScoring/Management/include/GmVPrimitiveScorer.hh"
#include "G4THitsMap.hh"
////////////////////////////////////////////////////////////////////////////////
// Description:
// This is a primitive scorer class for scoring energy deposit.
//
///////////////////////////////////////////////////////////////////////////////
class GmPSDose_LET : public GmVPrimitiveScorer
{
public: // with description
GmPSDose_LET(G4String name);
virtual ~GmPSDose_LET();
protected: // with description
virtual G4bool ProcessHits(G4Step*,G4TouchableHistory*);
private:
};
#endif
| [
"pedro.arce@ciemat.es"
] | pedro.arce@ciemat.es |
3de4897aaaea5062a6db32ddd73ec2086d42aea2 | adedc60b13c8e0538f4add6323084ec672b649bd | /corso01/sketch45/sketch45.ino | 096ae59072c4ce2f5ebecf1efe6403a412d2885c | [] | no_license | radiojam11/LezioniArduino | ed955d9bcbfa8d5b74876c519ebf4c235fe47140 | 13b771bf18bad7c31d35fd6178f04b2f678f30bb | refs/heads/master | 2020-05-21T18:23:47.887654 | 2015-06-25T18:28:09 | 2015-06-25T18:28:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,651 | ino | /* Prof. Michele Maffucci
19.04.2014
Utilizzo del ponte H L293D
per pilotare da tastiers il senso
di rotazione di un motore in CC
Collegamenti
L293D > Arduino
pin 1 - pin 9 - pin 16: +Vcc
pin 2: pin 4 Arduino
pin 3: motore
pin 4 - pin 5 - pin 12 - pin 13: GND
pin 6: motore
pin 7: 4 Arduino
pin 8: Vin Arduino
*/
// Pin di input del ponte H
const int pinIngresso1 = 5; // collegato al pin 3 dell'L293D
const int pinIngresso2 = 4; // collegato al pin 6 dell'L293D
void setup()
{
Serial.begin(9600); // inizializzazione della porta seriale
pinMode(pinIngresso1, OUTPUT); // pin di controllo senso di rotazione
pinMode(pinIngresso2, OUTPUT); // pin di controllo senso di rotazione
Serial.println("1 - 2 impostano la direzione, qualsiasi altro pulsante ferma il motore");
Serial.println("----------------------------------------------------------------------");
}
void loop()
{
if ( Serial.available()) { // verifica disponibilia' di un carattere sulla serial
char ch = Serial.read(); // legge il carattere inserito
if (ch == '1') // rotazione oraria
{
Serial.println("Rotazione oraria");
digitalWrite(pinIngresso1,LOW);
digitalWrite(pinIngresso2,HIGH);
}
else if (ch == '2') // rotazione antioraria
{
Serial.println("Rotazione antioraria");
digitalWrite(pinIngresso1,HIGH);
digitalWrite(pinIngresso2,LOW);
}
else
{
Serial.println("Motore fermo"); // ferma il motore
digitalWrite(pinIngresso1,LOW);
digitalWrite(pinIngresso2,LOW);
}
}
}
| [
"michele@maffucci.it"
] | michele@maffucci.it |
dbcbfed221617b1a2e3b45a19cd123974eeecac8 | c8d047ce0f40d541a3da75a1e11f1c9f99a11c1d | /src/script/interpreter.h | f2c51d06d1a9a475e8f0b1b7b9d03f9be81348a9 | [
"MIT"
] | permissive | anandsinha095/jdcoin-new | d6e91b459663ab992586fe41a055a50e046a9c71 | f6044406959c81bd1bc9662fa67025e434a72e5c | refs/heads/master | 2023-02-04T05:18:43.249231 | 2020-12-23T20:11:41 | 2020-12-23T20:11:41 | 323,985,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,557 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin developers
// Copyright (c) 2018-2019 The JDCOIN developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_SCRIPT_INTERPRETER_H
#define BITCOIN_SCRIPT_INTERPRETER_H
#include "script_error.h"
#include "primitives/transaction.h"
#include <vector>
#include <stdint.h>
#include <string>
class CPubKey;
class CScript;
class CTransaction;
class uint256;
/** Signature hash types/flags */
enum
{
SIGHASH_ALL = 1,
SIGHASH_NONE = 2,
SIGHASH_SINGLE = 3,
SIGHASH_ANYONECANPAY = 0x80,
};
/** Script verification flags */
enum
{
SCRIPT_VERIFY_NONE = 0,
// Evaluate P2SH subscripts (softfork safe, BIP16).
SCRIPT_VERIFY_P2SH = (1U << 0),
// Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure.
// Evaluating a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) by checksig causes script failure.
// (softfork safe, but not used or intended as a consensus rule).
SCRIPT_VERIFY_STRICTENC = (1U << 1),
// Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP62 rule 1)
SCRIPT_VERIFY_DERSIG = (1U << 2),
// Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure
// (softfork safe, BIP62 rule 5).
SCRIPT_VERIFY_LOW_S = (1U << 3),
// verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7).
SCRIPT_VERIFY_NULLDUMMY = (1U << 4),
// Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2).
SCRIPT_VERIFY_SIGPUSHONLY = (1U << 5),
// Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct
// pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating
// any other push causes the script to fail (BIP62 rule 3).
// In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4).
// (softfork safe)
SCRIPT_VERIFY_MINIMALDATA = (1U << 6),
// Discourage use of NOPs reserved for upgrades (NOP1-10)
//
// Provided so that nodes can avoid accepting or mining transactions
// containing executed NOP's whose meaning may change after a soft-fork,
// thus rendering the script invalid; with this flag set executing
// discouraged NOPs fails the script. This verification flag will never be
// a mandatory flag applied to scripts in a block. NOPs that are not
// executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected.
SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1U << 7),
// Require that only a single stack element remains after evaluation. This changes the success criterion from
// "At least one stack element must remain, and when interpreted as a boolean, it must be true" to
// "Exactly one stack element must remain, and when interpreted as a boolean, it must be true".
// (softfork safe, BIP62 rule 6)
// Note: CLEANSTACK should never be used without P2SH.
SCRIPT_VERIFY_CLEANSTACK = (1U << 8),
// Verify CHECKLOCKTIMEVERIFY
//
// See BIP65 for details.
SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9)
};
bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror);
uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
class BaseSignatureChecker
{
public:
virtual bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode) const
{
return false;
}
virtual bool CheckLockTime(const CScriptNum& nLockTime) const
{
return false;
}
virtual bool CheckColdStake(const CScript& script) const
{
return false;
}
virtual ~BaseSignatureChecker() {}
};
class TransactionSignatureChecker : public BaseSignatureChecker
{
private:
const CTransaction* txTo;
unsigned int nIn;
protected:
virtual bool VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const;
public:
TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn) : txTo(txToIn), nIn(nInIn) {}
bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode) const override;
bool CheckLockTime(const CScriptNum& nLockTime) const override;
bool CheckColdStake(const CScript& script) const override {
return txTo->CheckColdStake(script);
}
};
class MutableTransactionSignatureChecker : public TransactionSignatureChecker
{
private:
const CTransaction txTo;
public:
MutableTransactionSignatureChecker(const CMutableTransaction* txToIn, unsigned int nInIn) : TransactionSignatureChecker(&txTo, nInIn), txTo(*txToIn) {}
};
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* error = NULL);
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* error = NULL);
#endif // BITCOIN_SCRIPT_INTERPRETER_H
| [
"anandsinha095@gmail.com"
] | anandsinha095@gmail.com |
87cefa7f82f334ce46ea0e0fa18c086b248caba8 | 2ed839500f7c31f518beb433cdc7d21de6d4789b | /Game/texture.cpp | 11c4c9c4acad7197e347d1337503cd5b679e9afb | [] | no_license | NEUGWB/Game | 585d560c399c0a6938c9d697c258833aaabc558a | a55a0ca4d3ee225de6957eb9e1cadbe1bd9ad388 | refs/heads/main | 2023-03-05T17:39:10.481202 | 2021-02-17T15:57:27 | 2021-02-17T15:57:27 | 335,865,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,572 | cpp | /*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#include <iostream>
#include "texture.h"
Texture2D::Texture2D()
: Width(0), Height(0), Internal_Format(GL_RGB), Image_Format(GL_RGB), Wrap_S(GL_REPEAT), Wrap_T(GL_REPEAT), Filter_Min(GL_LINEAR), Filter_Max(GL_LINEAR)
{
glGenTextures(1, &this->ID);
}
Texture2D::~Texture2D()
{
//glDeleteTextures(1, &this->ID);
}
void Texture2D::Generate(unsigned int width, unsigned int height, unsigned char* data)
{
this->Width = width;
this->Height = height;
// create Texture
glBindTexture(GL_TEXTURE_2D, this->ID);
glTexImage2D(GL_TEXTURE_2D, 0, this->Internal_Format, width, height, 0, this->Image_Format, GL_UNSIGNED_BYTE, data);
// set Texture wrap and filter modes
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, this->Wrap_S);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, this->Wrap_T);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, this->Filter_Min);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, this->Filter_Max);
// unbind texture
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture2D::Bind() const
{
glBindTexture(GL_TEXTURE_2D, this->ID);
} | [
"850609901@qq.com"
] | 850609901@qq.com |
b484f913a47b747e5ebef10a13c1df2f4149879f | f72e694bb2df5abd070e8b33f130536b6ac605f6 | /src/phonetics.hpp | de83ddc7d1915960853fcb544b5fb9379b83d7b2 | [] | no_license | MubashirAli11/STT | 17b51eb49f4ded55e2a2e8d9bc60ca4f7a10c57e | 575bee875ec943ec354054b70b4235fdb9b1322d | refs/heads/master | 2020-04-13T12:26:09.120210 | 2018-12-26T17:20:40 | 2018-12-26T17:20:40 | 163,201,854 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 126 | hpp | #ifndef PHONETICS__HPP
#define PHONETICS__HPP
namespace marfix_stt {
class Phonetics {
};
}
#endif // PHONETICS__HPP
| [
"mubashir.ali1@hotmail.com"
] | mubashir.ali1@hotmail.com |
d1f32cc5aae59505e9a8bd203f7a2ff935692b5a | f30f043fa0dd940106d0a6d26cedd1dca6fa89d2 | /1505052/divide_offline_1505052.cpp | 716624b943e0159ac4a14b5fd0e85d7fae58bf9c | [] | no_license | oaishi/CSE-204-Data-Structures-Sessional | 8c10ad3581181a2f41a8c03370ea2a720a964685 | 4e862dc59a25077eff10f90b7b7281fa7fd7756c | refs/heads/master | 2020-12-21T17:28:04.522965 | 2020-01-27T14:11:54 | 2020-01-27T14:11:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,361 | cpp | #include<cstdio>
#include<iostream>
using namespace std;
int smally ;
typedef struct points
{
int x;
int y;
} p;
p L[3000], R[3000];
void skyline(p values[], int l, int r)
{
for(int i=l; i<=r; i++)
{
if(values[i].y<smally)
{
cout<< values[i].x<<" " <<values[i].y<<endl;
smally=values[i].y;
}
}
}
void printArr(p arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;
printArr(arr, l, m);
printArr(arr, m+1, r );
skyline(arr, l, r);
}
}
void mergeY(p arr[], int l, int m, int r)
{
int i, j, k;
int low = m - l + 1;
int high = r - m;
L[low], R[high];
for (i = 0; i < low ; i++)
{
L[i].x = arr[l + i].x;
L[i].y = arr[l + i].y;
}
for (j = 0; j < high ; j++)
{
R[j].x = arr[m + 1+ j].x;
R[j].y = arr[m + 1+ j].y;
}
i = 0;
j = 0;
k = l;
while (i < low && j < high)
{
if (L[i].x < R[j].x)
{
arr[k].x = L[i].x;
arr[k].y = L[i].y;
i++;
}
else if(L[i].x > R[j].x)
{
arr[k].x = R[j].x;
arr[k].y = R[j].y;
j++;
}
else
{
if (L[i].y <= R[j].y)
{
arr[k].x = L[i].x;
arr[k].y = L[i].y;
i++;
}
else if(L[i].y > R[j].y)
{
arr[k].x = R[j].x;
arr[k].y = R[j].y;
j++;
}
}
k++;
}
while (i < low)
{
arr[k].x = L[i].x;
arr[k].y = L[i].y;
i++;
k++;
}
while (j < high)
{
arr[k].x = R[j].x;
arr[k].y = R[j].y;
j++;
k++;
}
}
void mergeSortY(p arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;
mergeSortY(arr, l, m);
mergeSortY(arr, m+1, r);
mergeY(arr, l, m, r);
}
}
int main()
{
int arr_size, small;
cin>>arr_size;
p values[3000];
for(int i=0; i<arr_size; i++)
{
cin>>values[i].x;
cin>>values[i].y;
}
mergeSortY(values, 0, arr_size - 1);
smally=values[0].y;
smally++;
cout<<"Non-Dominating Points-\n";
printArr(values, 0,arr_size -1);
return 0;
}
| [
"oaishi.faria@gmail.com"
] | oaishi.faria@gmail.com |
0735542d0ca96b5eeccf896dbd5108fb929d91a4 | c8feb0c5dee0935d8696af8e0fe70916ace7d927 | /Assignment1/Includes/Transaction.cpp | 6ea0588e4e06262e8feb093631a7e2b10a17c97e | [] | no_license | WhiteOlivierus/OOPA | 67795dd4e2c37e295c9817cbe76b174839513ecd | 454e083bc21bc37362c8f5924e7e58de6960e1b6 | refs/heads/main | 2023-01-22T10:05:57.454689 | 2020-12-08T14:26:39 | 2020-12-08T14:26:39 | 311,994,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 672 | cpp | #include "Transaction.h"
std::ostream &operator<<(std::ostream &stream, const Transaction &transaction)
{
std::string action = transaction.wasCredited ? "added." : "removed.";
stream << "A transaction was made " << transaction.GetDate() << " and a amount of " << std::setprecision(2) << std::fixed << transaction.amountCredited << " euro was " << action;
return stream;
}
std::string Transaction::GetDate() const
{
struct tm buf;
char str[26];
localtime_s(&buf, &dateTime);
asctime_s(str, sizeof str, &buf);
std::string out = std::string(str);
out.erase(std::remove(out.begin(), out.end(), '\n'), out.end());
return out;
} | [
"bas.dijkstra@student.hku.nl"
] | bas.dijkstra@student.hku.nl |
527471e6175a6e80ca73f05e82037fc8e23aee9c | 0cdc1b6e00003152dc8e89cfa642b456943cb10f | /samples/sample-watch/src/SmplWatchApp.h | 0ab7c8d76badeaf105f9f3fd1958c1437598cd24 | [
"Apache-2.0"
] | permissive | karlkar/tizen-app-assist | 9a8250936526c1b19c4ce061ea286a44f393bcfe | 08732965a5129a51dc08b830c1121a07aeaf51f7 | refs/heads/master | 2021-01-22T03:40:24.421824 | 2017-05-25T10:46:29 | 2017-05-25T10:46:29 | 92,393,390 | 0 | 0 | null | 2017-05-25T10:40:46 | 2017-05-25T10:40:46 | null | UTF-8 | C++ | false | false | 1,325 | h | /*
* Copyright (c) 2014-2016 Samsung Electronics Co., Ltd. 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 _SMPL_WATCH_APP_H_
#define _SMPL_WATCH_APP_H_
#include <WWatchApp.h>
class SmplWatchFaceViewController;
class SmplWatchApp : public app_assist::WWatchApp {
public:
SmplWatchApp();
virtual ~SmplWatchApp();
private:
bool onCreate(); // override
void onTerminate(); // override
void onPause(); // override
void onResume(); // override
void onAppControl(app_control_h request, bool firstLaunch); // override
void onTimeTick(watch_time_h watchTime); // override
void onAmbientModeTimeTick(watch_time_h watchTime); // override
void onAmbientModeChanged(bool ambientMode); // override
SmplWatchFaceViewController* _watchFaceView;
};
#endif /* _SMPL_WATCH_APP_H_ */
| [
"hosang.kim@samsung.com"
] | hosang.kim@samsung.com |
754891ec5450497bc156e8caa2c7b8a136544475 | 95b10c9a5b452bdd527825832d5686738d3753b3 | /ILSwithDFSandThreeScaling/src/Test.cpp | db964ba7eaafc2813ceee2cf7e788f37fe318f64 | [] | no_license | windyswsw/ILSwithThreeScaling | 2b268246f7621e2b77c709cea26f04f90416012c | a543a25fa85dab9b535016ef2701a84ec54c4645 | refs/heads/master | 2021-01-13T21:18:54.879960 | 2017-02-14T11:19:22 | 2017-02-14T11:19:22 | 81,936,046 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,339 | cpp | /*
* Main.cpp
*
* Created on: Oct 19, 2015
* Author: u99319
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <iterator>
#include <map>
#include <time.h>
#include <algorithm>
#include <stdio.h>
#include <cstring>
#include <iomanip>
#include <stdarg.h>
#include <cstdarg>
#include <ctime>
//#include <chrono>
#include <unordered_map>
#include <set>
#include "StructsUse.h"
#include "FormatTime.h"
#include "CountCPU.h"
#include "GenLists.h"
#include "InitialListsGeneration.h"
#include "LinksPathsCheck.h"
#include "UpdateLists.h"
#include "AddRemovePolicy.h"
#include "ObjectValueCalculation.h"
#include "ScaleObjectValueCalculation.h"
#include "Print.h"
#include "PrintAllocation.h"
////#include "PrintTime.h"
#include "DFS.h"
//#include "Random.h"
#include "InitialAcceptanceCriteria.h"
#include "InitialPerturbation.h"
#include "InitialLocalSearchWithOnePolicyMove.h"
#include "DFSLocalSearchWithOnePolicyMove.h"
#include "InitialLocalSearch.h"
#include "InitialRepeatProcedure.h"
#include "InitialPolicyImplementation.h"
#include "Affordable.h"
#include "PolicyChangeListForRound.h"
#include "DFSVerticalScaling.h"
#include "DFSIncrementalScaling.h"
#include "DFSUnifiedScaling.h"
#include "VerticalScale.h"
#include "IncrementalScale.h"
#include "UnifiedScale.h"
#include "ScaleAcceptanceCriteria.h"
#include "LSVerticalScale.h"
#include "LSIncrementalScale.h"
#include "LSUnifiedScale.h"
#include "PerturbationUnifiedScale.h"
#include "PerturbationVerticalScale.h"
#include "PerturbationIncrementalScale.h"
#include "ScaleRepeatProcedure.h"
#include "ScaleLocal.h"
//int main(){
int main(int argc, char* argv[]){
if (argc != 2){
cout << "Usage: <V or U or I: V for Vertical, U for Unified, I for Incremental>" << "\n";
return -1;
}
else{
bool vertical = false;
bool unified = false;
bool incremental = true;
if (strcmp(argv[1],"V") == 0){
vertical = true;
}
else if (strcmp(argv[1],"U") == 0){
unified = true;
}
else if (strcmp(argv[1],"I") == 0){
incremental = true;
}
else{
cout << "Usage: <V or U or I: V for Vertical, U for Unified, I for Incremental> " << "\n";
return -1;
}
float LinksDelay = 0.0001; // from cisco white paper, processing delay per hop 25 micro seconds
int NoOfServers = 128;
int NoOfLinks = 160;
int InPathLinks = 3;
float ServerCap = 24; // from Online VNF scaling in data centers
//float MaxLinksCap = 10000; // in Mbps // 10Gbps from Network Functions Virtualization with Soft RealTime Gurantees
float MaxLinksCap = 1000000000;
int experiments = 1;
int InitialLocalSearchRounds = 5;
int InitialTerminationConditionRounds = 1;
int InitialNoOfPoliciesToChangeInPerturbation = 5;
int ScaleTerminationConditionRounds = 10;
int ScalePercentageOfPoliciesToChangeInPerturbation = 10;
/*time_t currentTime;
struct tm *currentDate;
time(¤tTime);
currentDate = localtime(¤tTime);*/
char filename1[256] = {0};
strcpy(filename1,"TimeILS.csv");
//strcat(filename1, fmt("-%d-%d-%d@%d.%d.%d.csv", currentDate->tm_mday, currentDate->tm_mon+1, currentDate->tm_year+1900, currentDate->tm_hour, currentDate->tm_min, currentDate->tm_sec).c_str());
ofstream myfile1;
myfile1.open (filename1, ios::out | ios::app);
/*typedef std::chrono::high_resolution_clock Time1;
typedef std::chrono::microseconds ms;*/
char filename2[256] = {0};
strcpy(filename2,"SummaryILS.csv");
//strcat(filename3, fmt("-%d-%d-%d@%d.%d.%d.csv", currentDate->tm_mday, currentDate->tm_mon+1, currentDate->tm_year+1900, currentDate->tm_hour, currentDate->tm_min, currentDate->tm_sec).c_str());
ofstream myfile2;
myfile2.open (filename2, ios::out | ios::app);
char filename3[256] = {0};
strcpy(filename3,"Allocation.txt");
//strcat(filename3, fmt("-%d-%d-%d@%d.%d.%d.csv", currentDate->tm_mday, currentDate->tm_mon+1, currentDate->tm_year+1900, currentDate->tm_hour, currentDate->tm_min, currentDate->tm_sec).c_str());
ofstream myfile3;
myfile3.open (filename3, ios::out | ios::app);
PrintFirstLine(myfile2);
PrintFirstLine(myfile2);
PrintNewLine(myfile2);
srand((unsigned int) time(0));
for(int r=0; r<experiments;r++){
CommonList NewCommonList;
GenCommonList(&NewCommonList);
UniqueList NewUniqueList;
GenUniqueList(&NewUniqueList, NoOfServers, ServerCap, MaxLinksCap);
FullSol InitialFullSolution;
InitialFullSolution.CurLists = NewUniqueList;
InitialFullSolution.ObjVal = 0;
InitialFullSolution.InitialObjVal = 0;
InitialFullSolution.CPULeft = NoOfServers * ServerCap;
InitialFullSolution.MaxCPUs = 0;
CountTotalCPUs(&InitialFullSolution, &NewCommonList);
InitialPolicyImplementation(&InitialFullSolution, &NewCommonList,LinksDelay, myfile1, myfile2, myfile3,InitialNoOfPoliciesToChangeInPerturbation, InitialTerminationConditionRounds );
PrintSummaryGlobal(r, &InitialFullSolution, myfile2, 'S', &NewCommonList);
PrintNewLine(myfile2);
PrintFullAllocation(r, 'S', &InitialFullSolution, myfile3);
PrintAllocationLine(myfile3);
FullSol InitialFullSolutionL;
InitialFullSolutionL.VectorOfPartialSols = InitialFullSolution.VectorOfPartialSols;
InitialFullSolutionL.VectorOfOriginalSols = InitialFullSolution.VectorOfOriginalSols;
InitialFullSolutionL.VectorOfChangedSols = InitialFullSolution.VectorOfChangedSols;
InitialFullSolutionL.CurLists = InitialFullSolution.CurLists;
InitialFullSolutionL.ObjVal = InitialFullSolution.ObjVal;
InitialFullSolutionL.InitialObjVal = InitialFullSolution.ObjVal;
InitialFullSolutionL.CPULeft = InitialFullSolution.CPULeft;
InitialFullSolutionL.MaxCPUs = InitialFullSolution.MaxCPUs;
vector<ChangeInfo> FullChangeListCur2;
gen_PolicyChangeList(&FullChangeListCur2, "ScalePattern.txt");
NewCommonList.FullChangeListCur = FullChangeListCur2;
PrintScaleFirstLine(myfile2);
PrintScaleFirstLine(myfile2);
PrintNewLine(myfile2);
ScaleLocal(&InitialFullSolutionL, &NewCommonList, LinksDelay, ServerCap, InPathLinks, ScalePercentageOfPoliciesToChangeInPerturbation, ScaleTerminationConditionRounds, myfile2, myfile3, vertical, unified, incremental);
}
myfile1.close();
myfile2.close();
myfile3.close();
}
return 0;
}
| [
"noreply@github.com"
] | windyswsw.noreply@github.com |
f6de1b2d38f135e1ffb77dcd02ce0a80c58f6b26 | e7d7377b40fc431ef2cf8dfa259a611f6acc2c67 | /SampleDump/Cpp/SDK/BP_Zweihander_AlpineGuard_functions.cpp | 8a59474fcf95522e7e38555fdbe078ae8535d40c | [] | no_license | liner0211/uSDK_Generator | ac90211e005c5f744e4f718cd5c8118aab3f8a18 | 9ef122944349d2bad7c0abe5b183534f5b189bd7 | refs/heads/main | 2023-09-02T16:37:22.932365 | 2021-10-31T17:38:03 | 2021-10-31T17:38:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,546 | cpp | // Name: Mordhau, Version: Patch23
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function:
// Offset -> 0x014F36A0
// Name -> Function BP_Zweihander_AlpineGuard.BP_Zweihander_AlpineGuard_C.ReceiveBeginPlay
// Flags -> (BlueprintCallable, BlueprintEvent)
void UBP_Zweihander_AlpineGuard_C::ReceiveBeginPlay()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_Zweihander_AlpineGuard.BP_Zweihander_AlpineGuard_C.ReceiveBeginPlay");
UBP_Zweihander_AlpineGuard_C_ReceiveBeginPlay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x014F36A0
// Name -> Function BP_Zweihander_AlpineGuard.BP_Zweihander_AlpineGuard_C.ReceiveActorBeginOverlap
// Flags -> (BlueprintCallable, BlueprintEvent)
// Parameters:
// class AActor* OtherActor (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UBP_Zweihander_AlpineGuard_C::ReceiveActorBeginOverlap(class AActor* OtherActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_Zweihander_AlpineGuard.BP_Zweihander_AlpineGuard_C.ReceiveActorBeginOverlap");
UBP_Zweihander_AlpineGuard_C_ReceiveActorBeginOverlap_Params params;
params.OtherActor = OtherActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x014F36A0
// Name -> Function BP_Zweihander_AlpineGuard.BP_Zweihander_AlpineGuard_C.ReceiveTick
// Flags -> (BlueprintCallable, BlueprintEvent)
// Parameters:
// float DeltaSeconds (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UBP_Zweihander_AlpineGuard_C::ReceiveTick(float DeltaSeconds)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_Zweihander_AlpineGuard.BP_Zweihander_AlpineGuard_C.ReceiveTick");
UBP_Zweihander_AlpineGuard_C_ReceiveTick_Params params;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x014F36A0
// Name -> Function BP_Zweihander_AlpineGuard.BP_Zweihander_AlpineGuard_C.ExecuteUbergraph_BP_Zweihander_AlpineGuard
// Flags -> (Final)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UBP_Zweihander_AlpineGuard_C::ExecuteUbergraph_BP_Zweihander_AlpineGuard(int EntryPoint)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_Zweihander_AlpineGuard.BP_Zweihander_AlpineGuard_C.ExecuteUbergraph_BP_Zweihander_AlpineGuard");
UBP_Zweihander_AlpineGuard_C_ExecuteUbergraph_BP_Zweihander_AlpineGuard_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"talon_hq@outlook.com"
] | talon_hq@outlook.com |
974f8f2cd45da2b934c87fb9a445db829da94f65 | c4c3734e8fd5cb2a36db6e22614d420d63e13e35 | /TP11 Bitcoin/TP11 Bitcoin/parameters.h | e62154297af2bc57594f1838e5e0354132d52998 | [] | no_license | fmoriconi/EDA_TP11 | a089e5842a88b9cca412484b753986665535a67e | 00a5d4a47f303e18821b4d075025788b6290a2be | refs/heads/master | 2020-03-19T03:23:56.823686 | 2018-06-20T22:41:14 | 2018-06-20T22:41:14 | 135,724,318 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 257 | h | #pragma once
#define OPTION_QTY 2
class parameters_t{
public:
parameters_t() {
options[0] = { "nodes" };
options[1] = { "miners" };
}
const char * options[OPTION_QTY];
bool flags[2] = { false }; // Nodes - Miners.
int nodes;
int miners;
}; | [
"31166325+fmoriconi@users.noreply.github.com"
] | 31166325+fmoriconi@users.noreply.github.com |
4b03f95116dd6f35d573ae35cb817f0ecd47800c | fa426ed53e612707a2447697164d70708399d673 | /Proiect/src/Revista.cpp | 40d4e21aab0451c580d66ff05bb26500b0540835 | [] | no_license | iamvale/Home | da61d5c0c2fb5e28d6b23acfd0c17b7ac07f17b4 | 10c7a66f62b2b0e521d5b39f6de8636fd4283eba | refs/heads/master | 2020-05-04T09:44:01.016405 | 2019-06-16T18:57:36 | 2019-06-16T18:57:36 | 179,074,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | cpp | #include "Revista.h"
#include "Articol.h"
Revista::Revista(std::string tit, int bucEx, int bucDisp, std::string tip):Articol(tit, bucEx, bucDisp)
{
tipRev = tip;
}
Revista::~Revista()
{
//dtor
}
void Revista::setTip(std::string tp) {
tipRev = tp;
}
| [
"32463819+iamvalentina@users.noreply.github.com"
] | 32463819+iamvalentina@users.noreply.github.com |
9a6200ad8a9b32ac6bf7007c1e6c52f3cebea308 | 803e7a8ad2da3a2b2d8819542de56d9232cf9cc1 | /Data_Structure/Linear_Structure/Stack_with_Linkdedlist.cpp | e803b98ef066349f563e876baa75f17be150bebf | [] | no_license | tianyaooooo/Notes | d49a19ecdb59740290cad9f6ccadccb40fc6411e | 3019d996c311fdcd24406ffa7d70982a81c401a8 | refs/heads/master | 2022-12-17T08:13:05.037744 | 2020-09-17T01:37:27 | 2020-09-17T01:37:27 | 279,558,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,281 | cpp | #include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node
{
int data;
struct Node * pNext;
} NODE, * PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom;
} STACK, * PSTACK;
// 初始化,目的是造出一个空栈
void init(PSTACK pS);
// 压栈
void push(PSTACK pS, int val);
// 判断栈是否为空
bool is_empty(PSTACK pS);
// 出栈 把 pS 所指向的栈出栈一次,并把出栈的元素存入 pVal 形参所指向的变量中,如果出栈失败(已是空栈),返回 false,否则返回 true
bool pop(PSTACK pS, int * pVal);
// 从栈顶到栈底遍历输出
void traverse(PSTACK pS);
// 清空栈,但栈结构还在(重回 init 后的样子)
void clear(PSTACK pS);
int main()
{
int val; // 出栈元素的值
STACK S;
init(&S);
push(&S, 1);
push(&S, 2);
push(&S, 3);
push(&S, 4);
push(&S, 5);
push(&S, 6);
traverse(&S);
if(pop(&S, &val))
{
cout<<"出栈成功!出栈的元素是"<<val<<endl;
}
else
{
cout<<"出栈失败!"<<endl;
}
traverse(&S);
clear(&S);
traverse(&S);
return 0;
}
void init(PSTACK pS)
{
pS->pBottom = (PNODE)malloc(sizeof(NODE));
if (pS->pBottom == NULL)
{
cout<<"动态内存分配失败!"<<endl;
exit(-1);
}
pS->pTop = pS->pBottom;
pS->pBottom->pNext = NULL; // 别忘记清空指针域!!
return;
}
void push(PSTACK pS, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (pNew == NULL)
{
cout<<"动态内存分配失败!"<<endl;
exit(-1);
}
pNew->data = val;
pNew->pNext = pS->pTop;
pS->pTop = pNew;
return;
}
bool is_empty(PSTACK pS)
{
if (pS->pBottom == pS->pTop)
{
return true;
}
else
{
return false;
}
}
bool pop(PSTACK pS, int * pVal)
{
if (is_empty(pS))
{
return false;
}
else
{
PNODE r = pS->pTop;
*pVal = r->data;
pS->pTop = r->pNext;
free(r);
r = NULL; // 别忘记清空指针
return true;
}
}
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
while(p != pS->pBottom)
{
cout<<p->data<<' ';
p = p->pNext;
}
cout<<endl;
return;
}
void clear(PSTACK pS)
{
if (is_empty(pS))
{
return;
}
else
{
PNODE p = pS->pTop;
while (p != pS->pBottom)
{
PNODE q = p->pNext;
free(p);
p = q;
q = NULL;
}
pS->pTop = pS->pBottom;
p = NULL;
}
return;
}
| [
"noreply@github.com"
] | tianyaooooo.noreply@github.com |
d16c26d59704c27dc206b8c750e5f5c9dae726c3 | d69cc85c6d1039c64112432b22a1a756b267b1a8 | /_cmake/core/WMath.cpp | c0ccdccfd00eed2cc7d4bbcbe6080bd35131101f | [
"MIT"
] | permissive | SSG-DRD-IOT/lab-protocols-mqtt-arduino | 02a004f60fcdd8da65d221dc287f26e3a016afa1 | 834cef842154b4645f98f1f7da57cb0ea887ca98 | refs/heads/master | 2021-01-19T07:54:17.220914 | 2018-04-03T16:11:34 | 2018-04-03T16:11:34 | 100,647,409 | 0 | 4 | MIT | 2018-04-03T16:11:35 | 2017-08-17T21:40:18 | C | UTF-8 | C++ | false | false | 1,614 | cpp | /*
Part of the Wiring project - http://wiring.org.co
Copyright (c) 2004-06 Hernando Barragan
Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
Lesser 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
*/
extern "C" {
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
}
#include "WMath.h"
void randomSeed(uint32_t dwSeed)
{
if (dwSeed != 0)
srand(dwSeed);
}
long random(long howbig)
{
if (howbig == 0) {
return 0;
}
return rand() % howbig;
}
long random(long howsmall, long howbig)
{
if (howsmall >= howbig) {
return howsmall;
}
long diff = howbig - howsmall;
return random(diff) + howsmall;
}
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
unsigned int makeWord(unsigned int w)
{
return w;
}
unsigned int makeWord(unsigned char h, unsigned char l)
{
return (h << 8) | l;
}
| [
"christopherx.crase@intel.com"
] | christopherx.crase@intel.com |
ecd64ec81b7b5f051ca86789c2752f4ab93034a5 | b2a68dcd001d23c1d7920352680ae394623026ea | /BOJ/02563/2563.cpp14.cpp | 578e93dfb813a3788d3ef400c8fa0d869ba6d817 | [] | no_license | nathankim0/algorithm-ps | 236779ba0daad0876a8e9d41990d23024778a9a5 | 29368dda780c29315d35c2ef7e78a0418df1aa53 | refs/heads/master | 2023-06-12T19:15:21.076210 | 2021-07-09T10:10:52 | 2021-07-09T10:10:52 | 384,387,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | cpp | #include <iostream>
using namespace std;
int arr[100][100];
int main() {
int n;
int a, b;
scanf("%d", &n);
while (n--) {
scanf("%d %d", &a, &b);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
arr[a + i][b + j] = 1;
}
}
}
int cnt = 0;
for (int i = 0; i <= 100; i++) {
for (int j = 0; j <= 100; j++) {
if (arr[i][j]) cnt++;
}
}
cout << cnt;
} | [
"jinyeob07@gmail.com"
] | jinyeob07@gmail.com |
edf5a26ad1e73b3be4239d599b21df8a155fae5d | 594aba22b8185ed8f43804c7b0b6738e9e5d031c | /Source/Shooter_3rdPerson/ShoooterCharacter.h | 5017a15e121a65aab2f28bcc011e86fa1a671f3a | [] | no_license | branthompson/3rdPersonShooter | 2acc7050e5d30bca483704bcdc60c24609a98625 | 337296f72e7b0908ae8293969f0bd42a9c23e452 | refs/heads/main | 2023-07-08T20:08:31.107346 | 2021-08-08T05:06:48 | 2021-08-08T05:06:48 | 393,859,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,389 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "ShoooterCharacter.generated.h"
class AGun;
UCLASS()
class SHOOTER_3RDPERSON_API AShoooterCharacter : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
AShoooterCharacter();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
UFUNCTION(BlueprintPure)
bool IsDead() const;
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;\
virtual float TakeDamage(float DamageAmount, struct FDamageEvent const &DamageEvent, class AController *EventInstigator, AActor *DamageCauser) override;
private:
void MoveForward(float AxisValue);
void MoveRight(float AxisValue);
void LookUpRate(float AxisValue);
void LookRightRate(float AxisValue);
void Shoot();
UPROPERTY(EditAnywhere)
float RotationRate = 10;
UPROPERTY(EditDefaultsOnly)
float MaxHealth = 100;
UPROPERTY(VisibleAnywhere)
float Health;
UPROPERTY(EditDefaultsOnly)
TSubclassOf<AGun> GunClass;
UPROPERTY()
AGun* Gun;
};
| [
"noreply@github.com"
] | branthompson.noreply@github.com |
33f4af957c223aa085f09d46e9b1149eb12f353a | 92ed12aef7e5d1d6e5b0574bc6d70549b1b345e5 | /Problems Implementations/C++ Implementation/Rounds Participations/Advent of code/2021/Day 12_part 2.cpp | 919d8f13f59f0b35385dcfdae6d58f14447e11f6 | [] | no_license | AmEr-Tinsley/Competitive-programming | 0d9adc3ef7b0a0d7a2aefc74ac3376ca3e97d74c | 0892a75e6f2a0d489d9edd53e37d4787c3452aa4 | refs/heads/master | 2023-03-16T23:58:07.349218 | 2023-03-11T17:50:27 | 2023-03-11T17:50:27 | 159,981,161 | 5 | 1 | null | 2022-09-03T07:46:03 | 2018-12-01T19:47:10 | C++ | UTF-8 | C++ | false | false | 1,790 | cpp | // ¯\_(ツ)_/¯
#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//#include <ext/pb_ds/detail/standard_policies.hpp>
#define pb push_back
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define ll long long
using namespace std;
//using namespace __gnu_pbds;
//typedef tree< int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
void file()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
//freopen("out.txt","w",stdout);
#endif
}
int tc;
const int N = 1e6 + 5, M = 2e6 + 5, MOD = 1e9 + 7, OO = 1e9 + 7;
const ll INF = 2e18;
map<string,vector<string>>g;
map<string,int>visited;
bool isSmallCave(string s){
return s[0] >= 'a' && s[0] <= 'z';
}
int go(string u){
int cnt = 0;
if(u == "end")return 1;
for(auto v : g[u]){
if(isSmallCave(v)){
bool validToVisit = v != "start";
if(visited[v] > 1)continue;
else if(visited[v] == 1){
for(auto p : visited){
if(isSmallCave(p.first) && p.second > 1)validToVisit = false;
}
}
if(validToVisit){
visited[v]++;
cnt+=go(v);
visited[v]--;
}
}
else{
cnt+=go(v);
}
}
return cnt;
}
void solve(int tc)
{
string a,b;
while(cin>>a>>b){
g[a].pb(b);
g[b].pb(a);
}
visited["start"] = 1;
int ans = go("start");
cout<<ans<<endl;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
file();
int tc = 1;
//scanf("%d",&tc);
for (int i = 1; i <= tc; i++)
solve(i);
} | [
"amerhosni07@gmail.com"
] | amerhosni07@gmail.com |
84ec860e24b49a71b2e4cab7930fa1f7813edb19 | b1310472138ac77fbb5b6dde1a30a5d337c9ebf6 | /TBGJCUtils/Examples/2017/TidyNumbers.cpp | c0aad6e62729fb63bf5d9c975053faa90b3fd5c3 | [] | no_license | bigbangvn/TBGJCUtils | 876da3784e0e203d0d874147ea1e49fe514d970e | a194b4848f4f973bbd51fc5ef7a97de8c5703e6e | refs/heads/master | 2021-01-19T03:51:57.098574 | 2017-04-14T01:06:26 | 2017-04-14T01:06:26 | 84,417,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,940 | cpp | //
// TidyNumbers.cpp
// TBGJCUtils
//
// Created by trongbangvp@gmail.com on 4/8/17.
// Copyright © 2017 trongbangvp@gmail.com. All rights reserved.
//
#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <algorithm>
using namespace std;
unsigned long long powInterger(int b, int n)
{
if(b == 0)
{
assert(0);
return 1;
}
if(n == 0) return 1;
if(n == 1) return b;
unsigned long long result = b;
for(int i = 1; i<n; ++i)
{
result = result * b;
}
return result;
}
unsigned long long findLastTidyNumber(unsigned long long N)
{
if(N<10)
return N;
//Convert to array
const int len = 20;
int index = len - 1;
int arr[len] = {0};
unsigned long long temp = N;
while(temp > 0)
{
int a = temp % 10;
temp = temp/10;
arr[index--] = a;
}
//Solve
for(int i = len-1; i> index+1; --i)
{
if(arr[i] < 0)
{
arr[i] = 9;
--arr[i-1];
}
if(arr[i] < arr[i-1])
{
--arr[i-1];
for(int j = i; j<len; ++j)
{
arr[j] = 9;
}
}
// if(currMax == 0)
// {
// return powInterger(10, (len-1) - (index+1)) - 1;
// }
}
unsigned long long result = 0;
unsigned long long gain = 1;
for(int i = len - 1; i >= index + 1; --i)
{
if(arr[i] >= 0)
{
result += arr[i]*gain;
gain *= 10;
} else
{
break;
}
}
return result;
}
#if 0
int main(int argc, const char * argv[]) {
int numTest;
cin >> numTest;
for(int i = 0; i<numTest; ++i)
{
unsigned long long N;
cin >> N;
unsigned long long result = findLastTidyNumber(N);
cout <<"Case #" <<i+1 <<": " <<result <<endl;
}
}
#endif
| [
"trongbangvp@gmail.com"
] | trongbangvp@gmail.com |
87bb2436e0e7fca6de7efc7acbfc9cb0448ff39a | 843124c50abdb72602af0b61daad9660739e5368 | /src/ces/systems/CUpdateSystem.h | dc0ee85f7abfcdc6d8484517ae7b313525c3bbc5 | [
"MIT"
] | permissive | opengamejam/OpenJam | 8806e9dd7eaa5e90048851733c9dc24d4d1f2e5c | 565dd19fa7f1a727966b4274b810424e5395600b | refs/heads/master | 2020-04-03T21:30:34.937897 | 2017-06-19T12:41:44 | 2017-06-19T12:41:44 | 28,153,757 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 508 | h | //
// CUpdateSystem.h
// OpenJam
//
// Created by Yevgeniy Logachev
// Copyright (c) 2014 yev. All rights reserved.
//
#ifndef CUPDATESYSTEM_H
#define CUPDATESYSTEM_H
#include "ISystem.h"
#include "CUpdateComponent.h"
namespace jam {
CLASS_PTR(CUpdateSystem)
class CUpdateSystem : public CSystemBase<CUpdateComponent> {
JAM_OBJECT
public:
CUpdateSystem();
virtual ~CUpdateSystem();
virtual void Update(unsigned long dt) override;
};
} // namespace jam
#endif /* CUPDATESYSTEM_H */
| [
"evg1985@gmail.com"
] | evg1985@gmail.com |
dad48b7df4931359c3ac91da7a7e2803ede7a18c | c05b8546d5c02434c2851fc5cc820fc6e12db563 | /src/qt/bitcoinstrings.cpp.save.save.save | 5362e07588801e25387dcceb15bc7eed95ca42a1 | [
"MIT"
] | permissive | taxicoinfoundation/taxicoin | 8289a75dabcc041220d14f6a3c11e5cbd8504de1 | b8db911cad0082b8d4c839f43f10420b6959c42c | refs/heads/master | 2016-09-02T04:54:57.264740 | 2014-03-06T21:36:01 | 2014-03-06T21:36:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,614 | save | #include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *bitcoin_strings[] = {
QT_TRANSLATE_NOOP("bitcoin-core", ""
"%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=taxicoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Taxicoin Alert\" admin@foo.com\n"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:"
"@STRENGTH)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv4: %s"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv6, "
"falling back to IPv4: %s"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Cannot obtain a lock on data directory %s. Taxicoin is probably already "
"running."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: The transaction was rejected! This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds!"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a relevant alert is received (%s in cmd is replaced by "
"message)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: "
"86400)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: "
"27000)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Set the number of script verification threads (up to 16, 0 = auto, <0 = "
"leave that many cores free, default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"mining or merchant applications"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Unable to bind to %s on this computer. Taxicoin is probably already running."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: Displayed transactions may not be correct! You may need to upgrade, "
"or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong Taxicoin will not work properly."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"You must set rpcpassword=<password> in the configuration file:\n"
"%s\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions."),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Taxicoin version"),
QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect through socks proxy"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of Taxicoin"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error opening block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: system error: "),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to read block info"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to read block"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to sync block index"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block index"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block info"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write file info"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write to coin database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write transaction index"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write undo data"),
QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"),
QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using DNS lookup (default: 1 unless -connect)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Generate coins (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"),
QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 288, 0 = all)"),
QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-4, default: 3)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Information"),
QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"),
QT_TRANSLATE_NOOP("bitcoin-core", "List commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 9333 or testnet: 19333)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Maintain a full transaction index (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("bitcoin-core", "Only accept block chain matching built-in checkpoints (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Output extra debugging information. Implies all other -debug* options"),
QT_TRANSLATE_NOOP("bitcoin-core", "Output extra network debugging information"),
QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the Taxicoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Select the version of socks proxy to use (4-5, default: 5)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or taxicoind"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to debugger"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set the number of threads to service RPC calls (default: 4)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: taxicoin.conf)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: taxicoind.pid)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("bitcoin-core", "System error: "),
QT_TRANSLATE_NOOP("bitcoin-core", "This help message"),
QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"),
QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("bitcoin-core", "Transaction too large"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unknown -socks proxy version requested: %i"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"),
QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart Taxicoin to complete"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("bitcoin-core", "You need to rebuild the database using -reindex to change -txindex"),
QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"),
};
| [
"simmons.johnalan@gmail.com"
] | simmons.johnalan@gmail.com |
72d959515cee47c13b07ed98d2b74f777e42dd46 | 7c513bd8398b095842e8eecb6e966f71feb5090f | /Tree.cpp | 08a3639a2ca30ac25f75b35e5ef8f4d71111ab65 | [] | no_license | vladchis20/Labor3 | 1a0f54e6f63a21d90e33a8a2938a5199c31ec516 | e4774b499da6cfb941ef45fdb8ae9683822c0b85 | refs/heads/master | 2022-04-12T16:55:54.392111 | 2020-04-06T19:53:11 | 2020-04-06T19:53:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,616 | cpp | #include <iostream>
#include "Node.h"
#include "Tree.h"
using namespace std;
Tree::Tree()
{
root = NULL;
}
Tree::Tree(int data)
{
root = new Node(data);
}
Tree::Tree(int arr[], int i, int n)
{
this->root = build_tree(arr,this->root,i,n);
}
Tree::~Tree()
{
delete root;
}
Node* Tree::build_tree(int arr[], Node* root, int i, int n)
{
// Base case for recursion
if (i < n)
{
Node* temp = new Node(arr[i]);
root = temp;
// Einfugen der linken Kind
root->left = build_tree(arr, root->left, 2 * i + 1, n);
// Einfugen der rechtes Kind
root->right = build_tree(arr, root->right, 2 * i + 2, n);
}
return root;
}
bool Tree::isEmpty()
{
if (root == NULL)
return true;
return false;
}
Node* Tree::insert(Node* node, int data)
{
/* 1. Wenn das Baum leer ist, gebe zuruck
einen neuen einzelnen Knoten*/
if (node == NULL)
return(node = new Node(data));
else
{
/* 2. Wenn nicht...*/
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
return node;
}
}
void Tree::printPostorder(Node* node)
{
if (node == NULL)
return;
printPostorder(node->left);
printPostorder(node->right);
cout << node->data << " ";
}
void Tree::printInorder(Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->data << " ";
printInorder(node->right);
}
void Tree::printPreorder(Node* node)
{
if (node == NULL)
return;
cout << node->data << " ";
printPreorder(node->left);
printPreorder(node->right);
}
int Tree::countNodes(Node* n)
{
int ct = 1;
if (n->left != NULL)
ct += countNodes(n->left);
if (n->right != NULL)
ct += countNodes(n->right);
return ct;
}
int Tree::countEdges(Node* n)
{
return countNodes(n) - 1;
}
int Tree::height(Node* n)
{
if (n == NULL)
return 0;
else
{
int lDepth = height(n->left);
int rDepth = height(n->right);
if (lDepth > rDepth)
return(lDepth + 1);
else return(rDepth + 1);
}
}
Node* Tree::minValueNode(Node* node)
{
Node* current = node;
while (current && current->left != NULL)
current = current->left;
return current;
}
Node* Tree::deleteNode(Node* root, int data)
{
}
| [
"noreply@github.com"
] | vladchis20.noreply@github.com |
ddafe2f276010941feb6e654dd4d4f88fd803e1f | edcdce99f0102fb170074b5f7c438df3000568fc | /AST_algorithm.h | 8570472d125b34d2a78161013469fa8b2e0abf5d | [] | no_license | lavender94/CSCI561-resolution | 0468d607ae9bf6416b8215a7cf73b06165588787 | 89303c733fa37b5a882c4edfe6548d9f1cae94cf | refs/heads/master | 2021-03-18T03:57:12.459581 | 2017-11-18T00:24:22 | 2017-11-18T00:24:22 | 73,983,780 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | h | #pragma once
#include "common.h"
#include <string>
#include "Parser.h"
Expression *EXP(Parser &p);
Expression *EXP2(Parser &p);
Expression *EXP3(Parser &p);
Expression *OP(Parser &p);
Expression *FUNC(Parser &p, std::string name);
Expression *buildAST(Parser &p);
| [
"hchen132@gmail.com"
] | hchen132@gmail.com |
1addd448690efedd6671c19277e9cc0b33f7ffa1 | eb8d36a89dbaeffeedd8584d970aa2b33a8b2c6e | /CQ-0232/sequence/sequence.cpp | 21844bcdfa0c23cc3d06afc89831f115549b4c02 | [] | no_license | mcfx0/CQ-NOIP-2021 | fe3f3a88c8b0cd594eb05b0ea71bfa2505818919 | 774d04aab2955fc4d8e833deabe43e91b79632c2 | refs/heads/main | 2023-09-05T12:41:42.711401 | 2021-11-20T08:59:40 | 2021-11-20T08:59:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,174 | cpp | #include<bits/stdc++.h>
using namespace std;
const long long mod=998244353;
int n,m,k,mar;
long long v[107],num[31],ans=0,dpc[107][107];
int now[107];
bool check()
{
long long size=0;
memset(now,0,sizeof(now));
for(int i=0;i<=m;i++) now[i]=num[i];
for(int i=0;i<=mar;i++)
{
now[i+1]+=(now[i]/2);
now[i]=now[i]%2;
}
for(int i=0;i<=mar;i++)
{
size+=now[i];
if(size>k) return 0;
}
return 1;
}
void dfs(int id,int y)
{
if(id>m)
{
if(y==0&&check())
{
long long tmp=1,times=1,w=n;
for(int i=0;i<=m;i++)
{
if(num[i]>0)
{
for(int j=1;j<=num[i];j++) tmp=tmp*v[i]%mod;
times=times*dpc[w][num[i]]%mod;
w-=num[i];
}
}
ans=(ans+times*tmp%mod)%mod;
}
return;
}
for(int i=0;i<=y;i++)
{
num[id]=i;
dfs(id+1,y-i);
}
}
int main()
{
freopen("sequence.in","r",stdin);
freopen("sequence.out","w",stdout);
scanf("%d %d %d",&n,&m,&k);
for(int i=0;i<=m;i++)
{
scanf("%lld",&v[i]);
v[i]=v[i]%mod;
}
dpc[1][1]=1;
for(int i=2;i<=n;i++)
{
dpc[i][1]=i;
for(int j=2;j<i;j++) dpc[i][j]=(dpc[i-1][j]+dpc[i-1][j-1])%mod;
dpc[i][i]=1;
}
mar=log2(n*(1<<m))+1;
dfs(0,n);
printf("%lld",ans);
return 0;
}
| [
"3286767741@qq.com"
] | 3286767741@qq.com |
c8cdc7ae0a2b147796395b27e0ebfecd4c8df4a6 | 2ba118058d82463561ebc4e9d52030e3a1ef466c | /visit_tuple_advanced.h | 556f63b4c0800b2b3fe4ebfe5d9fe07fadcd76d9 | [
"MIT"
] | permissive | xaedes/cpp_visit_tuple | fa84ca8e64f0f84cd8c6bc453da2bd419d0acfc2 | e7c5ec2e85eee942e1e15e4eccc89f02a7e7f58d | refs/heads/main | 2023-04-30T05:34:08.540744 | 2021-05-20T23:46:33 | 2021-05-20T23:46:33 | 368,197,202 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,385 | h | #pragma once
#include <tuple>
#include <type_traits>
namespace detail
{
template <class ReturnType, int Idx, class Tuple, class Visitor, std::enable_if_t<(Idx >= std::tuple_size<Tuple>::value) , bool> = true, std::enable_if_t<!std::is_void<ReturnType>::value, bool> = true>
ReturnType visit_tuple_impl(Tuple& tuple, int idx, const Visitor& visitor)
{
ReturnType default_value;
return default_value;
}
template <class ReturnType, int Idx, class Tuple, class Visitor, std::enable_if_t<(Idx < std::tuple_size<Tuple>::value) , bool> = true, std::enable_if_t<!std::is_void<ReturnType>::value, bool> = true>
ReturnType visit_tuple_impl(Tuple& tuple, int idx, const Visitor& visitor)
{
if (Idx == idx)
{
return visitor(std::get<Idx>(tuple));
}
return visit_tuple_impl<ReturnType, Idx+1>(tuple, idx, visitor);
}
template <class ReturnType, int Idx, class Tuple, class Visitor, std::enable_if_t<(Idx >= std::tuple_size<Tuple>::value) , bool> = true, std::enable_if_t<std::is_void<ReturnType>::value, bool> = true>
ReturnType visit_tuple_impl(Tuple& tuple, int idx, const Visitor& visitor)
{
}
template <class ReturnType, int Idx, class Tuple, class Visitor, std::enable_if_t<(Idx < std::tuple_size<Tuple>::value) , bool> = true, std::enable_if_t<std::is_void<ReturnType>::value, bool> = true>
ReturnType visit_tuple_impl(Tuple& tuple, int idx, const Visitor& visitor)
{
if (Idx == idx)
{
visitor(std::get<Idx>(tuple));
}
visit_tuple_impl<ReturnType, Idx+1>(tuple, idx, visitor);
}
template <int Idx, class Tuple, class AccumType, class Visitor, std::enable_if_t<(Idx >= std::tuple_size<Tuple>::value) , bool> = true>
AccumType&& foldl_tuple_impl(Tuple& tuple, AccumType&& accum, const Visitor& visitor)
{
return std::forward<AccumType>(accum);
}
template <int Idx, class Tuple, class AccumType, class Visitor, std::enable_if_t<(Idx < std::tuple_size<Tuple>::value) , bool> = true>
AccumType&& foldl_tuple_impl(Tuple& tuple, AccumType&& accum, const Visitor& visitor)
{
return std::forward<AccumType>(
foldl_tuple_impl<Idx+1>(
tuple,
std::forward<AccumType>(
visitor(
std::forward<AccumType>(accum),
std::get<Idx>(tuple)
)
), visitor
)
);
}
}
template <class ReturnType, class Tuple, class Visitor, std::enable_if_t<!std::is_void<ReturnType>::value, bool> = true>
ReturnType visit_tuple(Tuple& tuple, int idx, const Visitor& visitor)
{
return detail::visit_tuple_impl<ReturnType, 0>(tuple, idx, visitor);
}
template <class ReturnType, class Tuple, class Visitor, std::enable_if_t<std::is_void<ReturnType>::value, bool> = true>
ReturnType visit_tuple(Tuple& tuple, int idx, const Visitor& visitor)
{
detail::visit_tuple_impl<ReturnType, 0>(tuple, idx, visitor);
}
template <class Tuple, class AccumType, class Visitor>
AccumType&& foldl_tuple(Tuple& tuple, AccumType&& accum, const Visitor& visitor)
{
return std::forward<AccumType>(
detail::foldl_tuple_impl<0>(
tuple,
std::forward<AccumType>(accum),
visitor
)
);
}
| [
"noreply@github.com"
] | xaedes.noreply@github.com |
76e6dc2af4ac43f2fc8e8cf2081d00009a7ff427 | efaa8fe089e2ae47e582989e0035110df64d3732 | /week-03/day-3/BlogPost/main.cpp | 698be5d4600444499a12ba57e321520c82a3fbe7 | [] | no_license | green-fox-academy/gabortrajtler | b2416cba8c1d1c4bd05bbf71ac6c6bd8eb3ff83c | bc081a15fc7a1094928c4c428cb17faa6efc7369 | refs/heads/master | 2020-06-11T04:56:49.368008 | 2019-10-23T12:41:56 | 2019-10-23T12:41:56 | 193,855,290 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,384 | cpp | #include <iostream>
#include "BlogPost.h"
#include "Blog.h"
/*
*
* Create a BlogPost class that has
an authorName
a title
a text
a publicationDate
Create a few blog post objects:
"Lorem Ipsum" titled by John Doe posted at "2000.05.04."
Lorem ipsum dolor sit amet.
"Wait but why" titled by Tim Urban posted at "2010.10.10."
A popular long-form, stick-figure-illustrated blog about almost everything.
"One Engineer Is Trying to Get IBM to Reckon With Trump" titled by William Turton at "2017.03.28."
Daniel Hanley, a cybersecurity engineer at IBM, doesn’t want to be the center of attention. When I asked to take his picture outside one of IBM’s New York City offices, he told me that he wasn’t really into the whole organizer profile thing.
*
* Reuse your BlogPost class
Create a Blog class which can
store a list of BlogPosts
add BlogPosts to the list
delete(int) one item at given index
update(int, BlogPost) one item at the given index and update it with another BlogPost
*
*/
int main()
{
std::cout << "Blog Posts: " << std::endl;
BlogPost blogPost0("John Doe", "Lorem Ipsum", "Lorem ipsum dolor sit amet.", "2000.05.04.");
BlogPost blogPost1("Tim Urban", "Wait but why", "A popular long-form, stick-figure-illustrated blog about almost everything.", "2010.10.10.");
BlogPost blogPost2("William Turton", "One Engineer Is Trying to Get IBM to Reckon With Trump", "Daniel Hanley, a cybersecurity engineer at IBM, doesn’t want to be the center of attention. When I asked to take his picture outside one of IBM’s New York City offices, he told me that he wasn’t really into the whole organizer profile thing.", "2017.03.28.");
BlogPost blogPost3("William Turton", "One Engineer Is Trying to Get IBM to Reckon With Trump", "Daniel Hanley, a cybersecurity engineer at IBM, doesn't want to be the center of attention. When I asked to take his picture outside one of IBM's New York City offices, he told me that he wasn't really into the whole organizer profile thing.", "2017.03.28.");
/* std::cout << blogPost1.getTitle() << " titled by " << blogPost1.getAuthorName()
<< " posted at " << blogPost1.getPublicationDate() << " Text:" << std::endl;
std::cout << blogPost1.getText() << std::endl << std::endl;
std::cout << blogPost2.getTitle() << " titled by " << blogPost2.getAuthorName()
<< " posted at " << blogPost2.getPublicationDate() << " Text:" << std::endl;
std::cout << blogPost2.getText() << std::endl << std::endl;
std::cout << blogPost3.getTitle() << " titled by " << blogPost3.getAuthorName()
<< " posted at " << blogPost3.getPublicationDate() << " Text:" << std::endl;
std::cout << blogPost3.getText() << std::endl << std::endl;*/
Blog blog;
blog.add(blogPost0);
blog.add(blogPost1);
blog.add(blogPost2);
blog.deletePost(0);
blog.update(1, blogPost3);
std::cout << "Welcome to our Blog!" << std::endl;
for (int i = 0; i < blog.getBlog().size(); ++i) {
std::cout << blog.getBlog()[i].getTitle() << " titled by " << blog.getBlog()[i].getAuthorName()
<< " posted at " << blog.getBlog()[0].getPublicationDate() << " Text:" << std::endl;
std::cout << blog.getBlog()[i].getText() << std::endl << std::endl;
}
return 0;
} | [
"trajtlerg@gmail.com"
] | trajtlerg@gmail.com |
334ba2edefb4b6fa70d14a5ddc56762d4caaf0d8 | c1008dbb560e2f100d65751faa2fef775ac50e82 | /shopMall/mall.cpp | 102720dd030d397b6b49d0a546bebea8327fee45 | [
"MIT"
] | permissive | Alexader/OOPDesign | 363136eeb1448f64c26952c93159fe39f1d0512e | 860d0ef07eaeba600fb30acb17536a08e5682bc3 | refs/heads/master | 2021-04-09T13:25:01.070235 | 2018-03-16T15:30:23 | 2018-03-16T15:30:23 | 125,450,302 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,466 | cpp | //Submit this file
#include "mall.h"
//You are NOT allowed to include any additional library
//NOTE: Mall::duplicateShopLinkedList must NOT be implemented here
Mall::Mall(string name, string address) : name(name), address(address) {
shopHead = nullptr;
}
Mall::Mall(Mall &another) {
// Use duplicateShopLinkedList() to copy
shopHead = duplicateShopLinkedList(another.shopHead);
name = another.name;
address = another.address;
}
Mall::~Mall() {
// Delete the whole list
Node *head = shopHead; Node *temp = shopHead;
while (temp != nullptr) {
temp = temp->getNext();
delete head;
head = temp;
}
}
Shop *Mall::getShop(int shopNumber) {
if (shopHead == nullptr) return nullptr;
else {
// Traverse the list
Node *temp = shopHead;
while (temp != nullptr) {
if (temp->getShop()->getShopNumber() == shopNumber)
return temp->getShop();
temp = temp->getNext();
}
return nullptr;
}
}
void Mall::setName(string name) {
this->name = name;
}
void Mall::setAddress(string address) {
this->address = address;
}
string Mall::getName() {
return name;
}
string Mall::getAddress() {
return address;
}
bool Mall::addShop(string name, int shopNumber) {
if (shopHead == nullptr) {
shopHead = new Node(new Shop(name, shopNumber), nullptr);
return true;
}
Node *temp = shopHead;
do {
if (temp->getShop()->getShopNumber() == shopNumber) return false;
if (temp->getNext() == nullptr) {
temp->setNext(new Node(new Shop(name, shopNumber), nullptr));
return true;
}
temp = temp->getNext();
} while (temp != nullptr);
}
bool Mall::removeShop(int shopNumber) {
Node *fence = shopHead;
Node *formerPointer = nullptr;
if (fence == nullptr) return false;
while (fence->getNext() != nullptr) {
formerPointer = fence; // Save fence former pointer
if (fence->getShop()->getShopNumber() == shopNumber) {
// Swap next Node and current Node and delete next Node
Shop *tempShop = fence->getShop();
fence->setShop(fence->getNext()->getShop());
Node *temp = fence->getNext();
fence->setNext(temp->getNext());
temp->setShop(tempShop);
delete temp;
temp = nullptr; tempShop = nullptr;
return true;
}
else fence = fence->getNext();
}
if (fence->getShop()->getShopNumber() == shopNumber) { // In tail node
formerPointer->setNext(nullptr);
delete fence;
return true;
}
return false;
}
| [
"tyxj58@gmail.com"
] | tyxj58@gmail.com |
82d075e227b96e28ad56ebaee083d785d8bf6c0e | 141e1ea2c92f3dfb68c3cf25699b40bebfad7007 | /psana/src/legion_helper.h | 5e2a7fe5be0f9b16fe0dd620e8497944acd0bdff | [] | no_license | brtnfld/lcls2 | 33c4973264f046830fd4d134b7635c2d8353ea15 | 250fdd53f764b6e9842b959ab36688debd9c49b6 | refs/heads/master | 2020-03-21T00:41:24.741236 | 2018-06-25T16:55:38 | 2018-06-25T16:55:38 | 137,905,284 | 0 | 0 | null | 2018-06-19T14:46:28 | 2018-06-19T14:46:27 | null | UTF-8 | C++ | false | false | 1,337 | h | #ifndef LEGION_HELPER_H
#define LEGION_HELPER_H
#ifndef PSANA_USE_LEGION
#error legion_helper.h requires PSANA_USE_LEGION
#endif
#include <stddef.h>
#include <vector>
#include <legion.h>
// Helper for creating a logical region
class LegionArray {
public:
LegionArray();
LegionArray(size_t bytes);
LegionArray(const LegionArray &array) = delete; // not supported
~LegionArray();
LegionArray &operator=(LegionArray &&array); // consumes array
operator bool() const;
char *get_pointer();
private:
Legion::LogicalRegionT<1> region;
Legion::PhysicalRegion physical;
template <class C, typename ... Ts>
friend class LegionTask;
};
// Helper for creating a task
template <class C, typename ... Ts>
class LegionTask {
public:
LegionTask();
LegionTask(Ts ... ts);
void add_array(const LegionArray &array);
void launch();
protected:
std::vector<LegionArray> arrays; // valid inside run()
private:
Legion::TaskLauncher launcher;
protected:
static Legion::TaskID register_task(const char *task_name);
public:
static void task_wrapper(const Legion::Task *task,
const std::vector<Legion::PhysicalRegion> ®ions,
Legion::Context ctx, Legion::Runtime *runtime);
};
#include "legion_helper.inl"
#endif
| [
"slaughter@cs.stanford.edu"
] | slaughter@cs.stanford.edu |
8097ca8d35928dcbda6a130961aa16ab4dd0bfc2 | 62d77106b820b69098da1772a6f1eee57810c07e | /src/ReFFT.cpp | ccfe8afd72231b0e1c3221a5eaa63080a38e12b7 | [] | no_license | gdkar/rmwarp | eb2a6c2e5c00532ea14f995ce9bb31bd6a285cdd | bce89d436b0c3ca4aecc54b21debc3d6265d2cb2 | refs/heads/master | 2021-01-20T00:11:32.749997 | 2017-04-22T20:18:52 | 2017-04-22T20:18:52 | 89,094,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,038 | cpp | #include <thread>
#include <mutex>
#include "rmwarp/ReFFT.hpp"
#include "rmwarp/KaiserWindow.hpp"
using namespace RMWarp;
namespace detail {
struct _wisdom_reg {
template<class F,class D>
static void wisdom(F && ffunc, D && dfunc, const char mode[]) {
if(auto home = getenv("HOME")){
char fn[256];
::snprintf(fn, sizeof(fn), "%s/%s.f", home, ".rubberband.wisdom");
if(auto f = ::fopen(fn, mode)){
std::forward<F>(ffunc)(f);
fclose(f);
}
::snprintf(fn, sizeof(fn), "%s/%s.d", home, ".rubberband.wisdom");
if(auto f = ::fopen(fn, mode)){
std::forward<D>(dfunc)(f);
fclose(f);
}
}
}
static std::once_flag _wisdom_once;
_wisdom_reg(){
std::call_once(_wisdom_once,[](){
fftwf_init_threads();
fftwf_make_planner_thread_safe();
fftw_init_threads();
fftw_make_planner_thread_safe();
wisdom(fftwf_import_wisdom_from_file,fftw_import_wisdom_from_file,"rb");
});
}
~_wisdom_reg() {
wisdom(fftwf_export_wisdom_to_file,fftw_export_wisdom_to_file,"wb");
}
};
/*static*/ std::once_flag _wisdom_reg::_wisdom_once{};
_wisdom_reg the_registrar{};
}
void ReFFT::initPlans()
{
if(m_size) {
if(m_plan_r2c) {
fftwf_destroy_plan(m_plan_r2c);
m_plan_r2c = 0;
}
if(m_plan_c2r) {
fftwf_destroy_plan(m_plan_c2r);
m_plan_c2r = 0;
}
m_coef = m_size ? (m_size / 2 + 1) : 0; /// <- number of non-redundant forier coefficients
m_spacing = align_up(m_coef, item_alignment);
cexpr_for_each([sz=size_type(m_size)](auto & item){item.resize(sz);}
, m_h
, m_Dh
, m_Th
, m_TDh
, m_flat
);
cexpr_for_each([sz=size_type(spacing() * 2)](auto & item){item.resize(sz);}
, m_split
, m_X
, m_X_Dh
, m_X_Th
, m_X_TDh
);
auto _real = &m_split[0]; auto _imag = &m_split[m_spacing]; auto _time = &m_flat[0];
{
auto dims = fftwf_iodim{ m_size, 1, 1};
m_plan_r2c = fftwf_plan_guru_split_dft_r2c(
1, &dims, 0, nullptr, _time, _real, _imag, FFTW_ESTIMATE);
}
{
auto dims = fftwf_iodim{ m_size, 1, 1};
m_plan_c2r = fftwf_plan_guru_split_dft_c2r(
1, &dims, 0, nullptr, _real, _imag, _time, FFTW_ESTIMATE);
}
}
}
/*static*/ ReFFT ReFFT::Kaiser(int _size, float alpha)
{
auto win = vector_type(_size, 0.0f);
auto win_dt = vector_type(_size, 0.0f);
make_kaiser_window(win.begin(),win.end(), alpha);
return ReFFT(win.cbegin(),win.cend());
}
ReFFT& ReFFT::operator=(ReFFT && o ) noexcept
{
swap(o);
return *this;
}
void ReFFT::swap(ReFFT &o) noexcept
{
using std::swap;
swap(m_size,o.m_size);
swap(m_coef,o.m_coef);
swap(m_spacing,o.m_spacing);
swap(m_h,o.m_h);
swap(m_Dh,o.m_Dh);
swap(m_Th,o.m_Th);
swap(m_TDh,o.m_TDh);
swap(m_flat,o.m_flat);
swap(m_split,o.m_split);
swap(m_X,o.m_X);
swap(m_X_Dh,o.m_X_Dh);
swap(m_X_Th,o.m_X_Th);
swap(m_X_TDh,o.m_X_TDh);
swap(m_plan_r2c,o.m_plan_r2c);
swap(m_plan_c2r,o.m_plan_c2r);
}
ReFFT::ReFFT(ReFFT && o ) noexcept
: ReFFT(0)
{
swap(o);
}
ReFFT::~ReFFT()
{
if(m_size) {
if(m_plan_r2c) {
fftwf_destroy_plan(m_plan_r2c);
m_plan_r2c = 0;
}
if(m_plan_c2r) {
fftwf_destroy_plan(m_plan_c2r);
m_plan_c2r = 0;
}
}
}
void ReFFT::_finish_process( ReSpectrum & dst, int64_t _when )
{
using reg = simd_reg<float>;
using std::tie; using std::make_pair; using std::copy; using std::get;
constexpr auto w = int(simd_width<float>);
const auto _real = &m_X[0], _imag = &m_X[m_spacing]
,_real_Dh = &m_X_Dh[0], _imag_Dh = &m_X_Dh[m_spacing]
,_real_Th = &m_X_Th[0], _imag_Th = &m_X_Th[m_spacing]
,_real_TDh = &m_X_TDh[0], _imag_TDh = &m_X_TDh[m_spacing]
;
auto _cmul = [](auto r0, auto i0, auto r1, auto i1) {
return make_pair(r0 * r1 - i0 * i1, r0 * i1 + r1 * i0);
};
auto _pcmul = [&](auto x0, auto x1) {
return _cmul(std::get<0>(x0),std::get<1>(x0),
std::get<0>(x1),std::get<1>(x1));
};
auto _cinv = [e=m_epsilon](auto r, auto i) {
auto n = bs::rec(bs::sqr(r) + bs::sqr(i) + e);//bs::Eps<float>());
return make_pair(r * n , -i * n);
};
dst.reset(m_size, _when);
for(auto i = 0; i < m_coef; i += w ) {
auto _X_r = reg(_real + i), _X_i = reg(_imag + i);
bs::store(_X_r, dst.X_real() + i);
bs::store(_X_i, dst.X_imag() + i);
{
auto _X_mag = bs::hypot(_X_i,_X_r);
bs::store(_X_mag, dst.mag_data() + i);
bs::store(bs::log(_X_mag), dst.M_data() + i);
bs::store(bs::atan2(_X_i,_X_r), dst.Phi_data() + i);
}
tie(_X_r, _X_i) = _cinv(_X_r,_X_i);
auto _Dh_over_X = _cmul( reg(_real_Dh + i),reg(_imag_Dh + i) ,_X_r, _X_i );
bs::store(get<0>(_Dh_over_X), &dst.dM_dt [0] + i);
bs::store(get<1>(_Dh_over_X), &dst.dPhi_dt[0] + i);
auto _Th_over_X = _cmul( reg(_real_Th + i),reg(_imag_Th + i) ,_X_r, _X_i );
bs::store(-get<1>(_Th_over_X), &dst.dM_dw [0] + i);
bs::store( get<0>(_Th_over_X), &dst.dPhi_dw[0] + i);
auto _TDh_over_X = std::get<0>(_cmul( reg(_real_TDh + i),reg(_imag_TDh + i) ,_X_r, _X_i ));
auto _Th_Dh_over_X2 = std::get<0>(_pcmul(_Th_over_X,_Dh_over_X));
bs::store(_TDh_over_X - _Th_Dh_over_X2,&dst.d2Phi_dtdw[0] + i);
}
for(auto i = 0; i < m_coef; ++i) {
auto _X_r = *(_real + i), _X_i = *(_imag + i);
bs::store(_X_r, dst.X_real() + i);
bs::store(_X_i, dst.X_imag() + i);
{
auto _X_mag = bs::hypot(_X_i,_X_r);
bs::store(_X_mag, dst.mag_data() + i);
bs::store(bs::log(_X_mag), dst.M_data() + i);
bs::store(bs::atan2(_X_i,_X_r), dst.Phi_data() + i);
}
tie(_X_r, _X_i) = _cinv(_X_r,_X_i);
auto _Dh_over_X = _cmul( *(_real_Dh + i),*(_imag_Dh + i) ,_X_r, _X_i );
bs::store(get<0>(_Dh_over_X), &dst.dM_dt [0] + i);
bs::store(get<1>(_Dh_over_X), &dst.dPhi_dt[0] + i);
auto _Th_over_X = _cmul( *(_real_Th + i),*(_imag_Th + i) ,_X_r, _X_i );
bs::store(-get<1>(_Th_over_X), &dst.dM_dw [0] + i);
bs::store( get<0>(_Th_over_X), &dst.dPhi_dw[0] + i);
auto _TDh_over_X = std::get<0>(_cmul( *(_real_TDh + i),*(_imag_TDh + i) ,_X_r, _X_i ));
auto _Th_Dh_over_X2 = std::get<0>(_pcmul(_Th_over_X,_Dh_over_X));
bs::store(_TDh_over_X - _Th_Dh_over_X2,&dst.d2Phi_dtdw[0] + i);
}
}
int ReFFT::spacing() const
{
return m_spacing;
}
int ReFFT::size() const
{
return m_size;
}
int ReFFT::coefficients() const
{
return m_coef;
}
void ReFFT::updateGroupDelay(ReSpectrum &spec)
{
auto _lgd = spec.local_group_delay();
auto _lgda = spec.local_group_delay_acc();
auto _lgdw = spec.local_group_delay_weight();
auto _ltime = spec.local_time();
auto _mag = spec.mag_data();
auto _dPhi_dw = spec.dPhi_dw_data();
auto fr = 0.9f;//bs::pow(10.0f, -40.0f/20.0f);
auto ep = bs::sqrt(m_epsilon * fr * bs::rec(1-fr));
bs::transform(_mag,_mag + m_coef, _lgdw, [ep](auto m) {
auto _res = bs::is_less(m,decltype(m)(ep));
return bs::if_zero_else_one(_res);
});
/* std::transform(_mag,_mag + m_coef, _lgdw,[ep](auto m) {
return (m > ep) ? 1.0f : 0.0f;
});*/
bs::transform(_lgdw,_lgdw + m_coef, _dPhi_dw, _lgda,bs::multiplies);
std::partial_sum(_lgda,_lgda+m_coef,_lgda);
std::partial_sum(_lgdw,_lgdw+m_coef,_lgdw);
auto i = 0;
auto hi_bound = [](auto x){return (x * 1200)/1024;};
auto lo_bound = [](auto x){return (x * 860 )/1024;};
for(; i < m_coef - 8 && hi_bound(i) < i + 8; ++i) {
auto hi = i + 8;
auto lo = lo_bound(i);
auto _w = _lgdw[hi] - _lgdw[lo] + m_epsilon;
auto _d = _lgda[hi] - _lgda[lo];
_lgd[i] = -_d * bs::rec(_w);
}
for(; hi_bound(i) < m_coef; ++i) {
auto hi = hi_bound(i);
auto lo = lo_bound(i);
auto _w = _lgdw[hi] - _lgdw[lo] + m_epsilon;
auto _d = _lgda[hi] - _lgda[lo];
_lgd[i] = -_d * bs::rec(_w);
}
{
auto hi = m_coef - 1;
auto hiw = _lgdw[hi];
auto hid = _lgda[hi];
for(; i < m_coef; ++i) {
auto lo = lo_bound(i);
auto _w = hiw - _lgdw[lo] + m_epsilon;
auto _d = hid - _lgda[lo];
_lgd[i] = -_d * bs::rec(_w);
}
}
bs::transform(_lgd,_lgd+m_coef, _ltime, [w=float(spec.when())](auto x){return x + w;});
}
| [
"gdkar@alum.mit.edu"
] | gdkar@alum.mit.edu |
bc7d576730b068c422b038b306572cc616ff7208 | 938495d61712257f36cfeaa36f4380a760930047 | /clibrary/radonsolver.cpp | 1ac926ccf8fc0c4fdd2abeb1fb3d61a8a7c828c4 | [] | no_license | chaoshunh/seismic_unix | cec401f04e77c8dd6caf93e8cbac000a7ea15794 | c975332d5fab748d5f42ed8225e9f878def7d76a | refs/heads/master | 2022-11-06T18:22:16.105316 | 2020-06-26T16:52:43 | 2020-06-26T16:52:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,593 | cpp | #include "radonsolver.h"
/* This is an interface to the WTCGLS method in routine wtcgls.cpp
This function solves the system of equations
(FH WdT Wd FH + WmT Wm ) m = FH WdT Wd d
Notice that LH=FH WdT and L= Wd F are computed with matrix_3.
If we assumed noise and model are uncorrelated,
i.e., data and model covariances matrices Cd and Cm are diagonal
Wd is the factorization of the inverse data Covariance matrix
inv(Cd)=WdT Wd
Wm is the factorization of the inverse model Covariance matrix
inv(Cm)=WmT Wm
Wm is useful to increase resolution
Wd is useful to taper data at the boundaries and
to reduce effect of killed or bad traces
Wm depends on the model so iteration are necessary
Wd does not change.
*/
void radonsolver(float *pos, int nh, float **data, float *t, int nt, float dt,float **model, float *q, int nq, float dq, float eps1, float eps2, float eps, float fmax, float *Wd, int itercg, int iter_end,int norm,float step, int testadj, int rtmethod, float depth, char *solver)
{
int iq,ih,freq,iter; // counters
int nfft,maxfreq,nf; // sizes
complex **m2, **d2; // Workable arrays
complex **L; // operator
float w=0,wa,*dh;
float df;
float *Wm;
float **J;
// Foster and Mosher offset function
float *g=0;
float quantil1=eps1;
float quantil2=eps2;
float sigmam;
float sigmad;
int freqflag=0;
complex czero; czero.r=czero.i=0;
float J0=0;
int nf2=0;
complex *RC=0;
float *Cd;
// Note that c allocates memory per column
// Hence 2 D array with alloc2type requires reversing dimension
// i.e., first columns, then rows.
d2=ealloc2complex(nh,nt);
m2=ealloc2complex(nq,nt);
L=ealloc2complex(nq,nh);
dh=ealloc1float(nh);
Wm=ealloc1float(nq);
g=ealloc1float(nh);
Cd=ealloc1float(nh);
/**** cgfft ****/
nf2=npfa((int) 2*nq);
RC=ealloc1complex(nf2);
/*********************/
dataweigths(pos,nh,Wd,TRUE);
//for (ih=0;ih<nh;ih++) Cd[ih]=Wd[ih]*nh/fabs(pos[nh-1]-pos[0]);
for (ih=0;ih<nh;ih++) Cd[ih]=1;
//for (ih=0;ih<nh;ih++) Wd[ih]=Wd[ih]*nh/fabs(pos[nh-1]-pos[0]);
radon_moveout(pos,g,nh,rtmethod,depth);
fft_parameters(nt,dt,&nfft,&nf,&df);
fftgo_xt2fx(-1,data,d2,nh,nt,dt,nfft,nf);
maxfreq=(int) (fmax/df);
if (freqflag==1) maxfreq=nf;
fprintf(stderr,"maxfreq=%d, dt=%f, df=%f, nfft=%d nf=%d \n",maxfreq,dt,df,nfft,nf);
J=ealloc2float(iter_end,maxfreq);
for (freq=1;freq<maxfreq;freq++){
w=2*PI*freq*df;
wa=freqweight(freq,df,fmax-10,fmax);
radon_matrix(L,g,q,nh,nq,w);
//fprintf(stderr,"freq=%f\n",freq*df);
if (STREQ(solver,"cgfft_")) radon_matrix_cgfft(L,RC,nh,nq,nf2,Cd);
for (iter=1;iter<=iter_end;iter++){
// The deviations for data and model are computed on the least squares solution
// (after the first iteration). Then they are kept fixed to find the minimum
// of the cost function.
if (iter==2)
deviations(m2[freq],nq,d2[freq],nh,norm,quantil1,quantil2,&sigmam,&sigmad);
weights_inv(m2[freq],nq,norm,sigmam,Wm,iter);
//taper(Wm,nq,nq/5);
if (STREQ(solver,"adj___"))
Atimesx(d2[freq],L,m2[freq],nh,nq,TRUE);
else if (STREQ(solver,"cgfft_"))
/*I change for now step to sigmam to test Wm */
J0=radon_cgfft(d2[freq],L,RC,m2[freq],nh,nq,nf2,Wm,Cd,eps,itercg,step);
else if (STREQ(solver,"wtcgls"))
J0=wtcgls(d2[freq],L,m2[freq],Wm,Wd,nh,nq,0,step,itercg);
else if (STREQ(solver,"toep__"))
J0=radon_toeplitz(d2[freq],L,m2[freq],eps1,nh,nq);
else if (STREQ(solver,"cgtoep"))
J0=radon_cgtoep(d2[freq],L,m2[freq],eps1,nh,nq);
J[freq][iter-1]=J0;
}
if ((STREQ(solver,"toep__"))||(STREQ(solver,"adj___")))
for (iq=0;iq<nq;iq++) m2[freq][iq]/=nh;
if ((STREQ(solver,"cgfft_")))
for (iq=0;iq<nq;iq++) m2[freq][iq]/=nh;
if ((wa<1)&&(wa>0)) for (iq=0;iq<nq;iq++) m2[freq][iq]*=wa;
normalize(iter_end,J[freq]);
}
for (iq=0;iq<nq;iq++) m2[0][iq]=czero; //dc can not be recovered
for (freq=maxfreq;freq<nf;freq++) for (iq=0;iq<nq;iq++) m2[freq][iq]=czero;
fprintf(stderr,"w=%f\n",w);
fftback_fx2xt(1,model,m2,nq,nt,dt,nfft,nf);
//plotcurves(J,iter_end,freq,10,50,"Cost");
free2float(J);
free1complex(RC);
free1float(Cd);
free1float(g);
free1float(Wm);
free1float(dh);
free2complex(L);
free2complex(m2);
free2complex(d2);
return;
}
| [
"danielotrad@gmail.com"
] | danielotrad@gmail.com |
f0b8bd048e7d8230588f404e58053e4734f420aa | 780a8d5c451f9b4c4f5e1bec25c0c7f72ffeffd6 | /Project/Dizzy-Spiral/Dizzy_Spiral/iOS/Classes/Native/Il2CppCodeRegistration.cpp | d0f92de51dfa812955c8a1b4bede244210bfc3f4 | [] | no_license | 1812michaelpichler/Dizzy_Spiral | 2a88c8d0711f5ac62601f554e8fc3760eb98b5eb | 7822c88d6446314c910e8de828c0ff31d3721172 | refs/heads/master | 2020-06-11T00:45:33.294090 | 2018-01-22T14:52:57 | 2018-01-22T14:52:57 | 75,831,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,365 | cpp | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include "class-internals.h"
#include "codegen/il2cpp-codegen.h"
extern const Il2CppMethodPointer g_MethodPointers[];
extern const Il2CppMethodPointer g_DelegateWrappersManagedToNative[];
extern const Il2CppMarshalingFunctions g_MarshalingFunctions[];
extern const Il2CppMethodPointer g_Il2CppGenericMethodPointers[];
extern const InvokerMethod g_Il2CppInvokerPointers[];
extern const CustomAttributesCacheGenerator g_AttributeGenerators[];
const Il2CppCodeRegistration g_CodeRegistration =
{
11160,
g_MethodPointers,
0,
NULL,
25,
g_DelegateWrappersManagedToNative,
177,
g_MarshalingFunctions,
0,
NULL,
4302,
g_Il2CppGenericMethodPointers,
1648,
g_Il2CppInvokerPointers,
2527,
g_AttributeGenerators,
0,
NULL,
};
extern const Il2CppMetadataRegistration g_MetadataRegistration;
static const Il2CppCodeGenOptions s_Il2CppCodeGenOptions =
{
false,
};
static void s_Il2CppCodegenRegistration()
{
il2cpp_codegen_register (&g_CodeRegistration, &g_MetadataRegistration, &s_Il2CppCodeGenOptions);
}
static il2cpp::utils::RegisterRuntimeInitializeAndCleanup s_Il2CppCodegenRegistrationVariable (&s_Il2CppCodegenRegistration, NULL);
| [
"patrick@patrickkiss.com"
] | patrick@patrickkiss.com |
ef99b6ab1b3879922be63648890b1875406f324d | e4db258fb2fdbdc1fce5fdf7357a7f7d309e78f7 | /template method/max1.hpp | 4fb20a0bad85edfde356add75f44d88e319f1fea | [] | no_license | cepiloth/develnote | d42a316ce72eded0a9d8df2314de8d8026e08229 | 4fd72f9b5a948e584b99a917a5b40907bbddff12 | refs/heads/master | 2021-06-22T16:57:33.641236 | 2021-04-14T03:04:43 | 2021-04-14T03:04:43 | 206,345,777 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,044 | hpp | #pragma once
// 2020-10-11
template<typename T>
T max (T a, T b)
{
// b < a 라면 a를 반환하고 아니라면 b를 반환한다.
return b > a ? a : b;
}
/*
역사적인 이유로 형식 파라미터를 저으이할 때 typenmae 대신 class 사용할 수도 있다.
typename이라는 키워드는 C++98 표준을 만드는 중 상당히 늦게 도입됐다.
그 전에는 형식 파라미터를 키워드 class로 도입해야 했기 때문에 여전히 typename 대신 class를 사용할 수 있다.
그래서 템플릿 max()는 다음처럼 정의해도 된다.
template<class T>
T max(T a, T b)
{
return b > a ? a : b;
}
의미상 두 함수는 다를 게 전혀 없다. 따라서 여기서 class를 사용하더라도 템플릿 인자로 어떠한 형식이든 사용할 수 있다.
하지만 class를 사용하면 오해할 수 있으므로(T로 클래스형만을 쓸 수 있는 게 아닌데도) typename을 사용하는 편이 좋다.
클래스형 선언과 달리 typename 대신 키워드 struct 는 쓸 수 없다.
*/ | [
"lim10260@nate.com"
] | lim10260@nate.com |
2a5c03f582fe9a7cc0c8679b49607597c310a2aa | e407f89c7217faf1e9ea0ff045a1adff6e2f188c | /colorful-fireflies/src/ofApp.cpp | 6fe82975369d45965a60db995cddfd1a883cbf6c | [] | no_license | yutongxxx/CCOF_Fall2018_XIE_YUTONG | 43faa13ee459845fddad9f47f02a2a4c4d2af1a2 | 55e661f4fbce27d38220921869e565d49bd25742 | refs/heads/master | 2020-03-28T07:00:08.509703 | 2018-12-19T22:49:48 | 2018-12-19T22:49:48 | 147,874,153 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,705 | cpp | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
//
ofBackground(0xffffff);
ofEnableSmoothing();
circleResolution.addListener(this, &ofApp::circleResolutionChanged);
ringButton.addListener(this,&ofApp::ringButtonPressed);
gui.setup();
gui.add(radius.setup("closer", 9, 0.5, 50));
gui.add(circleResolution.set("differences", 5, 3, 12));
gui.add(ringButton.setup("future"));
gui.add(color.setup("color", ofColor(100, 100, 140), ofColor(0, 0), ofColor(255, 255)));
gui.add(frame.setup("framerate",10,0,100));
future.load("ring.mp3");
colorDatabase[0] = 0xFFEF00;
colorDatabase[1] = 0xFFEF00;
colorDatabase[2] = 0xFFFF00;
colorDatabase[3] = 0xFFFF00;
int colorIndex = (int)ofRandom(0, 3);
p.color = colorDatabase[colorIndex];
particles.push_back(p);
// ofDrawCircle(ofGetWindowHeight()/2, ofGetWindowWidth()/2, 5);
for(int i = 0; i< 10; i++){
for (int y = 0; y< 10 ; y++) {
pos2[y+i*10].set(100+y*100,30+i*100);
}
}
// color[i] = ofRandom(0xFFFFFF);
}
//--------------------------------------------------------------
void ofApp::exit(){
ringButton.removeListener(this,&ofApp::ringButtonPressed);
}
//--------------------------------------------------------------
void ofApp::update(){
for(int i = 0; i< 10; i++){
for (int y = 0; y< 10 ; y++) {
ofSetColor(color);
pos[y+i*10].set(200+y*100+20*sin(ofGetElapsedTimef()),30+i*100+20*cos(ofGetElapsedTimef()));
}
}
}
//--------------------------------------------------------------
void ofApp::circleResolutionChanged(int & circleResolution){
ofSetCircleResolution(circleResolution);
}
//--------------------------------------------------------------
void ofApp::ringButtonPressed(){
future.play();
}
//--------------------------------------------------------------
void ofApp::draw(){
// ofSetFrameRate(ofRandom(20));
gui.draw();
for(int i = 0; i < TOTALNUM; i++){
ofDrawCircle(pos[i], radius);
}
for(int i = 0; i < TOTALNUM; i++){
ofSetColor(ofRandom(99), ofRandom(200,255), ofRandom(0,130), ofRandom(30,50));
ofDrawCircle(pos2[i], radius+4);
}
for(int i = 0; i < TOTALNUM; i++){
ofSetColor(ofRandom(40), ofRandom(200,255), ofRandom(0,130), ofRandom(30,50));
ofDrawCircle(pos2[i], radius+5);
}
for(int i = 0; i < TOTALNUM; i++){
ofDrawCircle(pos2[i], radius+2);
}
}
| [
"noreply@github.com"
] | yutongxxx.noreply@github.com |
194d430f35af5845eabf51a09e706ba4daf37b08 | f221ab39e0d2c307be6fbf7adf58f636b24bdeea | /lib/FastPatchList.cpp | 69778839215440ea709a601913eba4f7e6a4d76b | [
"BSD-3-Clause"
] | permissive | ChristianFrisson/NMPT | 3a40e81e5e69f03980d7460d1d3ccf18d4bc3978 | dda56fa5202bde140500120ee472465d386b685c | refs/heads/master | 2021-01-20T07:00:10.101779 | 2018-07-18T00:46:30 | 2018-07-18T00:46:30 | 11,305,943 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,475 | cpp | /*
* FastPatchList.cpp
* OpenCV
*
* Created by Nicholas Butko on 7/25/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "FastPatchList.h"
#include "DebugGlobals.h"
#include <math.h>
#include <iostream>
#include <opencv2/core/core.hpp>
using namespace std;
using namespace cv;
FastPatchList::FastPatchList(Size minSize, Size maxSize, double scaleInc, double stepWidth,
cv::Size patchSize, int scaleStepWidth) : PatchList(minSize, maxSize, scaleInc, stepWidth, patchSize), scalestepwidth(scaleStepWidth){
}
void FastPatchList::resetPointers() {
if (_PATCHLIST_DEBUG) cout<< "FastPatchList Reset Pointers" << endl;
resetContainerSizes();
double* dest1 = (double*)filterImage.data;
double* dest2 = (double*)accumulatorImage.data;
int dstWidthStep1 = filterImage.step/sizeof(double);
int dstWidthStep2 = accumulatorImage.step/sizeof(double);
const integral_type* integralData = images[0]->startOfIntegralData();
Size mins = getMinEffectivePatchSize();
double currWidth = mins.width;
double currHeight = mins.height;
double currInc = stepwidth;
totalPatches = 0;
for (int i = 0; i < numScales; i++) {
Size s = images[0]->getImageSize();
int filterWidth = s.width - (int)currWidth + 1;
int filterHeight = s.height - (int)currHeight + 1;
int scalewidth = ceil(filterWidth *1.0/currInc);
int scaleheight = ceil(filterHeight*1.0/currInc);
numAtScale[i] = scalewidth*scaleheight;
scaleImageSizes[i] = cvSize(scalewidth,scaleheight);
scalePatchSizes[i]= cvSize((int)currWidth, (int)currHeight);
scaleFilterSizes[i]= cvSize((int)currWidth, (int)currHeight);
totalPatches+= numAtScale[i];
if (_PATCHLIST_DEBUG) cout<< "FastPatchList: Scale " << i << " expects " << numAtScale[i] << " patches of size " << (int)currWidth << "x" << (int)currHeight << "." << endl;
srcAtScales[i] = (const integral_type**)malloc(numAtScale[i]*sizeof(integral_type*));
destsAtScales[i] = (double**)malloc(numAtScale[i]*sizeof(double*));
accAtScales[i] = (double**)malloc(numAtScale[i]*sizeof(double*));
imLocAtScales[i] = (int*)malloc(numAtScale[i]*sizeof(int));
int ind = 0;
for (int j = 0; j < scaleheight; j++) {
int width = images[0]->getImageSize().width;
int rowInd1 = ((int)(j*currInc))*(images[0]->integralDataRowWidth());
int rowInd2 = j*dstWidthStep1;
int rowInd3 = j*dstWidthStep2;
int rowInd4 = ((int)(j*currInc))*(width);
for (int k = 0; k < scalewidth; k++) {
srcAtScales[i][ind] = &integralData[rowInd1+(int)(k*currInc)];
destsAtScales[i][ind] = &dest1[rowInd2+k];
accAtScales[i][ind] = &dest2[rowInd3+k];
imLocAtScales[i][ind] = rowInd4+(int)(k*currInc);
ind++;
}
}
//cout<< "Scale " << i << " found " << ind << " patches." << endl;
currWidth = currWidth*scaleinc;
currHeight = currHeight*scaleinc;
if (scalestepwidth) currInc = currInc*scaleinc;
}
if (_PATCHLIST_DEBUG) cout<< "In all, " << totalPatches << " patches were listed." << endl;
srcInds = (integral_type**)malloc(numAtScale[0]*sizeof(integral_type*));
destInds = (double**)malloc(numAtScale[0]*sizeof(double*));
accInds = (double**)malloc(numAtScale[0]*sizeof(double*));
imLoc = (int*)malloc(numAtScale[0]*sizeof(int));
shouldResetAccumulator = 1;
}
int FastPatchList::setImageAllScalesNeedsPointerReset(IplImage* newImage) {
Mat img = newImage;
oldNumScales = numScales;
origImageSize = img.size();
numScales = getEffectiveNumScales();
if (_PATCHLIST_DEBUG) cout<< "SetImage on FastPatchList with " << numScales << " scales." << endl;
if (numScales < 1) {
cout<< "Warning: There are no scales. Possibly the minimum size is larger than the image?" << endl;
}
int needsReset = 0;
for (int i = 0; i < numScales; i++) {
if (_PATCHLIST_DEBUG) cout << "For scale " << i << " needsReset is so far " << needsReset << endl;
if (i == 0 ) {
if (!images.empty()) {
if (_PATCHLIST_DEBUG) cout << "Replacing old patch." << endl;
//checking for a change in image size or underlying memory structure
const integral_type* previousIntegral = images[i]->startOfIntegralData();
Size s1 = images[i]->getImageSize();
images[i]->setImage(img,copyImageData,1);
Size s2 = images[i]->getImageSize();
if (s1.width != s2.width || s1.height != s2.height ||
previousIntegral != images[i]->startOfIntegralData() ){
if (_PATCHLIST_DEBUG) {
if (s1.width != s2.width)
cout << "Needs reset because image width at scale " << i
<< " changed from " << s1.width << " to "
<< s2.width << endl;
if (s1.height != s2.height)
cout << "Needs reset because image height at scale " << i
<< " changed from " << s1.height << " to "
<< s2.height << endl;
if (previousIntegral != images[i]->startOfIntegralData())
cout << "Needs reset because integral pointer at scale " << i
<< " changed from " << (void*)previousIntegral << " to "
<< (void*)images[i]->startOfIntegralData()<< endl;
}
needsReset = 1;
}
} else {
images.push_back(new ImagePatch());
images[0]->setImage(img,copyImageData,1);
needsReset = 1;
}
} else if ((unsigned int) i < images.size()) {
images[i] = images[0];
} else {
//cout << "Adding new one." << endl;
images.push_back(images[0]);
needsReset = 1;
}
}
return needsReset;
}
| [
"christian.frisson@gmail.com"
] | christian.frisson@gmail.com |
f950f1654162ea62c0f16b142cab3fdda0a54051 | cbd3ac62b75ac3dceb6ffb219eaa3fe9d2ef0c00 | /src/base/test/gtest_xml_util.h | 3775b7831770951a810cc0a08dbc55549db7f40d | [
"BSD-3-Clause"
] | permissive | crazypeace/naiveproxy | d403fa282bcf65cac3eacb519667d6767080d05d | 0a8242dca02b760272d4a0eb8f8a712f9d1093c4 | refs/heads/master | 2023-03-09T21:23:30.415305 | 2022-10-06T17:23:40 | 2022-10-06T17:23:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 830 | h | // Copyright 2013 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.
#ifndef BASE_TEST_GTEST_XML_UTIL_H_
#define BASE_TEST_GTEST_XML_UTIL_H_
#include <vector>
namespace base {
class FilePath;
struct TestResult;
// Produces a vector of test results based on GTest output file.
// Returns true iff the output file exists and has been successfully parsed.
// On successful return and if non-null, |crashed| is set to true if the test
// results are valid but incomplete.
[[nodiscard]] bool ProcessGTestOutput(const base::FilePath& output_file,
std::vector<TestResult>* results,
bool* crashed);
} // namespace base
#endif // BASE_TEST_GTEST_XML_UTIL_H_
| [
"kizdiv@gmail.com"
] | kizdiv@gmail.com |
285c592161eae7c5bca0d84c0d4a2d8769e892f1 | 31bd4984f3cb44e1292321895cec5ff5d993aac6 | /addons/ofxCvOpticalFlowLK/ofxCvOpticalFlowLK.h | 347b87e34c06c58308b321ef9e5db4929a723d3c | [
"MIT"
] | permissive | HellicarAndLewis/Triptych | a221a1cd58d9232ca58adbaad5f3610eba6547eb | 866e865f60ddd24efee57a6a8904567669ff71a4 | refs/heads/master | 2020-12-24T15:31:57.395363 | 2013-12-12T13:30:49 | 2013-12-12T13:30:49 | 4,615,958 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,954 | h | //
// ofxCvOpticalFlowLK.h - a OpenCV cvOpticalFlowLK warpper for openFrameworks
//
// Copyright (C) 2008 Takashi Maekawa <takachin@generative.info>
// All rights reserved.
// This is free software with ABSOLUTELY NO WARRANTY.
//
// You can redistribute it and/or modify it under the terms of
// the GNU Lesser General Public License.
//
#pragma once
#include "ofMain.h"
#include "ofxCvConstants.h"
#include "ofxCvGrayscaleImage.h"
class ofxCvOpticalFlowLK: public ofBaseDraws
{
public:
ofxCvOpticalFlowLK(void);
~ofxCvOpticalFlowLK(void);
void allocate(int _w, int _h);
void calc( ofxCvGrayscaleImage & pastImage, ofxCvGrayscaleImage & currentImage, int size);
void setCalcStep(int _cols, int _rows);
void reset();
void draw();
float getTotalMovement();
void draw(float x,float y) {
glPushMatrix();
glTranslatef(x, y, 0);
draw();
glPopMatrix();
}
bool forceAtPos(const ofVec2f &pos, ofVec2f &force) {
if(pos.x<captureWidth && pos.y < captureHeight && pos.x>=0 && pos.y>=0) {
force.x = cvGetReal2D(vel_x, pos.y, pos.x);
force.y = cvGetReal2D(vel_y, pos.y, pos.x);
return true;
} else {
return false;
}
}
void forceAtPos(float x, float y, float *dx, float *dy) {
if(x<captureWidth && y<captureHeight && x>=0 && y>=0) {
*dx = cvGetReal2D( vel_x, y, x );
*dy = cvGetReal2D( vel_y, y, x );
}
}
void draw(float x,float y,float w, float h) {
glPushMatrix();
glScalef(w/captureWidth, h/captureHeight, 1);
draw(x, y);
glPopMatrix();
}
int captureWidth;
int captureHeight;
IplImage* vel_x;
IplImage* vel_y;
float getWidth() { return captureWidth; }
float getHeight() { return captureHeight; }
static const int DEFAULT_CAPTURE_WIDTH = 320;
static const int DEFAULT_CAPTURE_HEIGHT = 240;
static const int DEFAULT_CAPTURE_COLS_STEP = 4;
static const int DEFAULT_CAPTURE_ROWS_STEP = 4;
int captureColsStep;
int captureRowsStep;
void blur(int flowBlur);
};
| [
"bereza@gmail.com"
] | bereza@gmail.com |
50053933b108a29f1ac88da62ede16a2596d85d9 | 1e9951acb23fbc230735df97bcb84d0c2e46a623 | /EEPROM1.ino.ino | ce9c5f0e48eb9b7a839ecf72417cdd39ad141444 | [] | no_license | Rokkee/EEPROM-arduino- | b575a33643332fe561ef0be1536d63d5636e472b | 682522e8b45dbd6629f60ec2403af37071342b1b | refs/heads/master | 2020-03-28T15:18:13.847874 | 2018-09-13T03:42:49 | 2018-09-13T03:42:49 | 148,578,026 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | ino | #include <EEPROM.h>
int direccion=0;
byte val1;
byte val2;
void setup() {
Serial.begin(9600);
byte informacion=b11001;
int valor=analogRead(0);
EEPROM.write(direccion,informacion);
EEPROM.write(direccion+1,valor);
}
void loop() {
EEPROM.read(direccion);
EEPROM.read(direccion+1);
Serial.print("En la direccion esta:");
Serial.print(direccion);
Serial.print("Se encuentra);
Serial.print(val1,DEC);
delay(100);
}
| [
"noreply@github.com"
] | Rokkee.noreply@github.com |
3e7ad41fb531cd7880edde73953569f83d0f00fa | 527421f3589e943db64c476656927c62829d1524 | /kernel/lib/userboot/userboot.cpp | dadb16b238c4305342cfd39eb98d444f0c0619cf | [] | no_license | wahwahwinner/smartnix | 5e0d0248ed8eaeb38d51a4b44c41eaa21d9c9b59 | f3aa1cc8873ec08f3ea7d66713843d3fdbebd7b5 | refs/heads/master | 2020-04-28T21:01:49.414154 | 2019-03-04T03:58:26 | 2019-03-04T03:58:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,371 | cpp |
#include <assert.h>
#include <err.h>
#include <inttypes.h>
#include <platform.h>
#include <trace.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <kernel/cmdline.h>
#include <vm/vm_object_paged.h>
#include <lib/console.h>
#include <lib/vdso.h>
#include <lk/init.h>
#include <mexec.h>
#include <object/channel_dispatcher.h>
#include <object/handle.h>
#include <object/job_dispatcher.h>
#include <object/message_packet.h>
#include <object/process_dispatcher.h>
#include <object/resource_dispatcher.h>
#include <object/thread_dispatcher.h>
#include <object/vm_address_region_dispatcher.h>
#include <object/vm_object_dispatcher.h>
#include <zircon/processargs.h>
#include <zircon/stack.h>
#if ENABLE_ENTROPY_COLLECTOR_TEST
#include <lib/crypto/entropy/quality_test.h>
#endif
static const size_t stack_size = ZIRCON_DEFAULT_STACK_SIZE;
#define STACK_VMO_NAME "userboot-initial-stack"
#define RAMDISK_VMO_NAME "userboot-raw-ramdisk"
#define CRASHLOG_VMO_NAME "crashlog"
namespace {
#include "userboot-code.h"
// This is defined in assembly by userboot-image.S; userboot-code.h
// gives details about the image's size and layout.
extern "C" const char userboot_image[];
class UserbootImage : private RoDso {
public:
explicit UserbootImage(const VDso* vdso)
: RoDso("userboot", userboot_image,
USERBOOT_CODE_END, USERBOOT_CODE_START),
vdso_(vdso) {}
// The whole userboot image consists of the userboot rodso image
// immediately followed by the vDSO image. This returns the size
// of that combined image.
size_t size() const {
return RoDso::size() + vdso_->size();
}
zx_status_t Map(fbl::RefPtr<VmAddressRegionDispatcher> root_vmar,
uintptr_t* vdso_base, uintptr_t* entry) {
// Create a VMAR (placed anywhere) to hold the combined image.
fbl::RefPtr<VmAddressRegionDispatcher> vmar;
zx_rights_t vmar_rights;
zx_status_t status = root_vmar->Allocate(0, size(),
ZX_VM_CAN_MAP_READ |
ZX_VM_CAN_MAP_WRITE |
ZX_VM_CAN_MAP_EXECUTE |
ZX_VM_CAN_MAP_SPECIFIC,
&vmar, &vmar_rights);
if (status != ZX_OK)
return status;
// Map userboot proper.
status = RoDso::Map(vmar, 0);
if (status == ZX_OK) {
*entry = vmar->vmar()->base() + USERBOOT_ENTRY;
// Map the vDSO right after it.
*vdso_base = vmar->vmar()->base() + RoDso::size();
status = vdso_->Map(fbl::move(vmar), RoDso::size());
}
return status;
}
private:
const VDso* vdso_;
};
} // anonymous namespace
// Get a handle to a VM object, with full rights except perhaps for writing.
static zx_status_t get_vmo_handle(fbl::RefPtr<VmObject> vmo, bool readonly,
fbl::RefPtr<VmObjectDispatcher>* disp_ptr,
Handle** ptr) {
if (!vmo)
return ZX_ERR_NO_MEMORY;
zx_rights_t rights;
fbl::RefPtr<Dispatcher> dispatcher;
zx_status_t result = VmObjectDispatcher::Create(
fbl::move(vmo), &dispatcher, &rights);
if (result == ZX_OK) {
if (disp_ptr)
*disp_ptr = fbl::RefPtr<VmObjectDispatcher>::Downcast(dispatcher);
if (readonly)
rights &= ~ZX_RIGHT_WRITE;
if (ptr)
*ptr = Handle::Make(fbl::move(dispatcher), rights).release();
}
return result;
}
static zx_status_t get_job_handle(Handle** ptr) {
zx_rights_t rights;
fbl::RefPtr<Dispatcher> dispatcher;
zx_status_t result = JobDispatcher::Create(
0u, GetRootJobDispatcher(), &dispatcher, &rights);
if (result == ZX_OK)
*ptr = Handle::Make(fbl::move(dispatcher), rights).release();
return result;
}
static zx_status_t get_resource_handle(Handle** ptr) {
zx_rights_t rights;
fbl::RefPtr<ResourceDispatcher> root;
zx_status_t result = ResourceDispatcher::Create(&root, &rights, ZX_RSRC_KIND_ROOT, 0, 0, 0,
"root");
if (result == ZX_OK)
*ptr = Handle::Make(fbl::RefPtr<Dispatcher>(root.get()),
rights).release();
return result;
}
// Create a channel and write the bootstrap message down one side of
// it, returning the handle to the other side.
static zx_status_t make_bootstrap_channel(
fbl::RefPtr<ProcessDispatcher> process,
fbl::unique_ptr<MessagePacket> msg,
zx_handle_t* out) {
HandleOwner user_channel_handle;
fbl::RefPtr<ChannelDispatcher> kernel_channel;
*out = ZX_HANDLE_INVALID;
{
fbl::RefPtr<Dispatcher> mpd0, mpd1;
zx_rights_t rights;
zx_status_t status = ChannelDispatcher::Create(&mpd0, &mpd1, &rights);
if (status != ZX_OK)
return status;
user_channel_handle = Handle::Make(fbl::move(mpd0), rights);
kernel_channel = DownCastDispatcher<ChannelDispatcher>(&mpd1);
}
// Here it goes!
zx_status_t status = kernel_channel->Write(ZX_KOID_INVALID, fbl::move(msg));
if (status != ZX_OK)
return status;
zx_handle_t hv = process->MapHandleToValue(user_channel_handle);
process->AddHandle(fbl::move(user_channel_handle));
*out = hv;
return ZX_OK;
}
enum bootstrap_handle_index {
BOOTSTRAP_VDSO,
BOOTSTRAP_VDSO_LAST_VARIANT = BOOTSTRAP_VDSO + VDso::variants() - 1,
BOOTSTRAP_RAMDISK,
BOOTSTRAP_RESOURCE_ROOT,
BOOTSTRAP_STACK,
BOOTSTRAP_PROC,
BOOTSTRAP_THREAD,
BOOTSTRAP_JOB,
BOOTSTRAP_VMAR_ROOT,
BOOTSTRAP_CRASHLOG,
#if ENABLE_ENTROPY_COLLECTOR_TEST
BOOTSTRAP_ENTROPY_FILE,
#endif
BOOTSTRAP_HANDLES
};
struct bootstrap_message {
zx_proc_args_t header;
uint32_t handle_info[BOOTSTRAP_HANDLES];
char cmdline[CMDLINE_MAX];
};
static fbl::unique_ptr<MessagePacket> prepare_bootstrap_message() {
const size_t data_size =
offsetof(struct bootstrap_message, cmdline) +
__kernel_cmdline_size;
bootstrap_message* msg =
static_cast<bootstrap_message*>(malloc(data_size));
if (msg == nullptr) {
return nullptr;
}
memset(&msg->header, 0, sizeof(msg->header));
msg->header.protocol = ZX_PROCARGS_PROTOCOL;
msg->header.version = ZX_PROCARGS_VERSION;
msg->header.environ_off = offsetof(struct bootstrap_message, cmdline);
msg->header.environ_num = static_cast<uint32_t>(__kernel_cmdline_count);
msg->header.handle_info_off =
offsetof(struct bootstrap_message, handle_info);
for (int i = 0; i < BOOTSTRAP_HANDLES; ++i) {
uint32_t info = 0;
switch (static_cast<bootstrap_handle_index>(i)) {
case BOOTSTRAP_VDSO ... BOOTSTRAP_VDSO_LAST_VARIANT:
info = PA_HND(PA_VMO_VDSO, i - BOOTSTRAP_VDSO);
break;
case BOOTSTRAP_RAMDISK:
info = PA_HND(PA_VMO_BOOTDATA, 0);
break;
case BOOTSTRAP_RESOURCE_ROOT:
info = PA_HND(PA_RESOURCE, 0);
break;
case BOOTSTRAP_STACK:
info = PA_HND(PA_VMO_STACK, 0);
break;
case BOOTSTRAP_PROC:
info = PA_HND(PA_PROC_SELF, 0);
break;
case BOOTSTRAP_THREAD:
info = PA_HND(PA_THREAD_SELF, 0);
break;
case BOOTSTRAP_JOB:
info = PA_HND(PA_JOB_DEFAULT, 0);
break;
case BOOTSTRAP_VMAR_ROOT:
info = PA_HND(PA_VMAR_ROOT, 0);
break;
case BOOTSTRAP_CRASHLOG:
info = PA_HND(PA_VMO_KERNEL_FILE, 0);
break;
#if ENABLE_ENTROPY_COLLECTOR_TEST
case BOOTSTRAP_ENTROPY_FILE:
info = PA_HND(PA_VMO_KERNEL_FILE, 1);
break;
#endif
case BOOTSTRAP_HANDLES:
__builtin_unreachable();
}
msg->handle_info[i] = info;
}
memcpy(msg->cmdline, __kernel_cmdline, __kernel_cmdline_size);
fbl::unique_ptr<MessagePacket> packet;
uint32_t num_handles = BOOTSTRAP_HANDLES;
zx_status_t status =
MessagePacket::Create(msg, static_cast<uint32_t>(data_size), num_handles, &packet);
free(msg);
if (status != ZX_OK) {
return nullptr;
}
return packet;
}
static void clog_to_vmo(const void* data, size_t off, size_t len, void* cookie) {
VmObject* vmo = static_cast<VmObject*>(cookie);
vmo->Write(data, off, len);
}
// Converts platform crashlog into a VMO
static zx_status_t crashlog_to_vmo(fbl::RefPtr<VmObject>* out) {
size_t size = platform_recover_crashlog(0, NULL, NULL);
fbl::RefPtr<VmObject> crashlog_vmo;
zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, size, &crashlog_vmo);
if (status != ZX_OK) {
return status;
}
platform_recover_crashlog(size, crashlog_vmo.get(), clog_to_vmo);
crashlog_vmo->set_name(CRASHLOG_VMO_NAME, sizeof(CRASHLOG_VMO_NAME) - 1);
mexec_stash_crashlog(crashlog_vmo);
*out = fbl::move(crashlog_vmo);
return ZX_OK;
}
static zx_status_t attempt_userboot() {
size_t rsize;
void* rbase = platform_get_ramdisk(&rsize);
if (rbase)
dprintf(INFO, "userboot: ramdisk %#15zx @ %p\n", rsize, rbase);
fbl::RefPtr<VmObject> stack_vmo;
zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, stack_size, &stack_vmo);
if (status != ZX_OK)
return status;
stack_vmo->set_name(STACK_VMO_NAME, sizeof(STACK_VMO_NAME) - 1);
fbl::RefPtr<VmObject> rootfs_vmo;
status = VmObjectPaged::CreateFromROData(rbase, rsize, &rootfs_vmo);
if (status != ZX_OK)
return status;
rootfs_vmo->set_name(RAMDISK_VMO_NAME, sizeof(RAMDISK_VMO_NAME) - 1);
fbl::RefPtr<VmObject> crashlog_vmo;
status = crashlog_to_vmo(&crashlog_vmo);
if (status != ZX_OK)
return status;
// Prepare the bootstrap message packet. This puts its data (the
// kernel command line) in place, and allocates space for its handles.
// We'll fill in the handles as we create things.
fbl::unique_ptr<MessagePacket> msg = prepare_bootstrap_message();
if (!msg)
return ZX_ERR_NO_MEMORY;
Handle** const handles = msg->mutable_handles();
DEBUG_ASSERT(msg->num_handles() == BOOTSTRAP_HANDLES);
status = get_vmo_handle(rootfs_vmo, false, nullptr,
&handles[BOOTSTRAP_RAMDISK]);
fbl::RefPtr<VmObjectDispatcher> stack_vmo_dispatcher;
if (status == ZX_OK)
status = get_vmo_handle(stack_vmo, false, &stack_vmo_dispatcher,
&handles[BOOTSTRAP_STACK]);
if (status == ZX_OK)
status = get_vmo_handle(crashlog_vmo, true, nullptr,
&handles[BOOTSTRAP_CRASHLOG]);
if (status == ZX_OK)
status = get_resource_handle(&handles[BOOTSTRAP_RESOURCE_ROOT]);
if (status == ZX_OK)
status = get_job_handle(&handles[BOOTSTRAP_JOB]);
#if ENABLE_ENTROPY_COLLECTOR_TEST
if (status == ZX_OK) {
if (crypto::entropy::entropy_was_lost) {
status = ZX_ERR_INTERNAL;
} else {
status = get_vmo_handle(
crypto::entropy::entropy_vmo,
/* readonly */ true, /* disp_ptr */ nullptr,
&handles[BOOTSTRAP_ENTROPY_FILE]);
}
}
#endif
if (status != ZX_OK)
return status;
fbl::RefPtr<Dispatcher> proc_disp;
fbl::RefPtr<VmAddressRegionDispatcher> vmar;
zx_rights_t rights, vmar_rights;
status = ProcessDispatcher::Create(GetRootJobDispatcher(), "userboot", 0,
&proc_disp, &rights,
&vmar, &vmar_rights);
if (status != ZX_OK)
return status;
handles[BOOTSTRAP_PROC] = Handle::Make(proc_disp, rights).release();
auto proc = DownCastDispatcher<ProcessDispatcher>(&proc_disp);
ASSERT(proc);
handles[BOOTSTRAP_VMAR_ROOT] = Handle::Make(vmar, vmar_rights).release();
const VDso* vdso = VDso::Create();
for (size_t i = BOOTSTRAP_VDSO; i <= BOOTSTRAP_VDSO_LAST_VARIANT; ++i) {
HandleOwner vmo_handle =
vdso->vmo_handle(static_cast<VDso::Variant>(i - BOOTSTRAP_VDSO));
handles[i] = vmo_handle.release();
}
UserbootImage userboot(vdso);
uintptr_t vdso_base = 0;
uintptr_t entry = 0;
status = userboot.Map(vmar, &vdso_base, &entry);
if (status != ZX_OK)
return status;
// Map the stack anywhere.
fbl::RefPtr<VmMapping> stack_mapping;
status = vmar->Map(0,
fbl::move(stack_vmo), 0, stack_size,
ZX_VM_PERM_READ | ZX_VM_PERM_WRITE,
&stack_mapping);
if (status != ZX_OK)
return status;
uintptr_t stack_base = stack_mapping->base();
uintptr_t sp = compute_initial_stack_pointer(stack_base, stack_size);
// Create the user thread and stash its handle for the bootstrap message.
fbl::RefPtr<ThreadDispatcher> thread;
{
fbl::RefPtr<Dispatcher> ut_disp;
// Make a copy of proc, as we need to a keep a copy for the
// bootstrap message.
status = ThreadDispatcher::Create(proc, 0, "userboot", &ut_disp, &rights);
if (status != ZX_OK)
return status;
handles[BOOTSTRAP_THREAD] = Handle::Make(ut_disp, rights).release();
thread = DownCastDispatcher<ThreadDispatcher>(&ut_disp);
}
DEBUG_ASSERT(thread);
// All the handles are in place, so we can send the bootstrap message.
zx_handle_t hv;
status = make_bootstrap_channel(proc, fbl::move(msg), &hv);
if (status != ZX_OK)
return status;
dprintf(SPEW, "userboot: %-23s @ %#" PRIxPTR "\n", "entry point", entry);
// Start the process's initial thread.
status = thread->Start(entry, sp, static_cast<uintptr_t>(hv), vdso_base,
/* initial_thread= */ true);
if (status != ZX_OK) {
printf("userboot: failed to start initial thread: %d\n", status);
return status;
}
return ZX_OK;
}
void userboot_init(uint level) {
attempt_userboot();
}
LK_INIT_HOOK(userboot, userboot_init, LK_INIT_LEVEL_USER);
| [
"376305680@qq.com"
] | 376305680@qq.com |
250b55c4b52f80dd481ed51feccebba13a44471b | d4058e13d7c5310cfbd889deecc27f9acdea9ea4 | /addcompilerwizard.h | 4f1109159d46a9e87fd3e51b30517d87df3053ef | [] | no_license | FreestyleOJ/Project_lemon | 24f95d5f6d6b55f7869f32ea39edcac403c3b984 | eda202936e40cf282b667fb106d5f2528daf9f59 | refs/heads/master | 2020-04-01T13:40:46.122735 | 2015-10-21T15:13:11 | 2015-10-21T15:13:11 | 43,739,368 | 7 | 5 | null | 2015-10-06T08:45:49 | 2015-10-06T08:45:49 | null | UTF-8 | C++ | false | false | 910 | h | #ifndef ADDCOMPILERWIZARD_H
#define ADDCOMPILERWIZARD_H
#include <QtCore>
#include <QtGui>
#include <QWizard>
namespace Ui {
class AddCompilerWizard;
}
class Compiler;
class AddCompilerWizard : public QWizard
{
Q_OBJECT
public:
explicit AddCompilerWizard(QWidget *parent = 0);
~AddCompilerWizard();
void accept();
const QList<Compiler*>& getCompilerList() const;
private:
Ui::AddCompilerWizard *ui;
QList<Compiler*> compilerList;
int nextId() const;
bool validateCurrentPage();
private slots:
void compilerTypeChanged();
void selectCompilerLocation();
void selectInterpreterLocation();
void selectGccPath();
void selectGppPath();
void selectFpcPath();
void selectFbcPath();
void selectJavacPath();
void selectJavaPath();
void selectPythonPath();
};
#endif // ADDCOMPILERWIZARD_H
| [
"crash@crash-VPCEA18EC.(none)"
] | crash@crash-VPCEA18EC.(none) |
23928343da043ac8061eb177addd7a2099c891f5 | 13f44a504648dc91869dfa9027c2f699949bae53 | /db/compaction.cpp | 584468b3255868526dc8a96ccd20061829d4789e | [
"BSD-3-Clause"
] | permissive | sarthakdadhakar/power-of-d | e90d8fb951d4350baf41506940c32bafa5718770 | 6c4be0a1b1242f267a92df24db407b1feffaa2a4 | refs/heads/main | 2023-01-21T08:45:02.069191 | 2020-11-18T03:28:40 | 2020-11-18T03:28:40 | 310,158,009 | 0 | 0 | BSD-3-Clause | 2020-11-05T01:23:05 | 2020-11-05T01:23:04 | null | UTF-8 | C++ | false | false | 23,009 | cpp |
//
// Created by Haoyu Huang on 5/4/20.
// Copyright (c) 2020 University of Southern California. All rights reserved.
//
#include "compaction.h"
#include "filename.h"
namespace leveldb {
void
FetchMetadataFilesInParallel(const std::vector<const FileMetaData *> &files,
const std::string &dbname,
const Options &options,
StoCBlockClient *client,
Env *env) {
uint32_t fetched_files = 0;
std::vector<const FileMetaData *> batch;
for (int i = 0; i < files.size(); i++) {
if (batch.size() == FETCH_METADATA_BATCH_SIZE &&
files.size() - i > FETCH_METADATA_BATCH_SIZE) {
fetched_files += batch.size();
FetchMetadataFiles(batch, dbname, options, client, env);
batch.clear();
}
batch.push_back(files[i]);
}
if (!batch.empty()) {
fetched_files += batch.size();
FetchMetadataFiles(batch, dbname, options, client, env);
}
NOVA_ASSERT(fetched_files == files.size());
}
void
FetchMetadataFiles(const std::vector<const FileMetaData *> &files,
const std::string &dbname, const Options &options,
StoCBlockClient *client, Env *env) {
// Fetch all metadata files in parallel.
char *backing_mems[files.size() * nova::NovaConfig::config->number_of_sstable_metadata_replicas];
int index = 0;
for (int i = 0; i < files.size(); i++) {
auto meta = files[i];
for (int replica_id = 0; replica_id < meta->block_replica_handles.size(); replica_id++) {
std::string filename = TableFileName(dbname, meta->number, FileInternalType::kFileMetadata, replica_id);
const StoCBlockHandle &meta_handle = meta->block_replica_handles[replica_id].meta_block_handle;
uint32_t backing_scid = options.mem_manager->slabclassid(0, meta_handle.size);
char *backing_buf = options.mem_manager->ItemAlloc(0, backing_scid);
memset(backing_buf, 0, meta_handle.size);
NOVA_LOG(rdmaio::DEBUG)
<< fmt::format("Fetch metadata blocks {} handle:{}", filename, meta->DebugString());
uint32_t req_id = client->InitiateReadDataBlock(meta_handle, 0, meta_handle.size, backing_buf,
meta_handle.size, "", false);
backing_mems[index] = backing_buf;
index++;
}
}
for (int i = 0; i < files.size(); i++) {
auto meta = files[i];
for (int replica_id = 0; replica_id < meta->block_replica_handles.size(); replica_id++) {
client->Wait();
}
}
index = 0;
for (int i = 0; i < files.size(); i++) {
auto meta = files[i];
for (int replica_id = 0; replica_id < meta->block_replica_handles.size(); replica_id++) {
char *backing_buf = backing_mems[index];
const StoCBlockHandle &meta_handle = meta->block_replica_handles[replica_id].meta_block_handle;
uint32_t backing_scid = options.mem_manager->slabclassid(0, meta_handle.size);
WritableFile *writable_file;
EnvFileMetadata env_meta = {};
auto sstablename = TableFileName(dbname, meta->number, FileInternalType::kFileData, replica_id);
Status s = env->NewWritableFile(sstablename, env_meta, &writable_file);
NOVA_ASSERT(s.ok());
Slice sstable_meta(backing_buf, meta_handle.size);
s = writable_file->Append(sstable_meta);
NOVA_ASSERT(s.ok());
s = writable_file->Flush();
NOVA_ASSERT(s.ok());
s = writable_file->Sync();
NOVA_ASSERT(s.ok());
s = writable_file->Close();
NOVA_ASSERT(s.ok());
delete writable_file;
writable_file = nullptr;
options.mem_manager->FreeItem(0, backing_buf, backing_scid);
index++;
}
}
}
Compaction::Compaction(VersionFileMap *input_version,
const InternalKeyComparator *icmp,
const Options *options, int level, int target_level)
: level_(level),
target_level_(target_level),
icmp_(icmp),
options_(options),
max_output_file_size_(options->max_file_size),
input_version_(input_version),
grandparent_index_(0),
seen_key_(false),
overlapped_bytes_(0) {
is_completed_ = false;
level_ptrs_.resize(options->level);
for (int i = 0; i < options->level; i++) {
level_ptrs_[i] = 0;
}
}
std::string Compaction::DebugString(const Comparator *user_comparator) {
Slice smallest = {};
Slice largest = {};
std::string files;
for (int which = 0; which < 2; which++) {
for (auto file : inputs_[which]) {
if (smallest.empty() ||
user_comparator->Compare(file->smallest.user_key(),
smallest) < 0) {
smallest = file->smallest.user_key();
}
if (largest.empty() ||
user_comparator->Compare(file->largest.user_key(),
largest) > 0) {
largest = file->largest.user_key();
}
files += file->ShortDebugString();
files += ",";
}
}
std::string debug = fmt::format("{}@{} + {}@{} s:{} l:{} {} {}",
inputs_[0].size(), level_,
inputs_[1].size(), target_level_,
smallest.ToString(), largest.ToString(),
files, grandparents_.size());
return debug;
}
bool Compaction::IsTrivialMove() const {
// Avoid a move if there is lots of overlapping grandparent data.
// Otherwise, the move could create a parent file that will require
// a very expensive merge later on.
return (num_input_files(0) == 1 && num_input_files(1) == 0 &&
level_ != target_level_);
// &&
// TotalFileSize(grandparents_) <=
// MaxGrandParentOverlapBytes(options_));
}
void Compaction::AddInputDeletions(VersionEdit *edit) {
for (int which = 0; which < 2; which++) {
for (size_t i = 0; i < inputs_[which].size(); i++) {
int delete_level = level_ + which;
auto *f = inputs_[which][i];
edit->DeleteFile(delete_level, f->number);
}
}
}
bool Compaction::ShouldStopBefore(const Slice &internal_key) {
// Scan to find earliest grandparent file that contains key.
while (grandparent_index_ < grandparents_.size() &&
icmp_->Compare(internal_key,
grandparents_[grandparent_index_]->largest.Encode()) >
0) {
if (seen_key_) {
overlapped_bytes_ += 1; //grandparents_[grandparent_index_]->file_size;
}
grandparent_index_++;
}
seen_key_ = true;
int max_overlap = 5;
max_overlap = std::min(max_overlap, (int) grandparents_.size() / 4);
max_overlap = std::max(max_overlap, 1);
if (overlapped_bytes_ >= max_overlap) {
// Too much overlap for current output; start new output
overlapped_bytes_ = 0;
return true;
} else {
return false;
}
}
CompactionStats CompactionState::BuildStats() {
CompactionStats stats;
stats.input_source.num_files = compaction->num_input_files(0);
stats.input_source.level = compaction->level();
stats.input_source.file_size = compaction->num_input_file_sizes(0);
stats.input_target.num_files = compaction->num_input_files(1);
stats.input_target.level = compaction->target_level();
stats.input_target.file_size = compaction->num_input_file_sizes(1);
return stats;
}
CompactionJob::CompactionJob(std::function<uint64_t(void)> &fn_generator,
leveldb::Env *env, const std::string &dbname,
const leveldb::Comparator *user_comparator,
const leveldb::Options &options,
EnvBGThread *bg_thread,
TableCache *table_cache)
: fn_generator_(fn_generator), env_(env), dbname_(dbname),
user_comparator_(
user_comparator), options_(options),
bg_thread_(bg_thread), table_cache_(table_cache) {
}
Status CompactionJob::OpenCompactionOutputFile(CompactionState *compact) {
assert(compact != nullptr);
assert(compact->builder == nullptr);
uint64_t file_number;
{
file_number = fn_generator_();
FileMetaData out;
if (file_number == 0) {
std::string str;
if (compact->compaction) {
str = compact->compaction->DebugString(user_comparator_);
}
NOVA_ASSERT(false) << str;
}
out.number = file_number;
out.smallest.Clear();
out.largest.Clear();
compact->outputs.push_back(out);
}
// Make the output file
MemManager *mem_manager = bg_thread_->mem_manager();
std::string filename = TableFileName(dbname_, file_number, FileInternalType::kFileData, 0);
StoCWritableFileClient *stoc_writable_file = new StoCWritableFileClient(
options_.env,
options_,
file_number,
mem_manager,
bg_thread_->stoc_client(),
dbname_,
bg_thread_->thread_id(),
options_.max_stoc_file_size,
bg_thread_->rand_seed(),
filename);
compact->outfile = new MemWritableFile(stoc_writable_file);
compact->builder = new TableBuilder(options_, compact->outfile);
return Status::OK();
}
Status
CompactionJob::FinishCompactionOutputFile(const ParsedInternalKey &ik,
CompactionState *compact,
Iterator *input) {
assert(compact != nullptr);
assert(compact->outfile != nullptr);
assert(compact->builder != nullptr);
const uint64_t output_number = compact->current_output()->number;
assert(output_number != 0);
// Check for iterator errors
Status s = input->status();
if (s.ok()) {
s = compact->builder->Finish();
} else {
compact->builder->Abandon();
}
const uint64_t current_entries = compact->builder->NumEntries();
const uint64_t current_data_blocks = compact->builder->NumDataBlocks();
const uint64_t current_bytes = compact->builder->FileSize();
compact->current_output()->file_size = current_bytes;
compact->total_bytes += current_bytes;
delete compact->builder;
compact->builder = nullptr;
NOVA_LOG(rdmaio::DEBUG)
<< fmt::format("Close table-{} at {} bytes", output_number,
current_bytes);
FileMetaData meta;
meta.number = output_number;
meta.file_size = current_bytes;
meta.smallest = compact->current_output()->smallest;
meta.largest = compact->current_output()->largest;
// Set meta in order to flush to the corresponding DC node.
StoCWritableFileClient *mem_file = static_cast<StoCWritableFileClient *>(compact->outfile->mem_file());
mem_file->set_meta(meta);
mem_file->set_num_data_blocks(current_data_blocks);
// Finish and check for file errors
NOVA_ASSERT(s.ok()) << s.ToString();
s = compact->outfile->Sync();
s = compact->outfile->Close();
mem_file->WaitForPersistingDataBlocks();
{
FileMetaData *output = compact->current_output();
output->converted_file_size = mem_file->Finalize();
output->block_replica_handles = mem_file->replicas();
output->parity_block_handle = mem_file->parity_block_handle();
mem_file->Validate(output->block_replica_handles, output->parity_block_handle);
delete mem_file;
mem_file = nullptr;
delete compact->outfile;
compact->outfile = nullptr;
}
return s;
}
Status
CompactionJob::CompactTables(CompactionState *compact,
Iterator *input,
CompactionStats *stats, bool drop_duplicates,
CompactInputType input_type,
CompactOutputType output_type,
const std::function<void(
const ParsedInternalKey &ikey,
const Slice &value)> &add_to_memtable) {
const uint64_t start_micros = env_->NowMicros();
std::string output;
if (input_type == CompactInputType::kCompactInputMemTables) {
output = fmt::format(
"bg[{}] Flushing {} memtables",
bg_thread_->thread_id(),
stats->input_source.num_files);
} else {
output = fmt::format(
"bg[{}] Major Compacting {}@{} + {}@{} files",
bg_thread_->thread_id(),
stats->input_source.num_files,
stats->input_source.level,
stats->input_target.num_files,
stats->input_target.level);
Log(options_.info_log, "%s", output.c_str());
NOVA_LOG(rdmaio::INFO) << output;
}
assert(compact->builder == nullptr);
assert(compact->outfile == nullptr);
assert(compact->outputs.empty());
input->SeekToFirst();
Status status;
ParsedInternalKey ikey;
std::string current_user_key;
bool has_current_user_key = false;
SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
std::vector<std::string> keys;
uint64_t memtable_size = 0;
while (input->Valid()) {
Slice key = input->key();
NOVA_ASSERT(ParseInternalKey(key, &ikey));
if (output_type == kCompactOutputSSTables &&
compact->ShouldStopBefore(key, user_comparator_) &&
compact->builder != nullptr &&
compact->builder->NumEntries() > 0) {
status = FinishCompactionOutputFile(ikey, compact, input);
if (!status.ok()) {
break;
}
}
// Handle key/value, add to state, etc.
bool drop = false;
if (!has_current_user_key ||
user_comparator_->Compare(ikey.user_key,
Slice(current_user_key)) !=
0) {
// First occurrence of this user key
current_user_key.assign(ikey.user_key.data(),
ikey.user_key.size());
has_current_user_key = true;
last_sequence_for_key = kMaxSequenceNumber;
}
if (last_sequence_for_key <= compact->smallest_snapshot) {
// Hidden by an newer entry for same user key
drop = true; // (A)
}
last_sequence_for_key = ikey.sequence;
#if 0
Log(options_.info_log,
" Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
"%d smallest_snapshot: %d",
ikey.user_key.ToString().c_str(),
(int)ikey.sequence, ikey.type, kTypeValue, drop,
compact->compaction->IsBaseLevelForKey(ikey.user_key),
(int)last_sequence_for_key, (int)compact->smallest_snapshot);
#endif
if (drop && drop_duplicates) {
// RDMA_LOG(rdmaio::DEBUG)
// << fmt::format("drop key-{}", ikey.FullDebugString());
input->Next();
continue;
} else {
// Open output file if necessary
if (output_type == kCompactOutputSSTables &&
compact->builder == nullptr) {
status = OpenCompactionOutputFile(compact);
if (!status.ok()) {
break;
}
}
if (output_type == kCompactOutputSSTables &&
compact->builder->NumEntries() == 0) {
compact->current_output()->smallest.DecodeFrom(key);
}
// RDMA_LOG(rdmaio::DEBUG)
// << fmt::format("add key-{}", ikey.FullDebugString());
// keys.push_back(ikey.DebugString());
if (output_type == kCompactOutputSSTables) {
compact->current_output()->largest.DecodeFrom(key);
if (!compact->builder->Add(key, input->value())) {
std::string added_keys;
for (auto &k : keys) {
added_keys += k;
added_keys += "\n";
}
NOVA_ASSERT(false) << fmt::format("{}\n {}",
compact->compaction->DebugString(
user_comparator_),
added_keys);
}
} else {
NOVA_ASSERT(output_type == kCompactOutputMemTables);
add_to_memtable(ikey, input->value());
memtable_size +=
input->key().size() + input->value().size();
}
// Close output file if it is big enough
if (output_type == kCompactOutputSSTables &&
compact->builder->FileSize() >= options_.max_file_size) {
status = FinishCompactionOutputFile(ikey, compact, input);
if (!status.ok()) {
break;
}
}
}
input->Next();
}
if (output_type == kCompactOutputSSTables && status.ok() &&
compact->builder != nullptr) {
status = FinishCompactionOutputFile(ikey, compact, input);
}
if (status.ok()) {
status = input->status();
}
delete input;
input = nullptr;
stats->micros = env_->NowMicros() - start_micros;
if (output_type == CompactOutputType::kCompactOutputSSTables) {
for (size_t i = 0; i < compact->outputs.size(); i++) {
stats->output.file_size += compact->outputs[i].file_size;
stats->output.num_files += 1;
}
} else {
stats->output.num_files = 1;
stats->output.file_size = memtable_size;
}
if (input_type == CompactInputType::kCompactInputMemTables) {
output = fmt::format(
"bg[{}] Flushing {} memtables => {} files {} bytes {}",
bg_thread_->thread_id(),
stats->input_source.num_files,
stats->output.num_files,
stats->output.file_size,
output_type == kCompactOutputMemTables ? "memtable"
: "sstable");
} else {
const int src_level = compact->compaction->level();
const int dest_level = compact->compaction->target_level();
output = fmt::format(
"bg[{}]: Major Compacted {}@{} + {}@{} files => {} bytes",
bg_thread_->thread_id(),
compact->compaction->num_input_files(0),
src_level,
compact->compaction->num_input_files(1),
dest_level,
compact->total_bytes);
NOVA_LOG(rdmaio::INFO) << output;
Log(options_.info_log, "%s", output.c_str());
}
if (input_type == CompactInputType::kCompactInputMemTables) {
output = fmt::format(
"Flushing memtables stats,{},{},{},{},{}",
stats->input_source.num_files +
stats->input_target.num_files,
stats->input_source.file_size +
stats->input_target.file_size,
stats->output.num_files, stats->output.file_size,
stats->micros);
} else {
output = fmt::format("Major compaction stats,{},{},{},{},{}",
stats->input_source.num_files +
stats->input_target.num_files,
stats->input_source.file_size +
stats->input_target.file_size,
stats->output.num_files,
stats->output.file_size,
stats->micros);
NOVA_LOG(rdmaio::INFO) << output;
Log(options_.info_log, "%s", output.c_str());
}
// Remove input files from table cache.
if (table_cache_) {
if (compact->compaction) {
for (int which = 0; which < 2; which++) {
for (int i = 0;
i < compact->compaction->inputs_[which].size(); i++) {
auto f = compact->compaction->inputs_[which][i];
table_cache_->Evict(f->number, true);
}
}
}
}
if (compact->compaction) {
compact->compaction->is_completed_ = true;
if (compact->compaction->complete_signal_) {
sem_post(compact->compaction->complete_signal_);
}
}
return status;
}
} | [
"saru.dadkr@gmail.com"
] | saru.dadkr@gmail.com |
66bf6731d2b54181692cc3be4eae289983951821 | 82050f339441ed964202d8cf5252be757192d95e | /source/remote.cpp | f0f0c09200fd5d366c65018cb3e1477c193659e4 | [] | no_license | Raphaeloo/aquaExternal | e1844900776f09ea5e0d0c9a38a052cc94dfa952 | 0a2019843a324aed0a620f579e999e2b428c1fe0 | refs/heads/master | 2021-05-11T01:22:06.761162 | 2017-12-16T07:28:29 | 2017-12-16T07:28:29 | 118,326,482 | 1 | 0 | null | 2018-01-21T10:54:56 | 2018-01-21T10:54:56 | null | UTF-8 | C++ | false | false | 7,007 | cpp | #include "remote.h"
#define FINDPATTERN_CHUNKSIZE 0x1000
namespace remote
{
// Map Module
void* MapModuleMemoryRegion::find(Handle handle, const char* data, const char* pattern)
{
char buffer[FINDPATTERN_CHUNKSIZE];
size_t len = strlen(pattern);
size_t chunksize = sizeof(buffer);
size_t totalsize = this->end - this->start;
size_t chunknum = 0;
while (totalsize)
{
size_t readsize = (totalsize < chunksize) ? totalsize : chunksize;
size_t readaddr = this->start + (chunksize * chunknum);
bzero(buffer, chunksize);
if (handle.Read((void*) readaddr, buffer, readsize))
{
for (size_t b = 0; b < readsize; b++)
{
size_t matches = 0;
while (buffer[b + matches] == data[matches] || pattern[matches] != 'x')
{
matches++;
if (matches == len)
return (char*) (readaddr + b);
}
}
}
totalsize -= readsize;
chunknum++;
}
return NULL;
}
// Handle
Handle::Handle(pid_t target)
{
std::stringstream buffer;
buffer << target;
pid = target;
pidStr = buffer.str();
}
Handle::Handle(std::string target)
{
// Check to see if the string is numeric (no negatives or dec allowed, which makes this function usable)
if (strspn(target.c_str(), "0123456789") != target.size())
{
pid = -1;
pidStr.clear();
}
else
{
std::istringstream buffer(target);
pidStr = target;
buffer >> pid;
}
}
std::string Handle::GetPath()
{
return GetSymbolicLinkTarget(("/proc/" + pidStr + "/exe"));
}
std::string Handle::GetWorkingDirectory()
{
return GetSymbolicLinkTarget(("/proc/" + pidStr + "/cwd"));
}
bool Handle::IsValid()
{
return (pid != -1);
}
bool Handle::IsRunning()
{
if (!IsValid())
return false;
struct stat sts;
return !(stat(("/proc/" + pidStr).c_str(), &sts) == -1 && errno == ENOENT);
}
bool Handle::Write(void* address, void* buffer, size_t size)
{
struct iovec local[1];
struct iovec remote[1];
local[0].iov_base = buffer;
local[0].iov_len = size;
remote[0].iov_base = address;
remote[0].iov_len = size;
return (process_vm_writev(pid, local, 1, remote, 1, 0) == size);
}
bool Handle::Read(void* address, void* buffer, size_t size)
{
struct iovec local[1];
struct iovec remote[1];
local[0].iov_base = buffer;
local[0].iov_len = size;
remote[0].iov_base = address;
remote[0].iov_len = size;
return (process_vm_readv(pid, local, 1, remote, 1, 0) == size);
}
unsigned long Handle::GetCallAddress(void* address)
{
int code = 0;
if (Read((char*) address + 1, &code, sizeof(unsigned int)))
return (unsigned long)code + (unsigned long) address + 5;
return 0;
}
unsigned long Handle::GetAbsoluteAddress(void* address, int offset, int size)
{
int code = 0;
if(Read((char*) address + offset, &code, sizeof(unsigned int)))
return (unsigned long) address + code + size;
return 0;
}
MapModuleMemoryRegion* Handle::GetRegionOfAddress(void* address)
{
for (size_t i = 0; i < regions.size(); i++)
{
if (regions[i].start > (unsigned long) address && (regions[i].start + regions[i].end) <= (unsigned long) address)
return ®ions[i];
}
return NULL;
}
void Handle::ParseMaps()
{
regions.clear();
std::ifstream maps("/proc/" + pidStr + "/maps");
std::string line;
while (std::getline(maps, line))
{
std::istringstream iss(line);
std::string memorySpace, permissions, offset, device, inode;
if (iss >> memorySpace >> permissions >> offset >> device >> inode)
{
std::string pathname;
for (size_t ls = 0, i = 0; i < line.length(); i++)
{
if (line.substr(i, 1).compare(" ") == 0)
{
ls++;
if (ls == 5)
{
size_t begin = line.substr(i, line.size()).find_first_not_of(' ');
if (begin != -1)
pathname = line.substr(begin + i, line.size());
else
pathname.clear();
}
}
}
MapModuleMemoryRegion region;
size_t memorySplit = memorySpace.find_first_of('-');
size_t deviceSplit = device.find_first_of(':');
std::stringstream ss;
if (memorySplit != -1)
{
ss << std::hex << memorySpace.substr(0, memorySplit);
ss >> region.start;
ss.clear();
ss << std::hex << memorySpace.substr(memorySplit + 1, memorySpace.size());
ss >> region.end;
ss.clear();
}
if (deviceSplit != -1)
{
ss << std::hex << device.substr(0, deviceSplit);
ss >> region.deviceMajor;
ss.clear();
ss << std::hex << device.substr(deviceSplit + 1, device.size());
ss >> region.deviceMinor;
ss.clear();
}
ss << std::hex << offset;
ss >> region.offset;
ss.clear();
ss << inode;
ss >> region.inodeFileNumber;
region.readable = (permissions[0] == 'r');
region.writable = (permissions[1] == 'w');
region.executable = (permissions[2] == 'x');
region.shared = (permissions[3] != '-');
if (!pathname.empty())
{
region.pathname = pathname;
size_t fileNameSplit = pathname.find_last_of('/');
if (fileNameSplit != -1)
region.filename = pathname.substr(fileNameSplit + 1, pathname.size());
}
regions.push_back(region);
}
}
}
std::string Handle::GetSymbolicLinkTarget(std::string target)
{
char buf[PATH_MAX];
ssize_t len = ::readlink(target.c_str(), buf, sizeof(buf) - 1);
if (len != -1)
{
buf[len] = 0;
return std::string(buf);
}
return std::string();
}
};
unsigned long remote::getModule(const char * moduleName, pid_t pid)
{
char cmd[256];
FILE *maps;
unsigned long result = 0;
snprintf(cmd, 256, "grep \"%s\" /proc/%i/maps | head -n 1 | cut -d \"-\" -f1", moduleName, pid);
maps = popen(cmd, "r");
if (maps)
if (fscanf(maps, "%" SCNx64, &result));
pclose(maps);
return result;
}
// Functions Exported
bool remote::FindProcessByName(std::string name, remote::Handle* out)
{
if(out == NULL || name.empty())
return false;
struct dirent *dire;
DIR *dir = opendir("/proc/");
if (dir) {
while ((dire = readdir(dir)) != NULL)
{
if (dire->d_type != DT_DIR)
continue;
std::string mapsPath = ("/proc/" + std::string(dire->d_name) + "/maps");
if (access(mapsPath.c_str(), F_OK) == -1)
continue;
remote::Handle proc(dire->d_name);
if (!proc.IsValid() || !proc.IsRunning())
continue;
std::string procPath = proc.GetPath();
if(procPath.empty())
continue;
size_t namePos = procPath.find_last_of('/');
if(namePos == -1)
continue; // what?
std::string exeName = procPath.substr(namePos + 1);
if(exeName.compare(name) == 0)
{
*out = proc;
return true;
}
}
closedir(dir);
}
return false;
} | [
"filipeps3net@hotmail.com"
] | filipeps3net@hotmail.com |
9efb58ca2447e05ed1d9ba19e6c4dceec413c246 | b40d74a5fa41476509e4cf84e4c1bf0c96383879 | /InputCheck.cpp | 2ab052b6a09a727ea34edbdaa4dbfddaaa71f0dc | [] | no_license | jmrbug96/mycis277finalapp | 371333ffdae6215ca0d041dd44e57f23e5aa45db | d039962b97e70a9d3e0dbdffe67a584a51ac64a6 | refs/heads/master | 2020-04-20T16:50:16.344489 | 2019-04-30T18:50:35 | 2019-04-30T18:50:35 | 168,970,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 890 | cpp | #include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include "InputCheck.h"
using namespace std;
void InputCheck::checkInput(char &inVar, char reqIn1, char reqIn2, char reqIn3, char reqIn4){
//If input is not valid, give 3 attempts to enter valid input.
if(inVar != reqIn1 && inVar != reqIn2 && inVar != reqIn3 && inVar != reqIn4){
for(count = 3; count > 0; count--){
cout << "Invalid entry. Try again(" << count << " attempts remaining): ";
cin >> inVar;
//If input is valid within 3 attempts, break the loop.
if(inVar == reqIn1 || inVar == reqIn2 || inVar == reqIn3 || inVar == reqIn4){
break;
}
}
//If all 3 attempts are exhausted, exit the program.
if(count == 0){
cout << "All 3 attempts exhausted. Exiting program....." << endl;
exit(1);
}
}
}
| [
"noreply@github.com"
] | jmrbug96.noreply@github.com |
c14a022563a566a1d038bb525e67ea0bc694c5ec | 502a0c02e0a8e25a5277249f2595975bdcaabf4c | /Challenge280 - SOLVED/Challenge280/stdafx.cpp | 290110a8a856363e5cbca69ec1b00d7de31a9626 | [] | no_license | seanhouser/Daily_Challenges | 7e386cb3e30e795516b700963d1fe1b664a011b3 | de1f43424f70103c362c5bcee9563efac1d7a9ba | refs/heads/master | 2021-07-15T16:14:36.214786 | 2017-10-19T19:48:25 | 2017-10-19T19:48:25 | 43,339,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 291 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Challenge280.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"seanmhouser@gmail.com"
] | seanmhouser@gmail.com |
e48f9106829f23a9ab3205dbf714fa9728a22f79 | cecf6991e6007ee4bc32a82e438c9120b3826dad | /Ranking/Source/Updater.cpp | bdf78bd2f178877c4c5d61b255aa3c2fc2266d32 | [] | no_license | thinking2535/Rso | 172a3499400331439a530cab78934fa4c4433771 | 35d556463118825a1d5d36f49d46f18a05806169 | refs/heads/main | 2022-11-30T12:43:50.917063 | 2022-11-23T10:47:59 | 2022-11-23T10:47:59 | 31,525,549 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49 | cpp | #include "Updater.h"
namespace rso::ranking
{
}
| [
"thinking2535@gmail.com"
] | thinking2535@gmail.com |
b72d7a0782028668ce0d0ce9826ec15dc97d1d3a | f9946f5d1283deece81f886de81b60829d7ca205 | /include/shared_data.h | ef0de2b5abf6a548676d908e3939681cd9324800 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | mg-code/tilemaker | 01843f9d862114a25807b3acb695cd24f6731ac9 | b1f326108ca33f6cc6e5f48cac9a3e10272d686a | refs/heads/master | 2020-03-22T21:54:18.602973 | 2018-07-13T07:45:26 | 2018-07-13T07:45:26 | 140,720,612 | 0 | 0 | null | 2018-07-12T13:59:32 | 2018-07-12T13:59:31 | null | UTF-8 | C++ | false | false | 1,353 | h | #ifndef _SHARED_DATA_H
#define _SHARED_DATA_H
#include <vector>
#include <map>
#include "rapidjson/document.h"
#include "osm_store.h"
#include "output_object.h"
#include "osm_object.h"
#include "mbtiles.h"
class Config
{
public:
std::vector<LayerDef> layers; // List of layers
std::map<std::string,uint> layerMap; // Layer->position map
std::vector<std::vector<uint> > layerOrder; // Order of (grouped) layers, e.g. [ [0], [1,2,3], [4] ]
uint baseZoom, startZoom, endZoom;
uint mvtVersion;
bool includeID, compress, gzip;
std::string compressOpt;
bool clippingBoxFromJSON;
double minLon, minLat, maxLon, maxLat;
std::string projectName, projectVersion, projectDesc;
std::string defaultView;
std::vector<Geometry> cachedGeometries; // prepared boost::geometry objects (from shapefiles)
Config();
virtual ~Config();
void readConfig(rapidjson::Document &jsonConfig, bool hasClippingBox, Box &clippingBox,
std::map< uint, std::vector<OutputObject> > &tileIndex, OSMObject &osmObject);
};
class SharedData
{
public:
uint zoom;
int threadNum;
OSMStore *osmStore;
bool verbose;
bool sqlite;
MBTiles mbtiles;
std::string outputFile;
std::map< uint, std::vector<OutputObject> > *tileIndexForZoom;
class Config config;
SharedData(OSMStore *osmStore);
virtual ~SharedData();
};
#endif //_SHARED_DATA_H
| [
"tim2009@sheerman-chase.org.uk"
] | tim2009@sheerman-chase.org.uk |
7fc709b06e020795d6c55c0ae0a7312148d2fa69 | 77c518b87e67e9926d130f856a7edb12302596eb | /Filters/Sources/vtkPolyPointSource.h | 7abdc80b8338fa6d3ccda5dca20059b61a23a61b | [
"BSD-3-Clause"
] | permissive | t3dbrida/VTK | 73e308baa1e779f208421a728a4a15fec5c4f591 | e944bac3ba12295278dcbfa5d1cd7e71d6457bef | refs/heads/master | 2023-08-31T21:01:58.375533 | 2019-09-23T06:43:00 | 2019-09-23T06:43:00 | 139,547,456 | 2 | 0 | NOASSERTION | 2019-11-22T14:46:48 | 2018-07-03T07:49:14 | C++ | UTF-8 | C++ | false | false | 2,094 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkPolyPointSource.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/**
* @class vtkPolyPointSource
* @brief create points from a list of input points
*
* vtkPolyPointSource is a source object that creates a vert from
* user-specified points. The output is a vtkPolyData.
*/
#ifndef vtkPolyPointSource_h
#define vtkPolyPointSource_h
#include "vtkFiltersSourcesModule.h" // For export macro
#include "vtkPolyDataAlgorithm.h"
class vtkPoints;
class VTKFILTERSSOURCES_EXPORT vtkPolyPointSource : public vtkPolyDataAlgorithm
{
public:
static vtkPolyPointSource* New();
vtkTypeMacro(vtkPolyPointSource, vtkPolyDataAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent) override;
//@{
/**
* Set the number of points in the poly line.
*/
void SetNumberOfPoints(vtkIdType numPoints);
vtkIdType GetNumberOfPoints();
//@}
/**
* Resize while preserving data.
*/
void Resize(vtkIdType numPoints);
/**
* Set a point location.
*/
void SetPoint(vtkIdType id, double x, double y, double z);
//@{
/**
* Get the points.
*/
void SetPoints(vtkPoints* points);
vtkGetObjectMacro(Points, vtkPoints);
//@}
/**
* Get the mtime plus consider its Points
*/
vtkMTimeType GetMTime() override;
protected:
vtkPolyPointSource();
~vtkPolyPointSource() override;
int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector *) override;
vtkPoints* Points;
private:
vtkPolyPointSource(const vtkPolyPointSource&) = delete;
void operator=(const vtkPolyPointSource&) = delete;
};
#endif
| [
"ken.martin@kitware.com"
] | ken.martin@kitware.com |
ed02ecd38a52081ebbbac646dad577266409300b | 3ae0faf27a72aa9a0e69836bb73aaaec37b7a1e8 | /src/component/layout/zIndexComponent.cpp | aa31d528796a25695bff44e0d453725d83446307 | [] | no_license | Jackbenfu/Jackbengine | 9be48ee5a9623cf1a51c8106336858c38278b076 | 4036b4086c41736e0b00bfe3ea2eb3f3f0b72c08 | refs/heads/master | 2021-07-01T20:44:39.679403 | 2020-05-27T21:53:20 | 2020-05-27T21:53:20 | 63,488,028 | 5 | 0 | null | 2019-04-06T14:11:57 | 2016-07-16T15:00:26 | C++ | UTF-8 | C++ | false | false | 415 | cpp | //
// zIndexComponent.cpp
// jackbengine
//
// Created by Damien Bendejacq on 29/07/2017.
// Copyright © 2017 Damien Bendejacq. All rights reserved.
//
#include "zIndexComponent.hpp"
namespace Jackbengine {
ZIndexComponent::ZIndexComponent(uint index)
: m_index {index}
{
}
uint ZIndexComponent::index() const
{
return m_index;
}
void ZIndexComponent::setIndex(uint index)
{
m_index = index;
}
}
| [
"damien.bendejacq@iscool-e.com"
] | damien.bendejacq@iscool-e.com |
05b44d16263ca33b022b412e3d1816fe02384bf1 | 4f515d43b685715f0c9f1ed7e24554b539dd76d3 | /src/DsG4Scintillation.cc | b25d4b2fa6115e802f11b316fde8e3a491150483 | [] | no_license | WenjieWu-Sci/simjuno | 8ca365fd9c3041df83a2bb150edd91714740a27c | 1cc6e7bb4926bde7e1d020b7efff7d96b85d3dad | refs/heads/master | 2021-08-26T09:26:24.970843 | 2017-09-30T06:31:08 | 2017-09-30T06:31:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,711 | cc | //
// ********************************************************************
// * DISCLAIMER *
// * *
// * The following disclaimer summarizes all the specific disclaimers *
// * of contributors to this software. The specific disclaimers,which *
// * govern, are listed with their locations in: *
// * http://cern.ch/geant4/license *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. *
// * *
// * This code implementation is the intellectual property of the *
// * GEANT4 collaboration. *
// * By copying, distributing or modifying the Program (or any work *
// * based on the Program) you indicate your acceptance of this *
// * statement, and all its terms. *
// ********************************************************************
//
//
//
// //////////////////////////////////////////////////////////////////////
// Scintillation Light Class Implementation
// //////////////////////////////////////////////////////////////////////
//
// File: G4Scintillation.cc
// Description: RestDiscrete Process - Generation of Scintillation Photons
// Version: 1.0
// Created: 1998-11-07
// Author: Peter Gumplinger
// Updated: 2005-08-17 by Peter Gumplinger
// > change variable name MeanNumPhotons -> MeanNumberOfPhotons
// 2005-07-28 by Peter Gumplinger
// > add G4ProcessType to constructor
// 2004-08-05 by Peter Gumplinger
// > changed StronglyForced back to Forced in GetMeanLifeTime
// 2002-11-21 by Peter Gumplinger
// > change to use G4Poisson for small MeanNumberOfPhotons
// 2002-11-07 by Peter Gumplinger
// > now allow for fast and slow scintillation component
// 2002-11-05 by Peter Gumplinger
// > now use scintillation constants from G4Material
// 2002-05-09 by Peter Gumplinger
// > use only the PostStepPoint location for the origin of
// scintillation photons when energy is lost to the medium
// by a neutral particle
// 2000-09-18 by Peter Gumplinger
// > change: aSecondaryPosition=x0+rand*aStep.GetDeltaPosition();
// aSecondaryTrack->SetTouchable(0);
// 2001-09-17, migration of Materials to pure STL (mma)
// 2003-06-03, V.Ivanchenko fix compilation warnings
//
//mail: gum@triumf.ca
//
//////////////////////////////////////////////////////////////////////////
//-------------------------------------------------------------------
// DsG4Scintillation is a class modified from G4Scintillation
// Birks' law is implemented
// Author: Liang Zhan, 2006/01/27
// Added weighted photon track method based on GLG4Scint. Jianglai 09/05/2006
// Modified: bv@bnl.gov, 2008/4/16 for DetSim
//--------------------------------------------------------------------
//
//#include <boost/python.hpp>
#include "DsG4Scintillation.h"
#include "G4UnitsTable.hh"
#include "G4LossTableManager.hh"
#include "G4MaterialCutsCouple.hh"
#include "G4Gamma.hh"
#include "G4Electron.hh"
#include "globals.hh"
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
//#include "DsPhotonTrackInfo.h"
//#include "G4DataHelpers/G4CompositeTrackInfo.h"
///////////////////////////////////////////////////////////////////
using namespace std;
/////////////////////////
// Class Implementation
/////////////////////////
//////////////
// Operators
//////////////
// DsG4Scintillation::operator=(const DsG4Scintillation &right)
// {
// }
/////////////////
// Constructors
/////////////////
DsG4Scintillation::DsG4Scintillation(const G4String& processName,
G4ProcessType type)
: G4VRestDiscreteProcess(processName, type)
, doReemission(true)
, doBothProcess(true)
, doReemissionOnly(false)
, fEnableQuenching(true)
, slowerTimeConstant(0) , slowerRatio(0)
, gammaSlowerTime(0) , gammaSlowerRatio(0)
, neutronSlowerTime(0) , neutronSlowerRatio(0)
, alphaSlowerTime(0) , alphaSlowerRatio(0)
, flagDecayTimeFast(true), flagDecayTimeSlow(true)
, fPhotonWeight(1.0)
, fApplyPreQE(false)
, fPreQE(1.)
, m_noop(false)
{
SetProcessSubType(fScintillation);
fTrackSecondariesFirst = false;
YieldFactor = 1.0;
ExcitationRatio = 1.0;
theFastIntegralTable = NULL;
theSlowIntegralTable = NULL;
theReemissionIntegralTable = NULL;
verboseLevel = 2;
G4cout << " DsG4Scintillation set verboseLevel by hand to " << verboseLevel << G4endl;
if (verboseLevel > 0) {
G4cout << GetProcessName() << " is created " << G4endl;
}
BuildThePhysicsTable();
}
////////////////
// Destructors
////////////////
DsG4Scintillation::~DsG4Scintillation()
{
if (theFastIntegralTable != NULL) {
theFastIntegralTable->clearAndDestroy();
delete theFastIntegralTable;
}
if (theSlowIntegralTable != NULL) {
theSlowIntegralTable->clearAndDestroy();
delete theSlowIntegralTable;
}
if (theReemissionIntegralTable != NULL) {
theReemissionIntegralTable->clearAndDestroy();
delete theReemissionIntegralTable;
}
}
////////////
// Methods
////////////
// AtRestDoIt
// ----------
//
G4VParticleChange*
DsG4Scintillation::AtRestDoIt(const G4Track& aTrack, const G4Step& aStep)
// This routine simply calls the equivalent PostStepDoIt since all the
// necessary information resides in aStep.GetTotalEnergyDeposit()
{
return DsG4Scintillation::PostStepDoIt(aTrack, aStep);
}
// PostStepDoIt
// -------------
//
G4VParticleChange*
DsG4Scintillation::PostStepDoIt(const G4Track& aTrack, const G4Step& aStep)
// This routine is called for each tracking step of a charged particle
// in a scintillator. A Poisson/Gauss-distributed number of photons is
// generated according to the scintillation yield formula, distributed
// evenly along the track segment and uniformly into 4pi.
{
aParticleChange.Initialize(aTrack);
if (m_noop) { // do nothing, bail
aParticleChange.SetNumberOfSecondaries(0);
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
G4String pname= "";
G4ThreeVector vertpos;
G4double vertenergy=0.0;
G4double reem_d=0.0;
G4bool flagReemission= false;
//DsPhotonTrackInfo* reemittedTI=0;
if (aTrack.GetDefinition() == G4OpticalPhoton::OpticalPhoton()) {
G4Track* track= aStep.GetTrack();
//G4CompositeTrackInfo* composite=dynamic_cast<G4CompositeTrackInfo*>(track->GetUserInformation());
//reemittedTI = composite?dynamic_cast<DsPhotonTrackInfo*>( composite->GetPhotonTrackInfo() ):0;
//const G4VProcess* process = track->GetCreatorProcess();
//if(process) pname = process->GetProcessName();
const G4VProcess* process;
if (track->GetParentID()==0) {
process= aStep.GetPostStepPoint()->GetProcessDefinedStep();
} else {
process= track->GetCreatorProcess();
}
if(process) pname = process->GetProcessName();
if (verboseLevel > 0) {
G4cout<<"Optical photon. Process name is " << pname <<G4endl;
}
if(doBothProcess) {
flagReemission= doReemission
&& aTrack.GetTrackStatus() == fStopAndKill
&& aStep.GetPostStepPoint()->GetStepStatus() != fGeomBoundary;
}
else{
flagReemission= doReemission
&& aTrack.GetTrackStatus() == fStopAndKill
&& aStep.GetPostStepPoint()->GetStepStatus() != fGeomBoundary
&& pname=="Cerenkov";
}
if(verboseLevel > 0) {
G4cout<<"flag of Reemission is "<<flagReemission<<"!!"<<G4endl;
}
if (!flagReemission) {
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
}
G4double TotalEnergyDeposit = aStep.GetTotalEnergyDeposit();
if (verboseLevel > 0 ) {
G4cout << " TotalEnergyDeposit: " << TotalEnergyDeposit
<< " material: " << aTrack.GetMaterial()->GetName() << G4endl;
}
if (TotalEnergyDeposit <= 0.0 && !flagReemission) {
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
const G4DynamicParticle* aParticle = aTrack.GetDynamicParticle();
const G4String aParticleName = aParticle->GetDefinition()->GetParticleName();
const G4Material* aMaterial = aTrack.GetMaterial();
G4MaterialPropertiesTable* aMaterialPropertiesTable= aMaterial->GetMaterialPropertiesTable();
//aMaterialPropertiesTable-> DumpTable();
if (!aMaterialPropertiesTable)
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
G4String FastTimeConstant = "FASTTIMECONSTANT";
G4String SlowTimeConstant = "SLOWTIMECONSTANT";
G4String strYieldRatio = "YIELDRATIO";
// reset the slower time constant and ratio
slowerTimeConstant = 0.0;
slowerRatio = 0.0;
if (aParticleName == "opticalphoton") {
FastTimeConstant = "ReemissionFASTTIMECONSTANT";
SlowTimeConstant = "ReemissionSLOWTIMECONSTANT";
strYieldRatio = "ReemissionYIELDRATIO";
}
else if(aParticleName == "gamma" || aParticleName == "e+" || aParticleName == "e-") {
FastTimeConstant = "GammaFASTTIMECONSTANT";
SlowTimeConstant = "GammaSLOWTIMECONSTANT";
strYieldRatio = "GammaYIELDRATIO";
slowerTimeConstant = gammaSlowerTime;
slowerRatio = gammaSlowerRatio;
}
else if(aParticleName == "alpha") {
FastTimeConstant = "AlphaFASTTIMECONSTANT";
SlowTimeConstant = "AlphaSLOWTIMECONSTANT";
strYieldRatio = "AlphaYIELDRATIO";
slowerTimeConstant = alphaSlowerTime;
slowerRatio = alphaSlowerRatio;
}
else {
FastTimeConstant = "NeutronFASTTIMECONSTANT";
SlowTimeConstant = "NeutronSLOWTIMECONSTANT";
strYieldRatio = "NeutronYIELDRATIO";
slowerTimeConstant = neutronSlowerTime;
slowerRatio = neutronSlowerRatio;
}
const G4MaterialPropertyVector* Fast_Intensity= aMaterialPropertiesTable->GetProperty("FASTCOMPONENT");
const G4MaterialPropertyVector* Slow_Intensity= aMaterialPropertiesTable->GetProperty("SLOWCOMPONENT");
const G4MaterialPropertyVector* Reemission_Prob= aMaterialPropertiesTable->GetProperty("REEMISSIONPROB");
if (verboseLevel > 0 ) {
G4cout << " MaterialPropertyVectors: Fast_Intensity " << Fast_Intensity
<< " Slow_Intensity " << Slow_Intensity
<< " Reemission_Prob " << Reemission_Prob << G4endl;
}
if (!Fast_Intensity && !Slow_Intensity )
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
G4int nscnt = 1;
if (Fast_Intensity && Slow_Intensity) nscnt = 2;
if ( verboseLevel > 0) {
G4cout << " Fast_Intensity " << Fast_Intensity
<< " Slow_Intensity " << Slow_Intensity
<< " nscnt " << nscnt << G4endl;
}
G4StepPoint* pPreStepPoint = aStep.GetPreStepPoint();
G4StepPoint* pPostStepPoint = aStep.GetPostStepPoint();
G4ThreeVector x0 = pPreStepPoint->GetPosition();
G4ThreeVector p0 = aStep.GetDeltaPosition().unit();
G4double t0 = pPreStepPoint->GetGlobalTime();
//Replace NumPhotons by NumTracks
G4int NumTracks=0;
G4double weight=1.0;
if (flagReemission) {
if(verboseLevel > 0){
G4cout<<"the process name is "<<pname<<"!!"<<G4endl;}
if ( Reemission_Prob == 0)
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
G4double p_reemission= Reemission_Prob->Value(aTrack.GetKineticEnergy());
if (G4UniformRand() >= p_reemission)
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
NumTracks= 1;
weight= aTrack.GetWeight();
if (verboseLevel > 0 ) {
G4cout << " flagReemission " << flagReemission << " weight " << weight << G4endl;}
}
else {
//////////////////////////////////// Birks' law ////////////////////////
// J.B.Birks. The theory and practice of Scintillation Counting.
// Pergamon Press, 1964.
// For particles with energy much smaller than minimum ionization
// energy, the scintillation response is non-linear because of quenching
// effect. The light output is reduced by a parametric factor:
// 1/(1 + birk1*delta + birk2* delta^2).
// Delta is the energy loss per unit mass thickness. birk1 and birk2
// were measured for several organic scintillators.
// Here we use birk1 = 0.0125*g/cm2/MeV and ignore birk2.
// R.L.Craun and D.L.Smith. Nucl. Inst. and Meth., 80:239-244, 1970.
// Liang Zhan 01/27/2006
// /////////////////////////////////////////////////////////////////////
G4double ScintillationYield = 0;
{// Yield. Material must have this or we lack raisins dayetras
// const G4MaterialPropertyVector* ptable = aMaterialPropertiesTable->GetConstProperty("SCINTILLATIONYIELD");
const G4double ptable = aMaterialPropertiesTable->GetConstProperty("SCINTILLATIONYIELD");
if (!ptable) {
G4cout << "ConstProperty: failed to get SCINTILLATIONYIELD"
<< G4endl;
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
ScintillationYield = ptable;
G4cout << "Scintillation yield is : " << ScintillationYield << G4endl;
}
G4double ResolutionScale = 1;
{// Resolution Scale
// const G4MaterialPropertyVector* ptable = aMaterialPropertiesTable->GetProperty("RESOLUTIONSCALE");
const G4double ptable = aMaterialPropertiesTable->GetConstProperty("RESOLUTIONSCALE");
if (ptable)
ResolutionScale = ptable;
}
G4double dE = TotalEnergyDeposit;
G4double dx = aStep.GetStepLength();
G4double dE_dx = dE/dx;
if(aTrack.GetDefinition() == G4Gamma::Gamma() && dE > 0)
{
G4LossTableManager* manager = G4LossTableManager::Instance();
dE_dx = dE/manager->GetRange(G4Electron::Electron(), dE, aTrack.GetMaterialCutsCouple());
//G4cout<<"gamma dE_dx = "<<dE_dx/(MeV/mm)<<"MeV/mm"<<G4endl;
}
G4double delta = dE_dx/aMaterial->GetDensity();//get scintillator density
//G4double birk1 = 0.0125*g/cm2/MeV;
G4double birk1 = birksConstant1;
if(abs(aParticle->GetCharge())>1.5)//for particle charge greater than 1.
birk1 = 0.57*birk1;
G4double birk2 = 0;
//birk2 = (0.0031*g/MeV/cm2)*(0.0031*g/MeV/cm2);
birk2 = birksConstant2;
G4double QuenchedTotalEnergyDeposit = TotalEnergyDeposit;
// if quenching is enabled, apply the birks law
if (fEnableQuenching) {
QuenchedTotalEnergyDeposit
= TotalEnergyDeposit/(1+birk1*delta+birk2*delta*delta);
}
//Add 300ns trick for muon simuation, by Haoqi Jan 27, 2011
if(FastMu300nsTrick) {
// cout<<"GlobalTime ="<<aStep.GetTrack()->GetGlobalTime()/ns<<endl;
if(aStep.GetTrack()->GetGlobalTime()/ns>300) {
ScintillationYield = YieldFactor * ScintillationYield;
}
else{
ScintillationYield=0.;
}
}
else {
ScintillationYield = YieldFactor * ScintillationYield;
}
G4double MeanNumberOfPhotons= ScintillationYield * QuenchedTotalEnergyDeposit;
// Implemented the fast simulation method from GLG4Scint
// Jianglai 09-05-2006
// randomize number of TRACKS (not photons)
// this gets statistics right for number of PE after applying
// boolean random choice to final absorbed track (change from
// old method of applying binomial random choice to final absorbed
// track, which did want poissonian number of photons divided
// as evenly as possible into tracks)
// Note for weight=1, there's no difference between tracks and photons.
G4double MeanNumberOfTracks= MeanNumberOfPhotons/fPhotonWeight;
if ( fApplyPreQE ) {
MeanNumberOfTracks*=fPreQE;
}
if (MeanNumberOfTracks > 10.) {
G4double sigma = ResolutionScale * sqrt(MeanNumberOfTracks);
NumTracks = G4int(G4RandGauss::shoot(MeanNumberOfTracks,sigma)+0.5);
}
else {
NumTracks = G4int(G4Poisson(MeanNumberOfTracks));
}
if ( verboseLevel > 0 ) {
G4cout << " Generated " << NumTracks << " scint photons. mean(scint photons) = " << MeanNumberOfTracks << G4endl;
}
}
weight*=fPhotonWeight;
if ( verboseLevel > 0 ) {
G4cout << " set scint photon weight to " << weight << " after multiplying original weight by fPhotonWeight " << fPhotonWeight
<< " NumTracks = " << NumTracks
<< G4endl;
}
// G4cerr<<"Scint weight is "<<weight<<G4endl;
if (NumTracks <= 0) {
// return unchanged particle and no secondaries
aParticleChange.SetNumberOfSecondaries(0);
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
////////////////////////////////////////////////////////////////
aParticleChange.SetNumberOfSecondaries(NumTracks);
if (fTrackSecondariesFirst) {
if (!flagReemission)
if (aTrack.GetTrackStatus() == fAlive )
aParticleChange.ProposeTrackStatus(fSuspend);
}
////////////////////////////////////////////////////////////////
G4int materialIndex = aMaterial->GetIndex();
G4PhysicsOrderedFreeVector* ReemissionIntegral = NULL;
ReemissionIntegral =
(G4PhysicsOrderedFreeVector*)((*theReemissionIntegralTable)(materialIndex));
// Retrieve the Scintillation Integral for this material
// new G4PhysicsOrderedFreeVector allocated to hold CII's
G4int Num = NumTracks; //# tracks is now the loop control
G4double fastTimeConstant = 0.0;
if (flagDecayTimeFast) { // Fast Time Constant
// const G4MaterialPropertyVector* ptable= aMaterialPropertiesTable->GetConstProperty(FastTimeConstant.c_str());
G4double ptable;
if (aMaterialPropertiesTable->ConstPropertyExists(FastTimeConstant.c_str())) {
ptable= aMaterialPropertiesTable->GetConstProperty(FastTimeConstant.c_str());
} else if (aMaterialPropertiesTable->ConstPropertyExists("FASTTIMECONSTANT")) {
ptable= aMaterialPropertiesTable->GetConstProperty("FASTTIMECONSTANT");
}
if (verboseLevel > 0) {
G4cout << " MaterialPropertyVector table " << ptable << " for FASTTIMECONSTANT"<<G4endl;
}
if (ptable) {
fastTimeConstant = ptable;
// if (verboseLevel > 0) {
// G4cout << " dump fast time constant table " << G4endl;
// const_cast <G4MaterialPropertyVector*>(ptable)->DumpValues();
// }
}
}
G4double slowTimeConstant = 0.0;
if (flagDecayTimeSlow) { // Slow Time Constant
// const G4MaterialPropertyVector* ptable = aMaterialPropertiesTable->GetProperty(SlowTimeConstant.c_str());
G4double ptable;
if (aMaterialPropertiesTable->ConstPropertyExists(SlowTimeConstant.c_str())) {
ptable= aMaterialPropertiesTable->GetConstProperty(SlowTimeConstant.c_str());
} else if (aMaterialPropertiesTable->ConstPropertyExists("SLOWTIMECONSTANT")) {
ptable = aMaterialPropertiesTable->GetConstProperty("SLOWTIMECONSTANT");
}
if (verboseLevel > 0) {
G4cout << " MaterialPropertyVector table " << ptable << " for SLOWTIMECONSTANT"<<G4endl;
}
if (ptable){
slowTimeConstant = ptable;
// if (verboseLevel > 0) {
// G4cout << " dump slow time constant table " << G4endl;
// const_cast <G4MaterialPropertyVector*>(ptable)->DumpVector();
// }
}
}
G4double YieldRatio = 0.0;
{
G4double ptable;
if (aMaterialPropertiesTable->ConstPropertyExists(strYieldRatio.c_str())) {
ptable = aMaterialPropertiesTable->GetConstProperty(strYieldRatio.c_str());
} else if (aMaterialPropertiesTable->ConstPropertyExists("YIELDRATIO")) {
ptable = aMaterialPropertiesTable->GetConstProperty("YIELDRATIO");
}
if (ptable) {
YieldRatio = ptable;
if (verboseLevel > 0) {
G4cout << " YieldRatio = "<< YieldRatio << " (yield ratio = fast/(fast+slow): " << G4endl;
// const_cast <G4MaterialPropertyVector*>(ptable)->DumpVector();
}
}
}
//loop over fast/slow scintillations
for (G4int scnt = 1; scnt <= nscnt; scnt++) {
G4double ScintillationTime = 0.*ns;
G4PhysicsOrderedFreeVector* ScintillationIntegral = NULL;
if (scnt == 1) {//fast
if (nscnt == 1) {
if(Fast_Intensity){
ScintillationTime = fastTimeConstant;
ScintillationIntegral =
(G4PhysicsOrderedFreeVector*)((*theFastIntegralTable)(materialIndex));
}
if(Slow_Intensity){
ScintillationTime = slowTimeConstant;
ScintillationIntegral =
(G4PhysicsOrderedFreeVector*)((*theSlowIntegralTable)(materialIndex));
}
}
else {
if ( ExcitationRatio == 1.0 ) {
Num = G4int( 0.5 + (min(YieldRatio,1.0) * NumTracks) ); // round off, not truncation
}
else {
Num = G4int( 0.5 + (min(ExcitationRatio,1.0) * NumTracks));
}
if ( verboseLevel>1 ){
G4cout << "Generate Num " << Num << " optical photons with fast component using NumTracks "
<< NumTracks << " YieldRatio " << YieldRatio << " ExcitationRatio " << ExcitationRatio
<< " min(YieldRatio,1.)*NumTracks = " << min(YieldRatio,1.)*NumTracks
<< " min(ExcitationRatio,1.)*NumTracks = " << min(ExcitationRatio,1.)*NumTracks
<< G4endl;
}
ScintillationTime = fastTimeConstant;
ScintillationIntegral =
(G4PhysicsOrderedFreeVector*)((*theFastIntegralTable)(materialIndex));
}
}
else {//slow
Num = NumTracks - Num;
ScintillationTime = slowTimeConstant;
ScintillationIntegral =
(G4PhysicsOrderedFreeVector*)((*theSlowIntegralTable)(materialIndex));
}
if (verboseLevel > 0) {
G4cout << "generate " << Num << " optical photons with scintTime " << ScintillationTime
<< " slowTimeConstant " << slowTimeConstant << " fastTimeConstant " << fastTimeConstant << G4endl;
}
if (!ScintillationIntegral) continue;
// Max Scintillation Integral
for (G4int i = 0; i < Num; i++) { //Num is # of 2ndary tracks now
// Determine photon energy
if(scnt == 2) {
ScintillationTime = slowTimeConstant;
if(flagDecayTimeSlow && G4UniformRand() < slowerRatio && (!flagReemission)) ScintillationTime = slowerTimeConstant;
}
G4double sampledEnergy;
if ( !flagReemission ) {
// normal scintillation
G4double CIIvalue = G4UniformRand()*ScintillationIntegral->GetMaxValue();
sampledEnergy= ScintillationIntegral->GetEnergy(CIIvalue);
if (verboseLevel>1)
{
G4cout << "sampledEnergy = " << sampledEnergy << G4endl;
G4cout << "CIIvalue = " << CIIvalue << G4endl;
}
}
else {
// reemission, the sample method need modification
G4double CIIvalue = G4UniformRand()*
ScintillationIntegral->GetMaxValue();
if (CIIvalue == 0.0) {
// return unchanged particle and no secondaries
aParticleChange.SetNumberOfSecondaries(0);
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
sampledEnergy=
ScintillationIntegral->GetEnergy(CIIvalue);
if (verboseLevel>1) {
G4cout << "oldEnergy = " <<aTrack.GetKineticEnergy() << G4endl;
G4cout << "reemittedSampledEnergy = " << sampledEnergy
<< "\nreemittedCIIvalue = " << CIIvalue << G4endl;
}
}
// Generate random photon direction
G4double cost = 1. - 2.*G4UniformRand();
G4double sint = sqrt((1.-cost)*(1.+cost));
G4double phi = twopi*G4UniformRand();
G4double sinp = sin(phi);
G4double cosp = cos(phi);
G4double px = sint*cosp;
G4double py = sint*sinp;
G4double pz = cost;
// Create photon momentum direction vector
G4ParticleMomentum photonMomentum(px, py, pz);
// Determine polarization of new photon
G4double sx = cost*cosp;
G4double sy = cost*sinp;
G4double sz = -sint;
G4ThreeVector photonPolarization(sx, sy, sz);
G4ThreeVector perp = photonMomentum.cross(photonPolarization);
phi = twopi*G4UniformRand();
sinp = sin(phi);
cosp = cos(phi);
photonPolarization = cosp * photonPolarization + sinp * perp;
photonPolarization = photonPolarization.unit();
// Generate a new photon:
G4DynamicParticle* aScintillationPhoton =
new G4DynamicParticle(G4OpticalPhoton::OpticalPhoton(),
photonMomentum);
aScintillationPhoton->SetPolarization
(photonPolarization.x(),
photonPolarization.y(),
photonPolarization.z());
aScintillationPhoton->SetKineticEnergy(sampledEnergy);
// Generate new G4Track object:
G4double rand=0;
G4ThreeVector aSecondaryPosition;
G4double deltaTime;
if (flagReemission) {
deltaTime= pPostStepPoint->GetGlobalTime() - t0
-ScintillationTime * log( G4UniformRand() );
aSecondaryPosition= pPostStepPoint->GetPosition();
vertpos = aTrack.GetVertexPosition();
vertenergy = aTrack.GetKineticEnergy();
reem_d =
sqrt( pow( aSecondaryPosition.x()-vertpos.x(), 2)
+ pow( aSecondaryPosition.y()-vertpos.y(), 2)
+ pow( aSecondaryPosition.z()-vertpos.z(), 2) );
}
else {
if (aParticle->GetDefinition()->GetPDGCharge() != 0)
{
rand = G4UniformRand();
}
else
{
rand = 1.0;
}
G4double delta = rand * aStep.GetStepLength();
deltaTime = delta /
((pPreStepPoint->GetVelocity()+
pPostStepPoint->GetVelocity())/2.);
deltaTime = deltaTime -
ScintillationTime * log( G4UniformRand() );
aSecondaryPosition =
x0 + rand * aStep.GetDeltaPosition();
}
G4double aSecondaryTime = t0 + deltaTime;
if ( verboseLevel>1 ){
G4cout << "Generate " << i << "th scintillation photon at relative time(ns) " << deltaTime
<< " with ScintillationTime " << ScintillationTime << " flagReemission " << flagReemission << G4endl;
}
G4Track* aSecondaryTrack =
new G4Track(aScintillationPhoton,aSecondaryTime,aSecondaryPosition);
//G4CompositeTrackInfo* comp=new G4CompositeTrackInfo();
//DsPhotonTrackInfo* trackinf=new DsPhotonTrackInfo();
//if ( flagReemission ){
// if ( reemittedTI ) *trackinf = *reemittedTI;
// trackinf->SetReemitted();
//}
//else if ( fApplyPreQE ) {
// trackinf->SetMode(DsPhotonTrackInfo::kQEPreScale);
// trackinf->SetQE(fPreQE);
//}
//comp->SetPhotonTrackInfo(trackinf);
//aSecondaryTrack->SetUserInformation(comp);
aSecondaryTrack->SetWeight( weight );
aSecondaryTrack->SetTouchableHandle(aStep.GetPreStepPoint()->GetTouchableHandle());
// aSecondaryTrack->SetTouchableHandle((G4VTouchable*)0);//this is wrong
aSecondaryTrack->SetParentID(aTrack.GetTrackID());
// add the secondary to the ParticleChange object
aParticleChange.SetSecondaryWeightByProcess( true ); // recommended
aParticleChange.AddSecondary(aSecondaryTrack);
aSecondaryTrack->SetWeight( weight );
if ( verboseLevel > 0 ) {
G4cout << " aSecondaryTrack->SetWeight( " << weight
<< " ) ; aSecondaryTrack->GetWeight() = " << aSecondaryTrack->GetWeight()
<< G4endl;
}
// The above line is necessary because AddSecondary()
// overrides our setting of the secondary track weight,
// in Geant4.3.1 & earlier. (and also later, at least
// until Geant4.7 (and beyond?)
// -- maybe not required if SetWeightByProcess(true) called,
// but we do both, just to be sure)
}
} // end loop over fast/slow scints
if (verboseLevel > 0) {
G4cout << "\n Exiting from G4Scintillation::DoIt -- NumberOfSecondaries = "
<< aParticleChange.GetNumberOfSecondaries() << G4endl;
}
return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep);
}
// BuildThePhysicsTable for the scintillation process
// --------------------------------------------------
//
void DsG4Scintillation::BuildThePhysicsTable()
{
if (theFastIntegralTable && theSlowIntegralTable && theReemissionIntegralTable) return;
const G4MaterialTable* theMaterialTable= G4Material::GetMaterialTable();
G4int numOfMaterials= G4Material::GetNumberOfMaterials();
// create new physics table
if (verboseLevel > 0) {
G4cout << G4endl;
G4cout << " theFastIntegralTable " << theFastIntegralTable
<< " theSlowIntegralTable " << theSlowIntegralTable
<< " theReemissionIntegralTable " << theReemissionIntegralTable << G4endl;
}
if(!theFastIntegralTable) theFastIntegralTable = new G4PhysicsTable(numOfMaterials);
if(!theSlowIntegralTable) theSlowIntegralTable = new G4PhysicsTable(numOfMaterials);
if(!theReemissionIntegralTable) theReemissionIntegralTable
= new G4PhysicsTable(numOfMaterials);
if (verboseLevel > 0) {
G4cout << " building the physics tables for the scintillation process " << G4endl;
}
// loop for materials
for (G4int i=0 ; i < numOfMaterials; i++) {
G4PhysicsOrderedFreeVector* aPhysicsOrderedFreeVector =
new G4PhysicsOrderedFreeVector();
G4PhysicsOrderedFreeVector* bPhysicsOrderedFreeVector =
new G4PhysicsOrderedFreeVector();
G4PhysicsOrderedFreeVector* cPhysicsOrderedFreeVector =
new G4PhysicsOrderedFreeVector();
// Retrieve vector of scintillation wavelength intensity for
// the material from the material's optical properties table.
G4Material* aMaterial = (*theMaterialTable)[i];
G4cout << " material : " << aMaterial->GetName() << G4endl;
G4MaterialPropertiesTable* aMaterialPropertiesTable =
aMaterial->GetMaterialPropertiesTable();
if (aMaterialPropertiesTable) {
G4MaterialPropertyVector* theFastLightVector =
aMaterialPropertiesTable->GetProperty("FASTCOMPONENT");
if (theFastLightVector) {
if (verboseLevel > 0) {
G4cout << " Building the material properties table for FASTCOMPONENT" << G4endl;
}
// Retrieve the first intensity point in vector
// of (photon energy, intensity) pairs
// theFastLightVector->ResetIterator();
// ++(*theFastLightVector); // advance to 1st entry
G4double currentIN= (*theFastLightVector)[0];
if (currentIN >= 0.0) {
// Create first (photon energy, Scintillation
// Integral pair
G4double currentPM= theFastLightVector->Energy(0);
G4double currentCII = 0.0;
aPhysicsOrderedFreeVector->InsertValues(currentPM , currentCII);
// Set previous values to current ones prior to loop
G4double prevPM = currentPM;
G4double prevCII = currentCII;
G4double prevIN = currentIN;
// loop over all (photon energy, intensity)
// pairs stored for this material
for (size_t ii= 1;
ii< theFastLightVector->GetVectorLength();
++ii)
{
currentPM= theFastLightVector->Energy(ii);
currentIN= (*theFastLightVector)[ii];
currentCII = 0.5 * (prevIN + currentIN);
currentCII = prevCII +
(currentPM - prevPM) * currentCII;
aPhysicsOrderedFreeVector->
InsertValues(currentPM, currentCII);
prevPM = currentPM;
prevCII = currentCII;
prevIN = currentIN;
}
}
}
G4MaterialPropertyVector* theSlowLightVector =
aMaterialPropertiesTable->GetProperty("SLOWCOMPONENT");
if (theSlowLightVector) {
if (verboseLevel > 0) {
G4cout << " Building the material properties table for SLOWCOMPONENT" << G4endl;
}
// Retrieve the first intensity point in vector
// of (photon energy, intensity) pairs
// theSlowLightVector->ResetIterator();
// ++(*theSlowLightVector); // advance to 1st entry
G4double currentIN = (*theSlowLightVector)[0];
if (currentIN >= 0.0) {
// Create first (photon energy, Scintillation
// Integral pair
G4double currentPM = theSlowLightVector->Energy(0);
G4double currentCII = 0.0;
bPhysicsOrderedFreeVector->InsertValues(currentPM , currentCII);
// Set previous values to current ones prior to loop
G4double prevPM = currentPM;
G4double prevCII = currentCII;
G4double prevIN = currentIN;
// loop over all (photon energy, intensity)
// pairs stored for this material
for (size_t ii= 1;
ii< theSlowLightVector->GetVectorLength();
++ii)
{
currentPM= theSlowLightVector->Energy(ii);
currentIN= (*theSlowLightVector)[ii];
currentCII = 0.5 * (prevIN + currentIN);
currentCII = prevCII +
(currentPM - prevPM) * currentCII;
bPhysicsOrderedFreeVector->
InsertValues(currentPM, currentCII);
prevPM = currentPM;
prevCII = currentCII;
prevIN = currentIN;
}
}
}
G4MaterialPropertyVector* theReemissionVector =
aMaterialPropertiesTable->GetProperty("REEMISSIONPROB");
if (theReemissionVector) {
if (verboseLevel > 0) {
G4cout << " Building the material properties table for REEMISSIONPROB" << G4endl;
}
// Retrieve the first intensity point in vector
// of (photon energy, intensity) pairs
// theReemissionVector->ResetIterator();
// ++(*theReemissionVector); // advance to 1st entry
G4double currentIN = (*theReemissionVector)[0];
if (currentIN >= 0.0) {
// Create first (photon energy, Scintillation
// Integral pair
G4double currentPM = theReemissionVector->Energy(0);
G4double currentCII = 0.0;
cPhysicsOrderedFreeVector->
InsertValues(currentPM , currentCII);
// Set previous values to current ones prior to loop
G4double prevPM = currentPM;
G4double prevCII = currentCII;
G4double prevIN = currentIN;
// loop over all (photon energy, intensity)
// pairs stored for this material
for (size_t ii= 1;
ii< theReemissionVector->GetVectorLength();
++ii)
{
currentPM= theReemissionVector->Energy(ii);
currentIN= (*theReemissionVector)[ii];
currentCII = 0.5 * (prevIN + currentIN);
currentCII = prevCII +
(currentPM - prevPM) * currentCII;
cPhysicsOrderedFreeVector->
InsertValues(currentPM, currentCII);
prevPM = currentPM;
prevCII = currentCII;
prevIN = currentIN;
}
}
}
}
// The scintillation integral(s) for a given material
// will be inserted in the table(s) according to the
// position of the material in the material table.
theFastIntegralTable->insertAt(i,aPhysicsOrderedFreeVector);
theSlowIntegralTable->insertAt(i,bPhysicsOrderedFreeVector);
theReemissionIntegralTable->insertAt(i,cPhysicsOrderedFreeVector);
}
}
// GetMeanFreePath
// ---------------
//
G4double DsG4Scintillation::GetMeanFreePath(const G4Track&,
G4double ,
G4ForceCondition* condition)
{
*condition = StronglyForced;
return DBL_MAX;
}
// GetMeanLifeTime
// ---------------
//
G4double DsG4Scintillation::GetMeanLifeTime(const G4Track&,
G4ForceCondition* condition)
{
*condition = Forced;
return DBL_MAX;
}
| [
"whuwenjie@gmail.com"
] | whuwenjie@gmail.com |
f5af579edf1384975d0b2846f4ffed970987f135 | bfd2a9f4ebfeea2125d2755916d1395b4fb00ab7 | /Algorithms on Graph/week2_graph_decomposition2/1_cs_curriculum/acyclicity.cpp | 59513075f44527e3125528e9c46ce33c5f207d6d | [] | no_license | akaushal123/Data-Structures-Specialization-Coursera | 8a1c28d13eeb42497e5bfdcb76c7d3b2a7a4ef2d | 840bfae12dbd9dfd7dc2311e3e1fd7e2434073a7 | refs/heads/master | 2022-12-04T03:14:45.693219 | 2020-08-12T09:22:28 | 2020-08-12T09:22:28 | 281,339,173 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | cpp | #include <iostream>
#include <vector>
#include <unordered_set>
using std::vector;
using std::pair;
bool explore(vector<vector<int> > &adj, int v, vector<bool> &visited, std::unordered_set<int> &s){
visited[v] = true;
//insert node into set
s.insert(v);
for(auto w: adj[v])
if(!visited[w] && explore(adj, w, visited, s))
return 1;
//search if node is already processed
else if(s.find(w)!=s.end())
return 1;
//remove node after processing from set
s.erase(v);
return 0;
}
int acyclic(vector<vector<int> > &adj) {
//write your code here
vector<bool> visited(adj.size(), false);
std::unordered_set<int> s;
for(int v = 0; v < adj.size(); v++)
if(!visited[v])
if(explore(adj, v, visited, s))
return 1;
return 0;
}
int main() {
size_t n, m;
std::cin >> n >> m;
vector<vector<int> > adj(n, vector<int>());
for (size_t i = 0; i < m; i++) {
int x, y;
std::cin >> x >> y;
adj[x - 1].push_back(y - 1);
}
std::cout << acyclic(adj);
}
| [
"noreply@github.com"
] | akaushal123.noreply@github.com |
c771b9baea0b1e4c4a77d530c22ecd5f57e00db5 | 92943b7e6d203b23e15d746186567532d5613307 | /Home work/19.02.19/19.02.19/Source.cpp | 08d2a738e3de79cb4c4d2fdb88c45efda792708f | [] | no_license | Zabehalin/C-Plus-Plus | 15d14820cd8084ce4bd4d2ebacbac991d56cfa3a | 2c26bb033d66cdc3ed8f83901ed51ce31ec6c57f | refs/heads/master | 2020-04-18T07:11:32.952399 | 2019-05-14T11:17:53 | 2019-05-14T11:17:53 | 167,352,012 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,796 | cpp | #include <iostream>
#include <ctime>
using namespace std;
/*1. Дано цілочисельний одновимірний масив. Заповнити його, вивести на екран у прямому та зворотньому порядку та порахувати суму елементів з використанням вказівників.*/
/*void Zap(int arr[], const int ROW);
void Vyvid(int arr[], const int ROW);
int main()
{
srand(unsigned(time(NULL)));
const int ROW = 10;
int arr[ROW];
Zap(arr, ROW);
Vyvid(arr, ROW);
system("pause");
return 0;
}
void Zap(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
arr[i] = rand() % 20;
}
}
void Vyvid(int arr[], const int ROW)
{
int sum = 0;
cout << "============ Pramyi =============" << endl;
for (int i = 0; i < ROW; i++)
{
sum += arr[i];
cout << "arr[" << i << "] = " << arr[i] << endl;
}
cout << "\n\tSUMA arr = " << sum << endl;
cout << "============ Zvorot =============" << endl;
for (int i = ROW-1; i >-1; i--)
{
cout << "arr[" << i << "] = " << arr[i] << endl;
}
}*/
/*2. Дано одновимірний масив. Знайти найбільше та найменше значення у масиві та поміняти їх у масиві місцями. Вивести перетворений масив на екран з використанням вказівників.*/
/*void Zap(int arr[], const int ROW);
void Vyvid(int arr[], const int ROW);
void SortBuble(int arr2[], const int ROW);
void Perevirca(int arr[], int arr2[], const int ROW);
int main()
{
srand(unsigned(time(NULL)));
const int ROW = 10;
int arr[ROW];
int arr2[ROW];
Zap(arr, ROW);
Vyvid(arr, ROW);
for (int i = 0; i < ROW; i++)
{
arr2[i] = arr[i];
}
SortBuble(arr2, ROW);
cout << endl;
Perevirca(arr, arr2, ROW);
cout << "Zmina MIN >< MAX" << endl;
Vyvid(arr, ROW);
system("pause");
return 0;
}
void Zap(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
arr[i] = rand() % 20;
}
}
void Vyvid(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
cout << arr[i] << "\t";
}
cout << endl;
}
void SortBuble(int arr2[], const int ROW)
{
for (int i = ROW - 1; i >= 1; i--)
{
for (int j = 0; j < i; j++)
{
if (arr2[j] > arr2[j + 1])
{
int tmp = arr2[j];
arr2[j] = arr2[j + 1];
arr2[j + 1] = tmp;
}
}
}
}
void Perevirca(int arr[], int arr2[], const int ROW)
{
int m = 0, b = 0,z = 0;
for (int i = 0; i < ROW; i++)
{
if (arr[i] == arr2[0])
{
m = i;
}
else if (arr[i] == arr2[ROW-1])
{
b = i;
}
}
cout << "Minim = " << arr[m] <<"===="<< m << endl;
cout << "Max = " << arr[b] <<"===="<< b << endl;
z = arr[m];
arr[m] = arr[b];
arr[b] = z;
}*/
/*3. Дано одновимірний масив. Поміняти місцями дві його половини(якщо масив має непарну довжину, то центральний елемент залишається на місці з використанням вказівників*/
void Zap(int arr[], const int ROW);
void Vyvid(int arr[], const int ROW);
void Zmina(int arr[], const int ROW);
int main()
{
const int ROW = 11;
int arr[ROW];
Zap(arr, ROW);
Vyvid(arr, ROW);
Zmina(arr, ROW);
system("pause");
return 0;
}
void Zap(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
arr[i] = rand() % 20;
}
}
void Vyvid(int arr[], const int ROW)
{
for (int i = 0; i < ROW; i++)
{
cout << arr[i] << "\t";
}
cout << endl;
}
void Zmina(int arr[], const int ROW)
{
int s = 0, z = 0;
s = ROW / 2;
for (int i = 0; i < ROW; i++)
{
if (s <= ROW -1 )
{
cout << arr[s] << "\t";
s++;
}
else if (s >= ROW)
{
cout << arr[z] << "\t";
z++;
}
}
cout << endl;
}
| [
"z380966645657@gmail.com"
] | z380966645657@gmail.com |
9c559f0f6142643e58dd5f6891b311e7c63ed9d7 | 0acace81433043d274bbeb5628fc150cc0f2d072 | /Sources/Emulator/src/mess/machine/vic20user.h | 8a99aeb0e3a7e31f898ba4ab5fbcf8d66ac5f150 | [] | no_license | SonnyJim/MAMEHub | b11780c6e022b47b0be97e4670c49b15a55ec052 | aeaa71c5ebdcf33c06d56625810913a99d3a4a66 | refs/heads/master | 2020-12-03T03:36:28.729082 | 2014-07-11T13:04:23 | 2014-07-11T13:04:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,652 | h | /**********************************************************************
Commodore VIC-20 User Port emulation
Copyright MESS Team.
Visit http://mamedev.org for licensing and usage restrictions.
**********************************************************************
GND 1 A GND
+5V 2 B CB1
/RESET 3 C PB0
JOY0 4 D PB1
JOY1 5 E PB2
JOY2 6 F PB3
LIGHT PEN 7 H PB4
CASSETTE SWITCH 8 J PB5
ATN 9 K PB6
+9VAC 10 L PB7
+9VAC 11 M CB2
GND 12 N GND
**********************************************************************/
#pragma once
#ifndef __VIC20_USER_PORT__
#define __VIC20_USER_PORT__
#include "emu.h"
//**************************************************************************
// CONSTANTS
//**************************************************************************
#define VIC20_USER_PORT_TAG "user"
//**************************************************************************
// INTERFACE CONFIGURATION MACROS
//**************************************************************************
#define VIC20_USER_PORT_INTERFACE(_name) \
const vic20_user_port_interface (_name) =
#define MCFG_VIC20_USER_PORT_ADD(_tag, _config, _slot_intf, _def_slot) \
MCFG_DEVICE_ADD(_tag, VIC20_USER_PORT, 0) \
MCFG_DEVICE_CONFIG(_config) \
MCFG_DEVICE_SLOT_INTERFACE(_slot_intf, _def_slot, false)
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// ======================> vic20_user_port_interface
struct vic20_user_port_interface
{
devcb_write_line m_out_light_pen_cb;
devcb_write_line m_out_cb1_cb;
devcb_write_line m_out_cb2_cb;
devcb_write_line m_out_reset_cb;
};
// ======================> vic20_user_port_device
class device_vic20_user_port_interface;
class vic20_user_port_device : public device_t,
public vic20_user_port_interface,
public device_slot_interface
{
public:
// construction/destruction
vic20_user_port_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
// computer interface
DECLARE_READ8_MEMBER( pb_r );
DECLARE_WRITE8_MEMBER( pb_w );
DECLARE_READ_LINE_MEMBER( joy0_r );
DECLARE_READ_LINE_MEMBER( joy1_r );
DECLARE_READ_LINE_MEMBER( joy2_r );
DECLARE_READ_LINE_MEMBER( light_pen_r );
DECLARE_READ_LINE_MEMBER( cassette_switch_r );
DECLARE_WRITE_LINE_MEMBER( cb1_w );
DECLARE_WRITE_LINE_MEMBER( cb2_w );
DECLARE_WRITE_LINE_MEMBER( atn_w );
DECLARE_WRITE_LINE_MEMBER( port_reset_w );
// cartridge interface
DECLARE_WRITE_LINE_MEMBER( light_pen_w ) { m_out_light_pen_func(state); }
DECLARE_WRITE_LINE_MEMBER( via_cb1_w ) { m_out_cb1_func(state); }
DECLARE_WRITE_LINE_MEMBER( via_cb2_w ) { m_out_cb2_func(state); }
DECLARE_WRITE_LINE_MEMBER( reset_w ) { m_out_reset_func(state); }
protected:
// device-level overrides
virtual void device_config_complete();
virtual void device_start();
virtual void device_reset();
devcb_resolved_write_line m_out_light_pen_func;
devcb_resolved_write_line m_out_cb1_func;
devcb_resolved_write_line m_out_cb2_func;
devcb_resolved_write_line m_out_reset_func;
device_vic20_user_port_interface *m_card;
};
// ======================> device_vic20_user_port_interface
// class representing interface-specific live vic20_expansion card
class device_vic20_user_port_interface : public device_slot_card_interface
{
public:
// construction/destruction
device_vic20_user_port_interface(const machine_config &mconfig, device_t &device);
virtual ~device_vic20_user_port_interface();
virtual UINT8 vic20_pb_r(address_space &space, offs_t offset) { return 0xff; };
virtual void vic20_pb_w(address_space &space, offs_t offset, UINT8 data) { };
virtual int vic20_joy0_r() { return 1; };
virtual int vic20_joy1_r() { return 1; };
virtual int vic20_joy2_r() { return 1; };
virtual int vic20_light_pen_r() { return 1; };
virtual int vic20_cassette_switch_r() { return 1; };
virtual void vic20_cb1_w(int state) { };
virtual void vic20_cb2_w(int state) { };
virtual void vic20_atn_w(int state) { };
protected:
vic20_user_port_device *m_slot;
};
// device type definition
extern const device_type VIC20_USER_PORT;
#endif
| [
"jgmath2000@gmail.com"
] | jgmath2000@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.