prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>sph_sha.rs<|end_file_name|><|fim▁begin|>#![allow(non_camel_case_types)]
extern crate libc;
use libc::{uint32_t, uint64_t, c_uchar, size_t, c_void, c_uint};
use std::mem::{zeroed};
use utils::{to_void_raw_ctx, to_void_raw_data, to_void_raw_dest};
#[repr(C)]
#[allow(non_snake_case)]
pub struct ShaSmallContext {
pub buf: [c_uchar; 64usize],
pub val: [uint32_t; 5usize],
pub count: uint64_t,
}
impl ::std::default::Default for ShaSmallContext {
fn default() -> Self { unsafe { zeroed() } }
}
#[repr(C)]
#[allow(non_snake_case)]
pub struct ShaMediumContext {
pub buf: [c_uchar; 64usize],
pub val: [uint32_t; 8usize],
pub count: uint64_t,
}
impl ::std::default::Default for ShaMediumContext {
fn default() -> Self { unsafe { zeroed() } }
}
#[repr(C)]
#[allow(non_snake_case)]
pub struct ShaBigContext {
pub buf: [c_uchar; 128usize],
pub val: [uint64_t; 8usize],
pub count: uint64_t,
}
impl ::std::default::Default for ShaBigContext {
fn default() -> Self { unsafe { zeroed() } }
}
pub type sha0 = [u8;20];
pub type sha1 = [u8;20];
pub type sha224 = [u8;28];
pub type sha256 = [u8;32];
pub type sha384 = [u8;48];
pub type sha512 = [u8;64];
extern {
pub fn sph_sha0_init(cc: *mut c_void) -> ();
pub fn sph_sha0(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
pub fn sph_sha0_close(cc: *mut c_void, dst: *mut c_void) -> ();
pub fn sph_sha0_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();
pub fn sph_sha0_comp(msg: *mut uint32_t, val: *mut uint32_t) -> ();
pub fn sph_sha1_init(cc: *mut c_void) -> ();
pub fn sph_sha1(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
pub fn sph_sha1_close(cc: *mut c_void, dst: *mut c_void) -> ();
pub fn sph_sha1_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();
pub fn sph_sha1_comp(msg: *mut uint32_t, val: *mut uint32_t) -> ();
pub fn sph_sha224_init(cc: *mut c_void) -> ();
pub fn sph_sha224(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
pub fn sph_sha224_close(cc: *mut c_void, dst: *mut c_void) -> ();
pub fn sph_sha224_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();
pub fn sph_sha224_comp(msg: *mut uint32_t, val: *mut uint32_t) -> ();
pub fn sph_sha256_init(cc: *mut c_void) -> ();
pub fn sph_sha256_close(cc: *mut c_void, dst: *mut c_void) -> ();
pub fn sph_sha256_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();
pub fn sph_sha384_init(cc: *mut c_void) -> ();
pub fn sph_sha384(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
pub fn sph_sha384_close(cc: *mut c_void, dst: *mut c_void) -> ();
pub fn sph_sha384_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();
pub fn sph_sha384_comp(msg: *mut uint64_t, val: *mut uint64_t) -> ();
pub fn sph_sha512_init(cc: *mut c_void) -> ();
pub fn sph_sha512_close(cc: *mut c_void, dst: *mut c_void) -> ();
pub fn sph_sha512_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();
}
pub fn sha0_init(cc: &mut ShaSmallContext) {
let void_raw_cc = to_void_raw_ctx(cc);
unsafe { sph_sha0_init(void_raw_cc) };
}
pub fn sha0_load(cc: &mut ShaSmallContext, data: &str) {
let void_raw_cc = to_void_raw_ctx(cc);
let (void_raw_data, len) = to_void_raw_data(data);<|fim▁hole|> unsafe { sph_sha0(void_raw_cc, void_raw_data, len) };
}
pub fn sha0_close(cc: &mut ShaSmallContext, dest: &mut sha0) {
let void_raw_cc = to_void_raw_ctx(cc);
let void_raw_dest = to_void_raw_dest(dest);
unsafe { sph_sha0_close(void_raw_cc, void_raw_dest); };
}
pub fn sha0_init_load_close(data: &str) -> sha0 {
let mut dest: sha0 = [0;20];
let mut cc = ShaSmallContext::default();
sha0_init(&mut cc);
sha0_load(&mut cc, data);
sha0_close(&mut cc, &mut dest);
return dest;
}
pub fn sha1_init(cc: &mut ShaSmallContext) {
let void_raw_cc = to_void_raw_ctx(cc);
unsafe { sph_sha1_init(void_raw_cc) };
}
pub fn sha1_load(cc: &mut ShaSmallContext, data: &str) {
let void_raw_cc = to_void_raw_ctx(cc);
let (void_raw_data, len) = to_void_raw_data(data);
unsafe { sph_sha1(void_raw_cc, void_raw_data, len) };
}
pub fn sha1_close(cc: &mut ShaSmallContext, dest: &mut sha1) {
let void_raw_cc = to_void_raw_ctx(cc);
let void_raw_dest = to_void_raw_dest(dest);
unsafe { sph_sha1_close(void_raw_cc, void_raw_dest); };
}
pub fn sha1_init_load_close(data: &str) -> sha1 {
let mut dest: sha1 = [0;20];
let mut cc = ShaSmallContext::default();
sha1_init(&mut cc);
sha1_load(&mut cc, data);
sha1_close(&mut cc, &mut dest);
return dest;
}
pub fn sha224_init(cc: &mut ShaMediumContext) {
let void_raw_cc = to_void_raw_ctx(cc);
unsafe { sph_sha224_init(void_raw_cc) };
}
pub fn sha224_load(cc: &mut ShaMediumContext, data: &str) {
let void_raw_cc = to_void_raw_ctx(cc);
let (void_raw_data, len) = to_void_raw_data(data);
unsafe { sph_sha224(void_raw_cc, void_raw_data, len) };
}
pub fn sha224_close(cc: &mut ShaMediumContext, dest: &mut sha224) {
let void_raw_cc = to_void_raw_ctx(cc);
let void_raw_dest = to_void_raw_dest(dest);
unsafe { sph_sha224_close(void_raw_cc, void_raw_dest); };
}
pub fn sha224_init_load_close(data: &str) -> sha224 {
let mut dest: sha224 = [0;28];
let mut cc = ShaMediumContext::default();
sha224_init(&mut cc);
sha224_load(&mut cc, data);
sha224_close(&mut cc, &mut dest);
return dest;
}
pub fn sha256_init(cc: &mut ShaMediumContext) {
let void_raw_cc = to_void_raw_ctx(cc);
unsafe { sph_sha256_init(void_raw_cc) };
}
pub fn sha256_load(cc: &mut ShaMediumContext, data: &str) {
let void_raw_cc = to_void_raw_ctx(cc);
let (void_raw_data, len) = to_void_raw_data(data);
unsafe { sph_sha224(void_raw_cc, void_raw_data, len) };
}
pub fn sha256_close(cc: &mut ShaMediumContext, dest: &mut sha256) {
let void_raw_cc = to_void_raw_ctx(cc);
let void_raw_dest = to_void_raw_dest(dest);
unsafe { sph_sha256_close(void_raw_cc, void_raw_dest); };
}
pub fn sha256_init_load_close(data: &str) -> sha256 {
let mut dest: sha256 = [0;32];
let mut cc = ShaMediumContext::default();
sha256_init(&mut cc);
sha256_load(&mut cc, data);
sha256_close(&mut cc, &mut dest);
return dest;
}
pub fn sha384_init(cc: &mut ShaBigContext) {
let void_raw_cc = to_void_raw_ctx(cc);
unsafe { sph_sha384_init(void_raw_cc) };
}
pub fn sha384_load(cc: &mut ShaBigContext, data: &str) {
let void_raw_cc = to_void_raw_ctx(cc);
let (void_raw_data, len) = to_void_raw_data(data);
unsafe { sph_sha384(void_raw_cc, void_raw_data, len) };
}
pub fn sha384_close(cc: &mut ShaBigContext, dest: &mut sha384) {
let void_raw_cc = to_void_raw_ctx(cc);
let void_raw_dest = to_void_raw_dest(dest);
unsafe { sph_sha384_close(void_raw_cc, void_raw_dest); };
}
pub fn sha384_init_load_close(data: &str) -> sha384 {
let mut dest: sha384 = [0;48];
let mut cc = ShaBigContext::default();
sha384_init(&mut cc);
sha384_load(&mut cc, data);
sha384_close(&mut cc, &mut dest);
return dest;
}
pub fn sha512_init(cc: &mut ShaBigContext) {
let void_raw_cc = to_void_raw_ctx(cc);
unsafe { sph_sha512_init(void_raw_cc) };
}
pub fn sha512_load(cc: &mut ShaBigContext, data: &str) {
let void_raw_cc = to_void_raw_ctx(cc);
let (void_raw_data, len) = to_void_raw_data(data);
unsafe { sph_sha384(void_raw_cc, void_raw_data, len) };
}
pub fn sha512_close(cc: &mut ShaBigContext, dest: &mut sha512) {
let void_raw_cc = to_void_raw_ctx(cc);
let void_raw_dest = to_void_raw_dest(dest);
unsafe { sph_sha512_close(void_raw_cc, void_raw_dest); };
}
pub fn sha512_init_load_close(data: &str) -> sha512 {
let mut dest: sha512 = [0;64];
let mut cc = ShaBigContext::default();
sha512_init(&mut cc);
sha512_load(&mut cc, data);
sha512_close(&mut cc, &mut dest);
return dest;
}<|fim▁end|> | |
<|file_name|>coincontroldialog.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coincontroldialog.h"
#include "ui_coincontroldialog.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "txmempool.h"
#include "walletmodel.h"
#include "wallet/coincontrol.h"
#include "init.h"
#include "policy/fees.h"
#include "policy/policy.h"
#include "validation.h" // For mempool
#include "wallet/fees.h"
#include "wallet/wallet.h"
#include <QApplication>
#include <QCheckBox>
#include <QCursor>
#include <QDialogButtonBox>
#include <QFlags>
#include <QIcon>
#include <QSettings>
#include <QString>
#include <QTreeWidget>
#include <QTreeWidgetItem>
QList<CAmount> CoinControlDialog::payAmounts;
CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
bool CoinControlDialog::fSubtractFeeFromAmount = false;
bool CCoinControlWidgetItem::operator<(const QTreeWidgetItem &other) const {
int column = treeWidget()->sortColumn();
if (column == CoinControlDialog::COLUMN_AMOUNT || column == CoinControlDialog::COLUMN_DATE || column == CoinControlDialog::COLUMN_CONFIRMATIONS)
return data(column, Qt::UserRole).toLongLong() < other.data(column, Qt::UserRole).toLongLong();
return QTreeWidgetItem::operator<(other);
}
CoinControlDialog::CoinControlDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::CoinControlDialog),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
// context menu actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this
lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this
unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTransactionHashAction);
contextMenu->addSeparator();
contextMenu->addAction(lockAction);
contextMenu->addAction(unlockAction);
// context menu signals
connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));
// clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);<|fim▁hole|> QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// toggle tree/list mode
connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));
// click on checkbox
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int)));
// click on header
#if QT_VERSION < 0x050000
ui->treeWidget->header()->setClickable(true);
#else
ui->treeWidget->header()->setSectionsClickable(true);
#endif
connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));
// ok button
connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
// (un)select all
connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));
// change coin control first column label due Qt4 bug.
// see https://github.com/bitcoin/bitcoin/issues/5716
ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString());
ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 110);
ui->treeWidget->setColumnWidth(COLUMN_LABEL, 190);
ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 320);
ui->treeWidget->setColumnWidth(COLUMN_DATE, 130);
ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 110);
ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transaction hash in this column, but don't show it
ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it
// default view is sorted by amount desc
sortView(COLUMN_AMOUNT, Qt::DescendingOrder);
// restore list mode and sortorder as a convenience feature
QSettings settings;
if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool())
ui->radioTreeMode->click();
if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder"))
sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt()));
}
CoinControlDialog::~CoinControlDialog()
{
QSettings settings;
settings.setValue("nCoinControlMode", ui->radioListMode->isChecked());
settings.setValue("nCoinControlSortColumn", sortColumn);
settings.setValue("nCoinControlSortOrder", (int)sortOrder);
delete ui;
}
void CoinControlDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel() && _model->getAddressTableModel())
{
updateView();
updateLabelLocked();
CoinControlDialog::updateLabels(_model, this);
}
}
// ok button
void CoinControlDialog::buttonBoxClicked(QAbstractButton* button)
{
if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
done(QDialog::Accepted); // closes the dialog
}
// (un)select all
void CoinControlDialog::buttonSelectAllClicked()
{
Qt::CheckState state = Qt::Checked;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
{
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked)
{
state = Qt::Unchecked;
break;
}
}
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state)
ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state);
ui->treeWidget->setEnabled(true);
if (state == Qt::Unchecked)
coinControl->UnSelectAll(); // just to be sure
CoinControlDialog::updateLabels(model, this);
}
// context menu
void CoinControlDialog::showMenu(const QPoint &point)
{
QTreeWidgetItem *item = ui->treeWidget->itemAt(point);
if(item)
{
contextMenuItem = item;
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
copyTransactionHashAction->setEnabled(true);
if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()))
{
lockAction->setEnabled(false);
unlockAction->setEnabled(true);
}
else
{
lockAction->setEnabled(true);
unlockAction->setEnabled(false);
}
}
else // this means click on parent node in tree mode -> disable all
{
copyTransactionHashAction->setEnabled(false);
lockAction->setEnabled(false);
unlockAction->setEnabled(false);
}
// show context menu
contextMenu->exec(QCursor::pos());
}
}
// context menu action: copy amount
void CoinControlDialog::copyAmount()
{
GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT)));
}
// context menu action: copy label
void CoinControlDialog::copyLabel()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL));
}
// context menu action: copy address
void CoinControlDialog::copyAddress()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS));
}
// context menu action: copy transaction id
void CoinControlDialog::copyTransactionHash()
{
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH));
}
// context menu action: lock coin
void CoinControlDialog::lockCoin()
{
if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked)
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed"));
updateLabelLocked();
}
// context menu action: unlock coin
void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->unlockCoin(outpt);
contextMenuItem->setDisabled(false);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
updateLabelLocked();
}
// copy label "Quantity" to clipboard
void CoinControlDialog::clipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// copy label "Amount" to clipboard
void CoinControlDialog::clipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// copy label "Fee" to clipboard
void CoinControlDialog::clipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// copy label "After fee" to clipboard
void CoinControlDialog::clipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// copy label "Bytes" to clipboard
void CoinControlDialog::clipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, ""));
}
// copy label "Dust" to clipboard
void CoinControlDialog::clipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// copy label "Change" to clipboard
void CoinControlDialog::clipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// treeview: sort
void CoinControlDialog::sortView(int column, Qt::SortOrder order)
{
sortColumn = column;
sortOrder = order;
ui->treeWidget->sortItems(column, order);
ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder);
}
// treeview: clicked on header
void CoinControlDialog::headerSectionClicked(int logicalIndex)
{
if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing
{
ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder);
}
else
{
if (sortColumn == logicalIndex)
sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder);
else
{
sortColumn = logicalIndex;
sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc
}
sortView(sortColumn, sortOrder);
}
}
// toggle tree mode
void CoinControlDialog::radioTreeMode(bool checked)
{
if (checked && model)
updateView();
}
// toggle list mode
void CoinControlDialog::radioListMode(bool checked)
{
if (checked && model)
updateView();
}
// checkbox clicked by user
void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
{
if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked)
coinControl->UnSelect(outpt);
else if (item->isDisabled()) // locked (this happens if "check all" through parent node)
item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
else
coinControl->Select(outpt);
// selection changed -> update labels
if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all
CoinControlDialog::updateLabels(model, this);
}
// TODO: Remove this temporary qt5 fix after Qt5.3 and Qt5.4 are no longer used.
// Fixed in Qt5.5 and above: https://bugreports.qt.io/browse/QTBUG-43473
#if QT_VERSION >= 0x050000
else if (column == COLUMN_CHECKBOX && item->childCount() > 0)
{
if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
item->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
#endif
}
// shows count of locked unspent outputs
void CoinControlDialog::updateLabelLocked()
{
std::vector<COutPoint> vOutpts;
model->listLockedCoins(vOutpts);
if (vOutpts.size() > 0)
{
ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
ui->labelLocked->setVisible(true);
}
else ui->labelLocked->setVisible(false);
}
void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
{
if (!model)
return;
// nPayAmount
CAmount nPayAmount = 0;
bool fDust = false;
CMutableTransaction txDummy;
for (const CAmount &amount : CoinControlDialog::payAmounts)
{
nPayAmount += amount;
if (amount > 0)
{
CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0));
txDummy.vout.push_back(txout);
fDust |= IsDust(txout, ::dustRelayFee);
}
}
CAmount nAmount = 0;
CAmount nPayFee = 0;
CAmount nAfterFee = 0;
CAmount nChange = 0;
unsigned int nBytes = 0;
unsigned int nBytesInputs = 0;
unsigned int nQuantity = 0;
bool fWitness = false;
std::vector<COutPoint> vCoinControl;
std::vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
for (const COutput& out : vOutputs) {
// unselect already spent, very unlikely scenario, this could happen
// when selected are spent elsewhere, like rpc or another computer
uint256 txhash = out.tx->GetHash();
COutPoint outpt(txhash, out.i);
if (model->isSpent(outpt))
{
coinControl->UnSelect(outpt);
continue;
}
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->tx->vout[out.i].nValue;
// Bytes
CTxDestination address;
int witnessversion = 0;
std::vector<unsigned char> witnessprogram;
if (out.tx->tx->vout[out.i].scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram))
{
nBytesInputs += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
fWitness = true;
}
else if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address))
{
CPubKey pubkey;
CKeyID *keyid = boost::get<CKeyID>(&address);
if (keyid && model->getPubKey(*keyid, pubkey))
{
nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
}
else
nBytesInputs += 148; // in all error cases, simply assume 148 here
}
else nBytesInputs += 148;
}
// calculation
if (nQuantity > 0)
{
// Bytes
nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here
if (fWitness)
{
// there is some fudging in these numbers related to the actual virtual transaction size calculation that will keep this estimate from being exact.
// usually, the result will be an overestimate within a couple of satoshis so that the confirmation dialog ends up displaying a slightly smaller fee.
// also, the witness stack size value is a variable sized integer. usually, the number of stack items will be well under the single byte var int limit.
nBytes += 2; // account for the serialized marker and flag bytes
nBytes += nQuantity; // account for the witness byte that holds the number of stack items for each input.
}
// in the subtract fee from amount case, we can tell if zero change already and subtract the bytes, so that fee calculation afterwards is accurate
if (CoinControlDialog::fSubtractFeeFromAmount)
if (nAmount - nPayAmount == 0)
nBytes -= 34;
// Fee
nPayFee = GetMinimumFee(nBytes, *coinControl, ::mempool, ::feeEstimator, nullptr /* FeeCalculation */);
if (nPayAmount > 0)
{
nChange = nAmount - nPayAmount;
if (!CoinControlDialog::fSubtractFeeFromAmount)
nChange -= nPayFee;
// Never create dust outputs; if we would, just add the dust to the fee.
if (nChange > 0 && nChange < MIN_CHANGE)
{
CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0));
if (IsDust(txout, ::dustRelayFee))
{
nPayFee += nChange;
nChange = 0;
if (CoinControlDialog::fSubtractFeeFromAmount)
nBytes -= 34; // we didn't detect lack of change above
}
}
if (nChange == 0 && !CoinControlDialog::fSubtractFeeFromAmount)
nBytes -= 34;
}
// after fee
nAfterFee = std::max<CAmount>(nAmount - nPayFee, 0);
}
// actually update labels
int nDisplayUnit = BitcoinUnits::BTC;
if (model && model->getOptionsModel())
nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity");
QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount");
QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee");
QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee");
QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes");
QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput");
QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange");
// enable/disable "dust" and "change"
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0);
// stats
l1->setText(QString::number(nQuantity)); // Quantity
l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount
l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee
l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee
l5->setText(((nBytes > 0) ? ASYMP_UTF8 : "") + QString::number(nBytes)); // Bytes
l7->setText(fDust ? tr("yes") : tr("no")); // Dust
l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change
if (nPayFee > 0)
{
l3->setText(ASYMP_UTF8 + l3->text());
l4->setText(ASYMP_UTF8 + l4->text());
if (nChange > 0 && !CoinControlDialog::fSubtractFeeFromAmount)
l8->setText(ASYMP_UTF8 + l8->text());
}
// turn label red when dust
l7->setStyleSheet((fDust) ? "color:red;" : "");
// tool tips
QString toolTipDust = tr("This label turns red if any recipient receives an amount smaller than the current dust threshold.");
// how many satoshis the estimated fee can vary per byte we guess wrong
assert(nBytes != 0);
double dFeeVary = (double)nPayFee / nBytes;
QString toolTip4 = tr("Can vary +/- %1 satoshi(s) per input.").arg(dFeeVary);
l3->setToolTip(toolTip4);
l4->setToolTip(toolTip4);
l7->setToolTip(toolTipDust);
l8->setToolTip(toolTip4);
dialog->findChild<QLabel *>("labelCoinControlFeeText") ->setToolTip(l3->toolTip());
dialog->findChild<QLabel *>("labelCoinControlAfterFeeText") ->setToolTip(l4->toolTip());
dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip());
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip());
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip());
// Insufficient funds
QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds");
if (label)
label->setVisible(nChange < 0);
}
void CoinControlDialog::updateView()
{
if (!model || !model->getOptionsModel() || !model->getAddressTableModel())
return;
bool treeMode = ui->radioTreeMode->isChecked();
ui->treeWidget->clear();
ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox
ui->treeWidget->setAlternatingRowColors(!treeMode);
QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
int nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
std::map<QString, std::vector<COutput> > mapCoins;
model->listCoins(mapCoins);
for (const std::pair<QString, std::vector<COutput>>& coins : mapCoins) {
CCoinControlWidgetItem *itemWalletAddress = new CCoinControlWidgetItem();
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
QString sWalletAddress = coins.first;
QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
if (sWalletLabel.isEmpty())
sWalletLabel = tr("(no label)");
if (treeMode)
{
// wallet address
ui->treeWidget->addTopLevelItem(itemWalletAddress);
itemWalletAddress->setFlags(flgTristate);
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
// label
itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel);
// address
itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress);
}
CAmount nSum = 0;
int nChildren = 0;
for (const COutput& out : coins.second) {
nSum += out.tx->tx->vout[out.i].nValue;
nChildren++;
CCoinControlWidgetItem *itemOutput;
if (treeMode) itemOutput = new CCoinControlWidgetItem(itemWalletAddress);
else itemOutput = new CCoinControlWidgetItem(ui->treeWidget);
itemOutput->setFlags(flgCheckbox);
itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
// address
CTxDestination outputAddress;
QString sAddress = "";
if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, outputAddress))
{
sAddress = QString::fromStdString(EncodeDestination(outputAddress));
// if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs
if (!treeMode || (!(sAddress == sWalletAddress)))
itemOutput->setText(COLUMN_ADDRESS, sAddress);
}
// label
if (!(sAddress == sWalletAddress)) // change
{
// tooltip from where the change comes from
itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress));
itemOutput->setText(COLUMN_LABEL, tr("(change)"));
}
else if (!treeMode)
{
QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress);
if (sLabel.isEmpty())
sLabel = tr("(no label)");
itemOutput->setText(COLUMN_LABEL, sLabel);
}
// amount
itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->tx->vout[out.i].nValue));
itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.tx->tx->vout[out.i].nValue)); // padding so that sorting works correctly
// date
itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.tx->GetTxTime()));
// confirmations
itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.nDepth));
itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.nDepth));
// transaction hash
uint256 txhash = out.tx->GetHash();
itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex()));
// vout index
itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
// disable locked coins
if (model->isLockedCoin(txhash, out.i))
{
COutPoint outpt(txhash, out.i);
coinControl->UnSelect(outpt); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed"));
}
// set checkbox
if (coinControl->IsSelected(COutPoint(txhash, out.i)))
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
// amount
if (treeMode)
{
itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)nSum));
}
}
// expand all partially selected
if (treeMode)
{
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
ui->treeWidget->topLevelItem(i)->setExpanded(true);
}
// sort view
sortView(sortColumn, sortOrder);
ui->treeWidget->setEnabled(true);
}<|fim▁end|> | QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this); |
<|file_name|>test_localimport.py<|end_file_name|><|fim▁begin|>from nose.tools import *
from localimport import localimport
import os
import sys
modules_dir = os.path.join(os.path.dirname(__file__), 'modules')
def test_localimport_with_autodisable():
sys.path.append(modules_dir)
import another_module as mod_a
try:
with localimport('modules') as _imp:
import some_module
import another_module as mod_b
assert 'some_module' in sys.modules
assert sys.modules['another_module'] is mod_b<|fim▁hole|> assert sys.modules['another_module'] is mod_a
assert mod_a is not mod_b
finally:
sys.path.remove(modules_dir)
del sys.modules['another_module']
def test_localimport_without_autodisable():
sys.path.append(modules_dir)
import another_module as mod_a
try:
with localimport('modules', do_autodisable=False) as _imp:
import some_module
import another_module as mod_b
assert 'some_module' in sys.modules
assert sys.modules['another_module'] is mod_b
assert mod_a is mod_b
assert 'some_module' not in sys.modules
assert sys.modules['another_module'] is mod_a
finally:
sys.path.remove(modules_dir)
del sys.modules['another_module']
def test_localimpot_parent_dir():
with localimport('.', parent_dir=modules_dir) as _imp:
import some_module
assert 'some_module' not in sys.modules
assert 'another_module' not in sys.modules
def test_localimpot_curdir():
with localimport('.') as _imp:
import some_module
assert 'some_module' not in sys.modules
assert 'another_module' not in sys.modules
def test_discover():
with localimport('.') as _imp:
assert_equals(sorted(x.name for x in _imp.discover()), ['another_module', 'some_module', 'test_localimport'])
with localimport('modules') as _imp:
assert_equals(sorted(x.name for x in _imp.discover()), ['another_module', 'some_module'])<|fim▁end|> | assert 'some_module' not in sys.modules |
<|file_name|>call_manager.py<|end_file_name|><|fim▁begin|><|fim▁hole|>../../../../../share/pyshared/papyon/sip/call_manager.py<|fim▁end|> | |
<|file_name|>1572705844584-RemoveOldColumns.ts<|end_file_name|><|fim▁begin|>import {MigrationInterface, QueryRunner} from "typeorm";<|fim▁hole|>export class RemoveOldColumns1572705844584 implements MigrationInterface {
name = 'RemoveOldColumns1572705844584'
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`ALTER TABLE "posts" DROP COLUMN "postType"`, undefined);
}
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`ALTER TABLE "posts" ADD "postType" character varying NOT NULL`, undefined);
}
}<|fim▁end|> | |
<|file_name|>test_140_lcmaps.py<|end_file_name|><|fim▁begin|>import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
class TestLcMaps(osgunittest.OSGTestCase):
required_rpms = ['lcmaps', 'lcmaps-db-templates', 'vo-client', 'vo-client-lcmaps-voms']
def test_01_configure(self):
core.config['lcmaps.db'] = '/etc/lcmaps.db'
core.config['lcmaps.gsi-authz'] = '/etc/grid-security/gsi-authz.conf'
core.skip_ok_unless_installed(*self.required_rpms)
template = files.read('/usr/share/lcmaps/templates/lcmaps.db.vomsmap',
as_single_string=True)
<|fim▁hole|> files.write(core.config['lcmaps.db'], template, owner='lcmaps')
files.write(core.config['lcmaps.gsi-authz'],
"globus_mapping liblcas_lcmaps_gt4_mapping.so lcmaps_callout\n",
owner='lcmaps')
def test_02_old_xrootd_policy(self):
core.skip_ok_unless_installed('xrootd-lcmaps', *self.required_rpms)
self.skip_ok_if(core.PackageVersion('xrootd-lcmaps') >= '1.4.0')
files.append(core.config['lcmaps.db'],
'''xrootd_policy:
verifyproxynokey -> banfile
banfile -> banvomsfile | bad
banvomsfile -> gridmapfile | bad
gridmapfile -> good | vomsmapfile
vomsmapfile -> good | defaultmapfile
defaultmapfile -> good | bad
''',
backup=False)<|fim▁end|> | |
<|file_name|>pd.py<|end_file_name|><|fim▁begin|>##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2018 Max Weller
## Copyright (C) 2019 DreamSourceLab <[email protected]>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##
import re
import sigrokdecode as srd
ann_cmdbit, ann_databit, ann_cmd, ann_data, ann_warning = range(5)
class Decoder(srd.Decoder):
api_version = 3
id = 'sda2506'
name = 'SDA2506'
longname = 'Siemens SDA 2506-5'<|fim▁hole|> outputs = []
tags = ['IC', 'Memory']
channels = (
{'id': 'clk', 'name': 'CLK', 'desc': 'Clock'},
{'id': 'd', 'name': 'DATA', 'desc': 'Data'},
{'id': 'ce', 'name': 'CE#', 'desc': 'Chip-enable'},
)
annotations = (
('cmdbit', 'Command bit'),
('databit', 'Data bit'),
('cmd', 'Command'),
('data', 'Data byte'),
('warnings', 'Human-readable warnings'),
)
annotation_rows = (
('bits', 'Bits', (ann_cmdbit, ann_databit)),
('commands', 'Commands', (ann_cmd,)),
('data', 'Data', (ann_data,)),
('warnings', 'Warnings', (ann_warning,)),
)
def __init__(self):
self.samplerate = None
self.reset()
def reset(self):
self.cmdbits = []
self.databits = []
def metadata(self, key, value):
if key == srd.SRD_CONF_SAMPLERATE:
self.samplerate = value
def start(self):
self.out_ann = self.register(srd.OUTPUT_ANN)
def putbit(self, ss, es, typ, value):
self.put(ss, es, self.out_ann, [typ, ['%s' % (value)]])
def putdata(self, ss, es):
value = 0
for i in range(8):
value = (value << 1) | self.databits[i]
self.put(ss, es, self.out_ann, [ann_data, ['%02X' % (value)]])
def decode_bits(self, offset, width):
out = 0
for i in range(width):
out = (out << 1) | self.cmdbits[offset + i][0]
return (out, self.cmdbits[offset + width - 1][1], self.cmdbits[offset][2])
def decode_field(self, name, offset, width):
val, ss, es = self.decode_bits(offset, width)
self.put(ss, es, self.out_ann, [ann_data, ['%s: %02X' % (name, val)]])
return val
def decode(self):
while True:
# Wait for CLK edge or CE edge.
(clk, d, ce) = self.wait([{0: 'e'}, {2: 'e'}])
if (self.matched & (0b1 << 0)) and ce == 1 and clk == 1:
# Rising clk edge and command mode.
bitstart = self.samplenum
self.wait({0: 'f'})
self.cmdbits = [(d, bitstart, self.samplenum)] + self.cmdbits
if len(self.cmdbits) > 24:
self.cmdbits = self.cmdbits[0:24]
self.putbit(bitstart, self.samplenum, ann_cmdbit, d)
elif (self.matched & (0b1 << 0)) and ce == 0 and clk == 0:
# Falling clk edge and data mode.
bitstart = self.samplenum
(clk, d, ce) = self.wait([{'skip': int(2.5 * (1e6 / self.samplerate))}, {0: 'r'}, {2: 'e'}]) # Wait 25 us for data ready.
if (self.matched & (0b1 << 2)) and not (self.matched & 0b011):
self.wait([{0: 'r'}, {2: 'e'}])
if len(self.databits) == 0:
self.datastart = bitstart
self.databits = [d] + self.databits
self.putbit(bitstart, self.samplenum, ann_databit, d)
if len(self.databits) == 8:
self.putdata(self.datastart, self.samplenum)
self.databits = []
elif (self.matched & (0b1 << 1)) and ce == 0:
# Chip enable edge.
try:
self.decode_field('addr', 1, 7)
self.decode_field('CB', 0, 1)
if self.cmdbits[0][0] == 0:
# Beginning read command.
self.decode_field('read', 1, 7)
self.put(self.cmdbits[7][1], self.samplenum,
self.out_ann, [ann_cmd, ['read' ]])
elif d == 0:
# Beginning write command.
self.decode_field('data', 8, 8)
addr, ss, es = self.decode_bits(1, 7)
data, ss, es = self.decode_bits(8, 8)
cmdstart = self.samplenum
self.wait({2: 'r'})
self.put(cmdstart, self.samplenum, self.out_ann,
[ann_cmd, ['Write to %02X: %02X' % (addr, data)]])
else:
# Beginning erase command.
val, ss, es = self.decode_bits(1, 7)
cmdstart = self.samplenum
self.wait({2: 'r'})
self.put(cmdstart, self.samplenum, self.out_ann,
[ann_cmd, ['Erase: %02X' % (val)]])
self.databits = []
except Exception as ex:
self.reset()<|fim▁end|> | desc = 'Serial nonvolatile 1-Kbit EEPROM.'
license = 'gplv2+'
inputs = ['logic'] |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
__all__ = [<|fim▁hole|> "test_svn",
]
if __name__ == "__main__" :
import doctest
for i in __all__ :
print ("%%-%ds: %%s" % (max(map(len, __all__)) + 1)) % (
i,
doctest.testmod(__import__(i, None, None, [i, ], ), ),
)<|fim▁end|> | "test_config_db",
"test_grid",
"test_shell", |
<|file_name|>0009_auto_20151128_1236.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0008_auto_20151124_1135'),
]
operations = [
migrations.AddField(
model_name='service',
name='short_name',
field=models.CharField(max_length=20, null=True),
),
migrations.AlterField(
model_name='product',
name='unit',
field=models.IntegerField(choices=[(1, b'kg'), (2, b'L')]),
),
migrations.AlterField(
model_name='supplierservice',
name='service',
field=models.ForeignKey(related_name='service_suppliers', to='core.Service'),
),
migrations.AlterField(
model_name='supplierservice',<|fim▁hole|> ]<|fim▁end|> | name='supplier',
field=models.ForeignKey(related_name='supplier_services', to='core.Supplier'),
), |
<|file_name|>UserType.py<|end_file_name|><|fim▁begin|>from sqlalchemy import Column, String, Integer
from BusTrack.repository import Base, session
from BusTrack.repository.models import STRING_LEN_SMALL
class UserType(Base):
__tablename__ = 'user_type'
id = Column(Integer, primary_key=True)
role_name = Column(String(STRING_LEN_SMALL))
@staticmethod
def __create_default_role__():
if session.query(UserType).count() != 0:
return
driver = UserType()
driver.role_name = 'Driver'
parent = UserType()
parent.role_name = 'Parent'
admin = UserType()
admin.role_name = 'Admin'
session.add(driver)<|fim▁hole|>
session.commit()
session.close()<|fim▁end|> | session.add(parent)
session.add(admin) |
<|file_name|>script.py<|end_file_name|><|fim▁begin|># coding=utf8
<|fim▁hole|>import time
from httplib2 import Http
from logging import handlers
LOG_FILE = '../logs/WSCN_client.log'
handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5) # 实例化handler
handler.setFormatter(logging.Formatter('%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'))
logger = logging.getLogger('client')
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
h = Http()
def send():
exchange_type = random_type()
r, c = h.request("http://127.0.0.1:4000/trade.do", "POST",
"{\"symbol\": \"WSCN\", \"type\": \"" + exchange_type + "\", \"amount\": " + random_amount() +
", \"price\": " + random_price() + "}", {"Content-Type": "text/json"})
if exchange_type == "buy" or exchange_type == "sell":
obj = json.loads(c)
logger.info("%s, %s", obj['order_id'], exchange_type)
def random_type():
return str(random.choice(["buy", "sell", "buy_market", "sell_market"]))
def random_amount():
return str(random.randrange(1, 100, 1))
def random_price():
return str(round(random.uniform(90.00, 110.00), 2))
if __name__ == '__main__':
for i in range(0, 1000):
send()
time.sleep(0.230)<|fim▁end|> | import random
import logging
import json |
<|file_name|>exampleSelector.js<|end_file_name|><|fim▁begin|>const createImmutableEqualsSelector = require('./customSelectorCreator');
const compare = require('../util/compare');
const exampleReducers = require('../reducers/exampleReducers');
/**
* Get state function
*/
const getSortingState = exampleReducers.getSortingState;
const getPaginationState = exampleReducers.getPaginationState;
const getDataState = exampleReducers.getDataState;
/**
* Sorting immutable data source
* @param {Map} source immutable data source
* @param {string} sortingKey property of data<|fim▁hole|> */
const sortingData = (source, sortingKey, orderByCondition) => {
let orderBy = orderByCondition === 'asc' ? 1 : -1;
return source.sortBy(data => data.get(sortingKey), (v, k) => orderBy * compare(v, k));
}
/**
* Paginating data from sortingSelector
* @param {List} sortedData immutable data source with sorting
* @param {number} start
* @param {number} end
* @return {array} sorting data with pagination and converting Immutable.List to array
*/
const pagination = (sortedData, start, end) => sortedData.slice(start, end).toList().toJS()
/**
* Partial selector only to do sorting
*/
const sortingSelector = createImmutableEqualsSelector(
[
getDataState, // get data source
getSortingState
],
(dataState, sortingCondition) => sortingData(dataState, sortingCondition.get('sortingKey'), sortingCondition.get('orderBy'))
)
/**
* Root selector to paginate data from sortingSelector
*/
const paginationSelector = createImmutableEqualsSelector(
[
sortingSelector, // bind selector to be new data source
getPaginationState
],
(sortedData, paginationCondition) => pagination(sortedData, paginationCondition.get('start'), paginationCondition.get('end'))
)
module.exports = paginationSelector;<|fim▁end|> | * @param {string} orderByCondition 'asc' or 'desc'
* @return {List} immutable testing data source with sorting |
<|file_name|>gae_settings.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from djangoappengine.settings_base import *
DEBUG = True
# By default Django disables debug mode when running test. However in webapi
# tests we need to know if DEBUG was set to True, otherwise testing this
# application would be difficult.
API_TEST_DEBUG = True if DEBUG else False
if DEBUG:
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'static'),
)
else:
STATIC_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'static')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '%sadmin/' % STATIC_URL
SECRET_KEY = '=r-$b*8hglm+858&9t043hlm6-&6-3d3vfc4((7yd0dbrakhvi'
AUTH_PROFILE_MODULE = 'users.UserProfile'
SITE_ID = 1
SITE_DOMAIN = 'example.appspot.com'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True<|fim▁hole|>INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'piston',
)
if DEBUG:
INSTALLED_APPS += ('django.contrib.staticfiles',)
NETADMIN_APPS = (
'netadmin',
'netadmin.reportmeta',
'netadmin.webapi',
'netadmin.networks',
'netadmin.events',
'netadmin.users',
'netadmin.permissions',
'netadmin.notifier',
'netadmin.utils.charts',
'netadmin.plugins'
)
INSTALLED_APPS += NETADMIN_APPS
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.static',
'django.core.context_processors.request',
'django.core.context_processors.media',
)
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
ROOT_URLCONF = 'urls'
LOGIN_URL = '/login/'
ACTIVATION_FROM_EMAIL = '[email protected]'
DATABASES['native'] = DATABASES['default']
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}
GAE_APPS = (
'djangotoolbox',
'dbindexer',
'permission_backend_nonrel',
'autoload',
'search',
'djangoappengine',
)
INSTALLED_APPS += GAE_APPS
AUTHENTICATION_BACKENDS = (
'permission_backend_nonrel.backends.NonrelPermissionBackend',
)
MIDDLEWARE_CLASSES += (
'autoload.middleware.AutoloadMiddleware',
)
TEST_RUNNER = 'djangotoolbox.test.CapturingTestSuiteRunner'
GAE_MAIL_ACCOUNT = '[email protected]'
AUTOLOAD_SITECONF = 'search_indexes'
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
try:
from local_settings import *
except ImportError:
pass<|fim▁end|> | |
<|file_name|>app.bundle.js<|end_file_name|><|fim▁begin|>/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(1);
var _jquery = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"jquery\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var _jquery2 = _interopRequireDefault(_jquery);
var _cats = __webpack_require__(327);
var _cats2 = _interopRequireDefault(_cats);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _jquery2.default)('<h1>Cats</h1>').appendTo('body');
var ul = (0, _jquery2.default)('<ul></ul>').appendTo('body');
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = _cats2.default[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var cat = _step.value;
(0, _jquery2.default)('<li></li>').text(cat).appendTo(ul);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {"use strict";
__webpack_require__(2);
__webpack_require__(323);
__webpack_require__(324);
if (global._babelPolyfill) {
throw new Error("only one instance of babel-polyfill is allowed");
}
global._babelPolyfill = true;
var DEFINE_PROPERTY = "defineProperty";
function define(O, key, value) {
O[key] || Object[DEFINE_PROPERTY](O, key, {
writable: true,
configurable: true,
value: value
});
}
define(String.prototype, "padLeft", "".padStart);
define(String.prototype, "padRight", "".padEnd);
"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) {
[][key] && define(Array, key, Function.call.bind([][key]));
});
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(3);
__webpack_require__(51);
__webpack_require__(52);
__webpack_require__(53);
__webpack_require__(54);
__webpack_require__(56);
__webpack_require__(59);
__webpack_require__(60);
__webpack_require__(61);
__webpack_require__(62);
__webpack_require__(63);
__webpack_require__(64);
__webpack_require__(65);
__webpack_require__(66);
__webpack_require__(67);
__webpack_require__(69);
__webpack_require__(71);
__webpack_require__(73);
__webpack_require__(75);
__webpack_require__(78);
__webpack_require__(79);
__webpack_require__(80);
__webpack_require__(84);
__webpack_require__(86);
__webpack_require__(88);
__webpack_require__(91);
__webpack_require__(92);
__webpack_require__(93);
__webpack_require__(94);
__webpack_require__(96);
__webpack_require__(97);
__webpack_require__(98);
__webpack_require__(99);
__webpack_require__(100);
__webpack_require__(101);
__webpack_require__(102);
__webpack_require__(104);
__webpack_require__(105);
__webpack_require__(106);
__webpack_require__(108);
__webpack_require__(109);
__webpack_require__(110);
__webpack_require__(112);
__webpack_require__(114);
__webpack_require__(115);
__webpack_require__(116);
__webpack_require__(117);
__webpack_require__(118);
__webpack_require__(119);
__webpack_require__(120);
__webpack_require__(121);
__webpack_require__(122);
__webpack_require__(123);
__webpack_require__(124);
__webpack_require__(125);
__webpack_require__(126);
__webpack_require__(131);
__webpack_require__(132);
__webpack_require__(136);
__webpack_require__(137);
__webpack_require__(138);
__webpack_require__(139);
__webpack_require__(141);
__webpack_require__(142);
__webpack_require__(143);
__webpack_require__(144);
__webpack_require__(145);
__webpack_require__(146);
__webpack_require__(147);
__webpack_require__(148);
__webpack_require__(149);
__webpack_require__(150);
__webpack_require__(151);
__webpack_require__(152);
__webpack_require__(153);
__webpack_require__(154);
__webpack_require__(155);
__webpack_require__(157);
__webpack_require__(158);
__webpack_require__(160);
__webpack_require__(161);
__webpack_require__(167);
__webpack_require__(168);
__webpack_require__(170);
__webpack_require__(171);
__webpack_require__(172);
__webpack_require__(176);
__webpack_require__(177);
__webpack_require__(178);
__webpack_require__(179);
__webpack_require__(180);
__webpack_require__(182);
__webpack_require__(183);
__webpack_require__(184);
__webpack_require__(185);
__webpack_require__(188);
__webpack_require__(190);
__webpack_require__(191);
__webpack_require__(192);
__webpack_require__(194);
__webpack_require__(196);
__webpack_require__(198);
__webpack_require__(199);
__webpack_require__(200);
__webpack_require__(202);
__webpack_require__(203);
__webpack_require__(204);
__webpack_require__(205);
__webpack_require__(216);
__webpack_require__(220);
__webpack_require__(221);
__webpack_require__(223);
__webpack_require__(224);
__webpack_require__(228);
__webpack_require__(229);
__webpack_require__(231);
__webpack_require__(232);
__webpack_require__(233);
__webpack_require__(234);
__webpack_require__(235);
__webpack_require__(236);
__webpack_require__(237);
__webpack_require__(238);
__webpack_require__(239);
__webpack_require__(240);
__webpack_require__(241);
__webpack_require__(242);
__webpack_require__(243);
__webpack_require__(244);
__webpack_require__(245);
__webpack_require__(246);
__webpack_require__(247);
__webpack_require__(248);
__webpack_require__(249);
__webpack_require__(251);
__webpack_require__(252);
__webpack_require__(253);
__webpack_require__(254);
__webpack_require__(255);
__webpack_require__(257);
__webpack_require__(258);
__webpack_require__(259);
__webpack_require__(261);
__webpack_require__(262);
__webpack_require__(263);
__webpack_require__(264);
__webpack_require__(265);
__webpack_require__(266);
__webpack_require__(267);
__webpack_require__(268);
__webpack_require__(270);
__webpack_require__(271);
__webpack_require__(273);
__webpack_require__(274);
__webpack_require__(275);
__webpack_require__(276);
__webpack_require__(279);
__webpack_require__(280);
__webpack_require__(282);
__webpack_require__(283);
__webpack_require__(284);
__webpack_require__(285);
__webpack_require__(287);
__webpack_require__(288);
__webpack_require__(289);
__webpack_require__(290);
__webpack_require__(291);
__webpack_require__(292);
__webpack_require__(293);
__webpack_require__(294);
__webpack_require__(295);
__webpack_require__(296);
__webpack_require__(298);
__webpack_require__(299);
__webpack_require__(300);
__webpack_require__(301);
__webpack_require__(302);
__webpack_require__(303);
__webpack_require__(304);
__webpack_require__(305);
__webpack_require__(306);
__webpack_require__(307);
__webpack_require__(308);
__webpack_require__(310);
__webpack_require__(311);
__webpack_require__(312);
__webpack_require__(313);
__webpack_require__(314);
__webpack_require__(315);
__webpack_require__(316);
__webpack_require__(317);
__webpack_require__(318);
__webpack_require__(319);
__webpack_require__(320);
__webpack_require__(321);
__webpack_require__(322);
module.exports = __webpack_require__(9);
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// ECMAScript 6 symbols shim
var global = __webpack_require__(4);
var has = __webpack_require__(5);
var DESCRIPTORS = __webpack_require__(6);
var $export = __webpack_require__(8);
var redefine = __webpack_require__(18);
var META = __webpack_require__(22).KEY;
var $fails = __webpack_require__(7);
var shared = __webpack_require__(23);
var setToStringTag = __webpack_require__(25);
var uid = __webpack_require__(19);
var wks = __webpack_require__(26);
var wksExt = __webpack_require__(27);
var wksDefine = __webpack_require__(28);
var enumKeys = __webpack_require__(29);
var isArray = __webpack_require__(44);
var anObject = __webpack_require__(12);
var isObject = __webpack_require__(13);
var toIObject = __webpack_require__(32);
var toPrimitive = __webpack_require__(16);
var createDesc = __webpack_require__(17);
var _create = __webpack_require__(45);
var gOPNExt = __webpack_require__(48);
var $GOPD = __webpack_require__(50);
var $DP = __webpack_require__(11);
var $keys = __webpack_require__(30);
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function';
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
return _create(dP({}, 'a', {
get: function () { return dP(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (it, key, D) {
var protoDesc = gOPD(ObjectProto, key);
if (protoDesc) delete ObjectProto[key];
dP(it, key, D);
if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function (tag) {
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D) {
if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if (has(AllSymbols, key)) {
if (!D.enumerable) {
if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
D = _create(D, { enumerable: createDesc(0, false) });
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
anObject(it);
var keys = enumKeys(P = toIObject(P));
var i = 0;
var l = keys.length;
var key;
while (l > i) $defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P) {
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
var E = isEnum.call(this, key = toPrimitive(key, true));
if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
it = toIObject(it);
key = toPrimitive(key, true);
if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
var D = gOPD(it, key);
if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
var names = gOPN(toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
var IS_OP = it === ObjectProto;
var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
$Symbol = function Symbol() {
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function (value) {
if (this === ObjectProto) $set.call(OPSymbols, value);
if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString() {
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(49).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(43).f = $propertyIsEnumerable;
__webpack_require__(42).f = $getOwnPropertySymbols;
if (DESCRIPTORS && !__webpack_require__(24)) {
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function (name) {
return wrap(wks(name));
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });
for (var es6Symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function (key) {
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
},
useSetter: function () { setter = true; },
useSimple: function () { setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it) {
var args = [it];
var i = 1;
var replacer, $replacer;
while (arguments.length > i) args.push(arguments[i++]);
$replacer = replacer = args[1];
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ }),
/* 4 */
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/***/ }),
/* 5 */
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(7)(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 7 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4);
var core = __webpack_require__(9);
var hide = __webpack_require__(10);
var redefine = __webpack_require__(18);
var ctx = __webpack_require__(20);
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
var key, own, out, exp;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if (target) redefine(target, key, out, type & $export.U);
// export
if (exports[key] != out) hide(exports, key, exp);
if (IS_PROTO && expProto[key] != out) expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/* 9 */
/***/ (function(module, exports) {
var core = module.exports = { version: '2.5.7' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(11);
var createDesc = __webpack_require__(17);
module.exports = __webpack_require__(6) ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(12);
var IE8_DOM_DEFINE = __webpack_require__(14);
var toPrimitive = __webpack_require__(16);
var dP = Object.defineProperty;
exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/* 13 */
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () {
return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
var document = __webpack_require__(4).document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(13);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/* 17 */
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4);
var hide = __webpack_require__(10);
var has = __webpack_require__(5);
var SRC = __webpack_require__(19)('src');
var TO_STRING = 'toString';
var $toString = Function[TO_STRING];
var TPL = ('' + $toString).split(TO_STRING);
__webpack_require__(9).inspectSource = function (it) {
return $toString.call(it);
};
(module.exports = function (O, key, val, safe) {
var isFunction = typeof val == 'function';
if (isFunction) has(val, 'name') || hide(val, 'name', key);
if (O[key] === val) return;
if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if (O === global) {
O[key] = val;
} else if (!safe) {
delete O[key];
hide(O, key, val);
} else if (O[key]) {
O[key] = val;
} else {
hide(O, key, val);
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString() {
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
/***/ }),
/* 19 */
/***/ (function(module, exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(21);
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/* 21 */
/***/ (function(module, exports) {
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
var META = __webpack_require__(19)('meta');
var isObject = __webpack_require__(13);
var has = __webpack_require__(5);
var setDesc = __webpack_require__(11).f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
return true;
};
var FREEZE = !__webpack_require__(7)(function () {
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
setDesc(it, META, { value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
} });
};
var fastKey = function (it, create) {
// return primitive with prefix
if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function (it, create) {
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
var core = __webpack_require__(9);
var global = __webpack_require__(4);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: core.version,
mode: __webpack_require__(24) ? 'pure' : 'global',
copyright: '© 2018 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/* 24 */
/***/ (function(module, exports) {
module.exports = false;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
var def = __webpack_require__(11).f;
var has = __webpack_require__(5);
var TAG = __webpack_require__(26)('toStringTag');
module.exports = function (it, tag, stat) {
if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__(23)('wks');
var uid = __webpack_require__(19);
var Symbol = __webpack_require__(4).Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(26);
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4);
var core = __webpack_require__(9);
var LIBRARY = __webpack_require__(24);
var wksExt = __webpack_require__(27);
var defineProperty = __webpack_require__(11).f;
module.exports = function (name) {
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(30);
var gOPS = __webpack_require__(42);
var pIE = __webpack_require__(43);
module.exports = function (it) {
var result = getKeys(it);
var getSymbols = gOPS.f;
if (getSymbols) {
var symbols = getSymbols(it);
var isEnum = pIE.f;
var i = 0;
var key;
while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
} return result;
};
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(31);
var enumBugKeys = __webpack_require__(41);
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(5);
var toIObject = __webpack_require__(32);
var arrayIndexOf = __webpack_require__(36)(false);
var IE_PROTO = __webpack_require__(40)('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(33);
var defined = __webpack_require__(35);
module.exports = function (it) {
return IObject(defined(it));
};
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(34);
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/* 34 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/* 35 */
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(32);
var toLength = __webpack_require__(37);
var toAbsoluteIndex = __webpack_require__(39);
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(38);
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/* 38 */
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(38);
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(23)('keys');
var uid = __webpack_require__(19);
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/* 41 */
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/* 42 */
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/* 43 */
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(34);
module.exports = Array.isArray || function isArray(arg) {
return cof(arg) == 'Array';
};
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(12);
var dPs = __webpack_require__(46);
var enumBugKeys = __webpack_require__(41);
var IE_PROTO = __webpack_require__(40)('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(15)('iframe');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
__webpack_require__(47).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(11);
var anObject = __webpack_require__(12);
var getKeys = __webpack_require__(30);
module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = getKeys(Properties);
var length = keys.length;
var i = 0;
var P;
while (length > i) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
var document = __webpack_require__(4).document;
module.exports = document && document.documentElement;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(32);
var gOPN = __webpack_require__(49).f;
var toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return gOPN(it);
} catch (e) {
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it) {
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(31);
var hiddenKeys = __webpack_require__(41).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return $keys(O, hiddenKeys);
};
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(43);
var createDesc = __webpack_require__(17);
var toIObject = __webpack_require__(32);
var toPrimitive = __webpack_require__(16);
var has = __webpack_require__(5);
var IE8_DOM_DEFINE = __webpack_require__(14);
var gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) {
O = toIObject(O);
P = toPrimitive(P, true);
if (IE8_DOM_DEFINE) try {
return gOPD(O, P);
} catch (e) { /* empty */ }
if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: __webpack_require__(45) });
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f });
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(46) });
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(32);
var $getOwnPropertyDescriptor = __webpack_require__(50).f;
__webpack_require__(55)('getOwnPropertyDescriptor', function () {
return function getOwnPropertyDescriptor(it, key) {
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(8);
var core = __webpack_require__(9);
var fails = __webpack_require__(7);
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(57);
var $getPrototypeOf = __webpack_require__(58);
__webpack_require__(55)('getPrototypeOf', function () {
return function getPrototypeOf(it) {
return $getPrototypeOf(toObject(it));
};
});
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(35);
module.exports = function (it) {
return Object(defined(it));
};
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(5);
var toObject = __webpack_require__(57);
var IE_PROTO = __webpack_require__(40)('IE_PROTO');
var ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(57);
var $keys = __webpack_require__(30);
__webpack_require__(55)('keys', function () {
return function keys(it) {
return $keys(toObject(it));
};
});
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(55)('getOwnPropertyNames', function () {
return __webpack_require__(48).f;
});
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.5 Object.freeze(O)
var isObject = __webpack_require__(13);
var meta = __webpack_require__(22).onFreeze;
__webpack_require__(55)('freeze', function ($freeze) {
return function freeze(it) {
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.17 Object.seal(O)
var isObject = __webpack_require__(13);
var meta = __webpack_require__(22).onFreeze;
__webpack_require__(55)('seal', function ($seal) {
return function seal(it) {
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.15 Object.preventExtensions(O)
var isObject = __webpack_require__(13);
var meta = __webpack_require__(22).onFreeze;
__webpack_require__(55)('preventExtensions', function ($preventExtensions) {
return function preventExtensions(it) {
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(13);
__webpack_require__(55)('isFrozen', function ($isFrozen) {
return function isFrozen(it) {
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(13);
__webpack_require__(55)('isSealed', function ($isSealed) {
return function isSealed(it) {
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(13);
__webpack_require__(55)('isExtensible', function ($isExtensible) {
return function isExtensible(it) {
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(8);
$export($export.S + $export.F, 'Object', { assign: __webpack_require__(68) });
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(30);
var gOPS = __webpack_require__(42);
var pIE = __webpack_require__(43);
var toObject = __webpack_require__(57);
var IObject = __webpack_require__(33);
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(7)(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = gOPS.f;
var isEnum = pIE.f;
while (aLen > index) {
var S = IObject(arguments[index++]);
var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
} return T;
} : $assign;
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(8);
$export($export.S, 'Object', { is: __webpack_require__(70) });
/***/ }),
/* 70 */
/***/ (function(module, exports) {
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y) {
// eslint-disable-next-line no-self-compare
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(8);
$export($export.S, 'Object', { setPrototypeOf: __webpack_require__(72).set });
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(13);
var anObject = __webpack_require__(12);
var check = function (O, proto) {
anObject(O);
if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function (test, buggy, set) {
try {
set = __webpack_require__(20)(Function.call, __webpack_require__(50).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch (e) { buggy = true; }
return function setPrototypeOf(O, proto) {
check(O, proto);
if (buggy) O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = __webpack_require__(74);
var test = {};
test[__webpack_require__(26)('toStringTag')] = 'z';
if (test + '' != '[object z]') {
__webpack_require__(18)(Object.prototype, 'toString', function toString() {
return '[object ' + classof(this) + ']';
}, true);
}
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(34);
var TAG = __webpack_require__(26)('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (e) { /* empty */ }
};
module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = __webpack_require__(8);
$export($export.P, 'Function', { bind: __webpack_require__(76) });
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var aFunction = __webpack_require__(21);
var isObject = __webpack_require__(13);
var invoke = __webpack_require__(77);
var arraySlice = [].slice;
var factories = {};
var construct = function (F, len, args) {
if (!(len in factories)) {
for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']';
// eslint-disable-next-line no-new-func
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /* , ...args */) {
var fn = aFunction(this);
var partArgs = arraySlice.call(arguments, 1);
var bound = function (/* args... */) {
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if (isObject(fn.prototype)) bound.prototype = fn.prototype;
return bound;
};
/***/ }),
/* 77 */
/***/ (function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function (fn, args, that) {
var un = that === undefined;
switch (args.length) {
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(11).f;
var FProto = Function.prototype;
var nameRE = /^\s*function ([^ (]*)/;
var NAME = 'name';
// 19.2.4.2 name
NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, {
configurable: true,
get: function () {
try {
return ('' + this).match(nameRE)[1];
} catch (e) {
return '';
}
}
});
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var isObject = __webpack_require__(13);
var getPrototypeOf = __webpack_require__(58);
var HAS_INSTANCE = __webpack_require__(26)('hasInstance');
var FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) {
if (typeof this != 'function' || !isObject(O)) return false;
if (!isObject(this.prototype)) return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while (O = getPrototypeOf(O)) if (this.prototype === O) return true;
return false;
} });
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
var $parseInt = __webpack_require__(81);
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt });
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
var $parseInt = __webpack_require__(4).parseInt;
var $trim = __webpack_require__(82).trim;
var ws = __webpack_require__(83);
var hex = /^[-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) {
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
var defined = __webpack_require__(35);
var fails = __webpack_require__(7);
var spaces = __webpack_require__(83);
var space = '[' + spaces + ']';
var non = '\u200b\u0085';
var ltrim = RegExp('^' + space + space + '*');
var rtrim = RegExp(space + space + '*$');
var exporter = function (KEY, exec, ALIAS) {
var exp = {};
var FORCE = fails(function () {
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if (ALIAS) exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function (string, TYPE) {
string = String(defined(string));
if (TYPE & 1) string = string.replace(ltrim, '');
if (TYPE & 2) string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
/***/ }),
/* 83 */
/***/ (function(module, exports) {
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
var $parseFloat = __webpack_require__(85);
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat });
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
var $parseFloat = __webpack_require__(4).parseFloat;
var $trim = __webpack_require__(82).trim;
module.exports = 1 / $parseFloat(__webpack_require__(83) + '-0') !== -Infinity ? function parseFloat(str) {
var string = $trim(String(str), 3);
var result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(4);
var has = __webpack_require__(5);
var cof = __webpack_require__(34);
var inheritIfRequired = __webpack_require__(87);
var toPrimitive = __webpack_require__(16);
var fails = __webpack_require__(7);
var gOPN = __webpack_require__(49).f;
var gOPD = __webpack_require__(50).f;
var dP = __webpack_require__(11).f;
var $trim = __webpack_require__(82).trim;
var NUMBER = 'Number';
var $Number = global[NUMBER];
var Base = $Number;
var proto = $Number.prototype;
// Opera ~12 has broken Object#toString
var BROKEN_COF = cof(__webpack_require__(45)(proto)) == NUMBER;
var TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function (argument) {
var it = toPrimitive(argument, false);
if (typeof it == 'string' && it.length > 2) {
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0);
var third, radix, maxCode;
if (first === 43 || first === 45) {
third = it.charCodeAt(2);
if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if (first === 48) {
switch (it.charCodeAt(1)) {
case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default: return +it;
}
for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) {
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if (code < 48 || code > maxCode) return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) {
$Number = function Number(value) {
var it = arguments.length < 1 ? 0 : value;
var that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for (var keys = __webpack_require__(6) ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++) {
if (has(Base, key = keys[j]) && !has($Number, key)) {
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
__webpack_require__(18)(global, NUMBER, $Number);
}
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
var setPrototypeOf = __webpack_require__(72).set;
module.exports = function (that, target, C) {
var S = target.constructor;
var P;
if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) {
setPrototypeOf(that, P);
} return that;
};
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var toInteger = __webpack_require__(38);
var aNumberValue = __webpack_require__(89);
var repeat = __webpack_require__(90);
var $toFixed = 1.0.toFixed;
var floor = Math.floor;
var data = [0, 0, 0, 0, 0, 0];
var ERROR = 'Number.toFixed: incorrect invocation!';
var ZERO = '0';
var multiply = function (n, c) {
var i = -1;
var c2 = c;
while (++i < 6) {
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function (n) {
var i = 6;
var c = 0;
while (--i >= 0) {
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function () {
var i = 6;
var s = '';
while (--i >= 0) {
if (s !== '' || i === 0 || data[i] !== 0) {
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function (x, n, acc) {
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function (x) {
var n = 0;
var x2 = x;
while (x2 >= 4096) {
n += 12;
x2 /= 4096;
}
while (x2 >= 2) {
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128.0.toFixed(0) !== '1000000000000000128'
) || !__webpack_require__(7)(function () {
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits) {
var x = aNumberValue(this, ERROR);
var f = toInteger(fractionDigits);
var s = '';
var m = ZERO;
var e, z, j, k;
if (f < 0 || f > 20) throw RangeError(ERROR);
// eslint-disable-next-line no-self-compare
if (x != x) return 'NaN';
if (x <= -1e21 || x >= 1e21) return String(x);
if (x < 0) {
s = '-';
x = -x;
}
if (x > 1e-21) {
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if (e > 0) {
multiply(0, z);
j = f;
while (j >= 7) {
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while (j >= 23) {
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if (f > 0) {
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
var cof = __webpack_require__(34);
module.exports = function (it, msg) {
if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg);
return +it;
};
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var toInteger = __webpack_require__(38);
var defined = __webpack_require__(35);
module.exports = function repeat(count) {
var str = String(defined(this));
var res = '';
var n = toInteger(count);
if (n < 0 || n == Infinity) throw RangeError("Count can't be negative");
for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str;
return res;
};
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $fails = __webpack_require__(7);
var aNumberValue = __webpack_require__(89);
var $toPrecision = 1.0.toPrecision;
$export($export.P + $export.F * ($fails(function () {
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function () {
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision) {
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(8);
$export($export.S, 'Number', { EPSILON: Math.pow(2, -52) });
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.2 Number.isFinite(number)
var $export = __webpack_require__(8);
var _isFinite = __webpack_require__(4).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it) {
return typeof it == 'number' && _isFinite(it);
}
});
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(8);
$export($export.S, 'Number', { isInteger: __webpack_require__(95) });
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(13);
var floor = Math.floor;
module.exports = function isInteger(it) {
return !isObject(it) && isFinite(it) && floor(it) === it;
};
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(8);
$export($export.S, 'Number', {
isNaN: function isNaN(number) {
// eslint-disable-next-line no-self-compare
return number != number;
}
});
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(8);
var isInteger = __webpack_require__(95);
var abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number) {
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(8);
$export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff });
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(8);
$export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff });
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
var $parseFloat = __webpack_require__(85);
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat });
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
var $parseInt = __webpack_require__(81);
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt });
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.3 Math.acosh(x)
var $export = __webpack_require__(8);
var log1p = __webpack_require__(103);
var sqrt = Math.sqrt;
var $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x) {
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
/***/ }),
/* 103 */
/***/ (function(module, exports) {
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x) {
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.5 Math.asinh(x)
var $export = __webpack_require__(8);
var $asinh = Math.asinh;
function asinh(x) {
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh });
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.7 Math.atanh(x)
var $export = __webpack_require__(8);
var $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x) {
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.9 Math.cbrt(x)
var $export = __webpack_require__(8);
var sign = __webpack_require__(107);
$export($export.S, 'Math', {
cbrt: function cbrt(x) {
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
/***/ }),
/* 107 */
/***/ (function(module, exports) {
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x) {
// eslint-disable-next-line no-self-compare
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.11 Math.clz32(x)
var $export = __webpack_require__(8);
$export($export.S, 'Math', {
clz32: function clz32(x) {
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.12 Math.cosh(x)
var $export = __webpack_require__(8);
var exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x) {
return (exp(x = +x) + exp(-x)) / 2;
}
});
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.14 Math.expm1(x)
var $export = __webpack_require__(8);
var $expm1 = __webpack_require__(111);
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 });
/***/ }),
/* 111 */
/***/ (function(module, exports) {
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x) {
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
var $export = __webpack_require__(8);
$export($export.S, 'Math', { fround: __webpack_require__(113) });
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
var sign = __webpack_require__(107);
var pow = Math.pow;
var EPSILON = pow(2, -52);
var EPSILON32 = pow(2, -23);
var MAX32 = pow(2, 127) * (2 - EPSILON32);
var MIN32 = pow(2, -126);
var roundTiesToEven = function (n) {
return n + 1 / EPSILON - 1 / EPSILON;
};
module.exports = Math.fround || function fround(x) {
var $abs = Math.abs(x);
var $sign = sign(x);
var a, result;
if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
// eslint-disable-next-line no-self-compare
if (result > MAX32 || result != result) return $sign * Infinity;
return $sign * result;
};
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = __webpack_require__(8);
var abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars
var sum = 0;
var i = 0;
var aLen = arguments.length;
var larg = 0;
var arg, div;
while (i < aLen) {
arg = abs(arguments[i++]);
if (larg < arg) {
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if (arg > 0) {
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.18 Math.imul(x, y)
var $export = __webpack_require__(8);
var $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * __webpack_require__(7)(function () {
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y) {
var UINT16 = 0xffff;
var xn = +x;
var yn = +y;
var xl = UINT16 & xn;
var yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.21 Math.log10(x)
var $export = __webpack_require__(8);
$export($export.S, 'Math', {
log10: function log10(x) {
return Math.log(x) * Math.LOG10E;
}
});
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.20 Math.log1p(x)
var $export = __webpack_require__(8);
$export($export.S, 'Math', { log1p: __webpack_require__(103) });
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.22 Math.log2(x)
var $export = __webpack_require__(8);
$export($export.S, 'Math', {
log2: function log2(x) {
return Math.log(x) / Math.LN2;
}
});
/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.28 Math.sign(x)
var $export = __webpack_require__(8);
$export($export.S, 'Math', { sign: __webpack_require__(107) });
/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.30 Math.sinh(x)
var $export = __webpack_require__(8);
var expm1 = __webpack_require__(111);
var exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * __webpack_require__(7)(function () {
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x) {
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.33 Math.tanh(x)
var $export = __webpack_require__(8);
var expm1 = __webpack_require__(111);
var exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x) {
var a = expm1(x = +x);
var b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.34 Math.trunc(x)
var $export = __webpack_require__(8);
$export($export.S, 'Math', {
trunc: function trunc(it) {
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
var toAbsoluteIndex = __webpack_require__(39);
var fromCharCode = String.fromCharCode;
var $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars
var res = [];
var aLen = arguments.length;
var i = 0;
var code;
while (aLen > i) {
code = +arguments[i++];
if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
var toIObject = __webpack_require__(32);
var toLength = __webpack_require__(37);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite) {
var tpl = toIObject(callSite.raw);
var len = toLength(tpl.length);
var aLen = arguments.length;
var res = [];
var i = 0;
while (len > i) {
res.push(String(tpl[i++]));
if (i < aLen) res.push(String(arguments[i]));
} return res.join('');
}
});
/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 21.1.3.25 String.prototype.trim()
__webpack_require__(82)('trim', function ($trim) {
return function trim() {
return $trim(this, 3);
};
});
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $at = __webpack_require__(127)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(128)(String, 'String', function (iterated) {
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
var O = this._t;
var index = this._i;
var point;
if (index >= O.length) return { value: undefined, done: true };
point = $at(O, index);
this._i += point.length;
return { value: point, done: false };
});
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(38);
var defined = __webpack_require__(35);
// true -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
return function (that, pos) {
var s = String(defined(that));
var i = toInteger(pos);
var l = s.length;
var a, b;
if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(24);
var $export = __webpack_require__(8);
var redefine = __webpack_require__(18);
var hide = __webpack_require__(10);
var Iterators = __webpack_require__(129);
var $iterCreate = __webpack_require__(130);
var setToStringTag = __webpack_require__(25);
var getPrototypeOf = __webpack_require__(58);
var ITERATOR = __webpack_require__(26)('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';
var returnThis = function () { return this; };
module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); };
} return function entries() { return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = $native || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
$default = function values() { return $native.call(this); };
}
// Define iterator
if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if (DEFAULT) {
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if (FORCED) for (key in methods) {
if (!(key in proto)) redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ }),
/* 129 */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var create = __webpack_require__(45);
var descriptor = __webpack_require__(17);
var setToStringTag = __webpack_require__(25);
var IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(10)(IteratorPrototype, __webpack_require__(26)('iterator'), function () { return this; });
module.exports = function (Constructor, NAME, next) {
Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $at = __webpack_require__(127)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos) {
return $at(this, pos);
}
});
/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = __webpack_require__(8);
var toLength = __webpack_require__(37);
var context = __webpack_require__(133);
var ENDS_WITH = 'endsWith';
var $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /* , endPosition = @length */) {
var that = context(this, searchString, ENDS_WITH);
var endPosition = arguments.length > 1 ? arguments[1] : undefined;
var len = toLength(that.length);
var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len);
var search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__(134);
var defined = __webpack_require__(35);
module.exports = function (that, searchString, NAME) {
if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__(13);
var cof = __webpack_require__(34);
var MATCH = __webpack_require__(26)('match');
module.exports = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__(26)('match');
module.exports = function (KEY) {
var re = /./;
try {
'/./'[KEY](re);
} catch (e) {
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch (f) { /* empty */ }
} return true;
};
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = __webpack_require__(8);
var context = __webpack_require__(133);
var INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', {
includes: function includes(searchString /* , position = 0 */) {
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: __webpack_require__(90)
});
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = __webpack_require__(8);
var toLength = __webpack_require__(37);
var context = __webpack_require__(133);
var STARTS_WITH = 'startsWith';
var $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = context(this, searchString, STARTS_WITH);
var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.2 String.prototype.anchor(name)
__webpack_require__(140)('anchor', function (createHTML) {
return function anchor(name) {
return createHTML(this, 'a', 'name', name);
};
});
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
var fails = __webpack_require__(7);
var defined = __webpack_require__(35);
var quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function (string, tag, attribute, value) {
var S = String(defined(string));
var p1 = '<' + tag;
if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function (NAME, exec) {
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function () {
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.3 String.prototype.big()
__webpack_require__(140)('big', function (createHTML) {
return function big() {
return createHTML(this, 'big', '', '');
};
});
/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.4 String.prototype.blink()
__webpack_require__(140)('blink', function (createHTML) {
return function blink() {
return createHTML(this, 'blink', '', '');
};
});
/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.5 String.prototype.bold()
__webpack_require__(140)('bold', function (createHTML) {
return function bold() {
return createHTML(this, 'b', '', '');
};
});
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.6 String.prototype.fixed()
__webpack_require__(140)('fixed', function (createHTML) {
return function fixed() {
return createHTML(this, 'tt', '', '');
};
});
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
__webpack_require__(140)('fontcolor', function (createHTML) {
return function fontcolor(color) {
return createHTML(this, 'font', 'color', color);
};
});
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
__webpack_require__(140)('fontsize', function (createHTML) {
return function fontsize(size) {
return createHTML(this, 'font', 'size', size);
};
});
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.9 String.prototype.italics()
__webpack_require__(140)('italics', function (createHTML) {
return function italics() {
return createHTML(this, 'i', '', '');
};
});
/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.10 String.prototype.link(url)
__webpack_require__(140)('link', function (createHTML) {
return function link(url) {
return createHTML(this, 'a', 'href', url);
};
});
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.11 String.prototype.small()
__webpack_require__(140)('small', function (createHTML) {
return function small() {
return createHTML(this, 'small', '', '');
};
});
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.12 String.prototype.strike()
__webpack_require__(140)('strike', function (createHTML) {
return function strike() {
return createHTML(this, 'strike', '', '');
};
});
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.13 String.prototype.sub()
__webpack_require__(140)('sub', function (createHTML) {
return function sub() {
return createHTML(this, 'sub', '', '');
};
});
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.14 String.prototype.sup()
__webpack_require__(140)('sup', function (createHTML) {
return function sup() {
return createHTML(this, 'sup', '', '');
};
});
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = __webpack_require__(8);
$export($export.S, 'Date', { now: function () { return new Date().getTime(); } });
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var toObject = __webpack_require__(57);
var toPrimitive = __webpack_require__(16);
$export($export.P + $export.F * __webpack_require__(7)(function () {
return new Date(NaN).toJSON() !== null
|| Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1;
}), 'Date', {
// eslint-disable-next-line no-unused-vars
toJSON: function toJSON(key) {
var O = toObject(this);
var pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = __webpack_require__(8);
var toISOString = __webpack_require__(156);
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', {
toISOString: toISOString
});
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var fails = __webpack_require__(7);
var getTime = Date.prototype.getTime;
var $toISOString = Date.prototype.toISOString;
var lz = function (num) {
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
module.exports = (fails(function () {
return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z';
}) || !fails(function () {
$toISOString.call(new Date(NaN));
})) ? function toISOString() {
if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value');
var d = this;
var y = d.getUTCFullYear();
var m = d.getUTCMilliseconds();
var s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
} : $toISOString;
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
var DateProto = Date.prototype;
var INVALID_DATE = 'Invalid Date';
var TO_STRING = 'toString';
var $toString = DateProto[TO_STRING];
var getTime = DateProto.getTime;
if (new Date(NaN) + '' != INVALID_DATE) {
__webpack_require__(18)(DateProto, TO_STRING, function toString() {
var value = getTime.call(this);
// eslint-disable-next-line no-self-compare
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive');
var proto = Date.prototype;
if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(159));
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var anObject = __webpack_require__(12);
var toPrimitive = __webpack_require__(16);
var NUMBER = 'number';
module.exports = function (hint) {
if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = __webpack_require__(8);
$export($export.S, 'Array', { isArray: __webpack_require__(44) });
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var ctx = __webpack_require__(20);
var $export = __webpack_require__(8);
var toObject = __webpack_require__(57);
var call = __webpack_require__(162);
var isArrayIter = __webpack_require__(163);
var toLength = __webpack_require__(37);
var createProperty = __webpack_require__(164);
var getIterFn = __webpack_require__(165);
$export($export.S + $export.F * !__webpack_require__(166)(function (iter) { Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var index = 0;
var iterFn = getIterFn(O);
var length, result, step, iterator;
if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for (result = new C(length); length > index; index++) {
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(12);
module.exports = function (iterator, fn, value, entries) {
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (e) {
var ret = iterator['return'];
if (ret !== undefined) anObject(ret.call(iterator));
throw e;
}
};
/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(129);
var ITERATOR = __webpack_require__(26)('iterator');
var ArrayProto = Array.prototype;
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $defineProperty = __webpack_require__(11);
var createDesc = __webpack_require__(17);
module.exports = function (object, index, value) {
if (index in object) $defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__(74);
var ITERATOR = __webpack_require__(26)('iterator');
var Iterators = __webpack_require__(129);
module.exports = __webpack_require__(9).getIteratorMethod = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(26)('iterator');
var SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function () { SAFE_CLOSING = true; };
// eslint-disable-next-line no-throw-literal
Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }
module.exports = function (exec, skipClosing) {
if (!skipClosing && !SAFE_CLOSING) return false;
var safe = false;
try {
var arr = [7];
var iter = arr[ITERATOR]();
iter.next = function () { return { done: safe = true }; };
arr[ITERATOR] = function () { return iter; };
exec(arr);
} catch (e) { /* empty */ }
return safe;
};
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var createProperty = __webpack_require__(164);
// WebKit Array.of isn't generic
$export($export.S + $export.F * __webpack_require__(7)(function () {
function F() { /* empty */ }
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */) {
var index = 0;
var aLen = arguments.length;
var result = new (typeof this == 'function' ? this : Array)(aLen);
while (aLen > index) createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = __webpack_require__(8);
var toIObject = __webpack_require__(32);
var arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(169)(arrayJoin)), 'Array', {
join: function join(separator) {
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var fails = __webpack_require__(7);
module.exports = function (method, arg) {
return !!method && fails(function () {
// eslint-disable-next-line no-useless-call
arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null);
});
};
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var html = __webpack_require__(47);
var cof = __webpack_require__(34);
var toAbsoluteIndex = __webpack_require__(39);
var toLength = __webpack_require__(37);
var arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * __webpack_require__(7)(function () {
if (html) arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end) {
var len = toLength(this.length);
var klass = cof(this);
end = end === undefined ? len : end;
if (klass == 'Array') return arraySlice.call(this, begin, end);
var start = toAbsoluteIndex(begin, len);
var upTo = toAbsoluteIndex(end, len);
var size = toLength(upTo - start);
var cloned = new Array(size);
var i = 0;
for (; i < size; i++) cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var aFunction = __webpack_require__(21);
var toObject = __webpack_require__(57);
var fails = __webpack_require__(7);
var $sort = [].sort;
var test = [1, 2, 3];
$export($export.P + $export.F * (fails(function () {
// IE8-
test.sort(undefined);
}) || !fails(function () {
// V8 bug
test.sort(null);
// Old WebKit
}) || !__webpack_require__(169)($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn) {
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $forEach = __webpack_require__(173)(0);
var STRICT = __webpack_require__(169)([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */) {
return $forEach(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(20);
var IObject = __webpack_require__(33);
var toObject = __webpack_require__(57);
var toLength = __webpack_require__(37);
var asc = __webpack_require__(174);
module.exports = function (TYPE, $create) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
var create = $create || asc;
return function ($this, callbackfn, that) {
var O = toObject($this);
var self = IObject(O);
var f = ctx(callbackfn, that, 3);
var length = toLength(self.length);
var index = 0;
var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
var val, res;
for (;length > index; index++) if (NO_HOLES || index in self) {
val = self[index];
res = f(val, index, O);
if (TYPE) {
if (IS_MAP) result[index] = res; // map
else if (res) switch (TYPE) {
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __webpack_require__(175);
module.exports = function (original, length) {
return new (speciesConstructor(original))(length);
};
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
var isArray = __webpack_require__(44);
var SPECIES = __webpack_require__(26)('species');
module.exports = function (original) {
var C;
if (isArray(original)) {
C = original.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return C === undefined ? Array : C;
};
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $map = __webpack_require__(173)(1);
$export($export.P + $export.F * !__webpack_require__(169)([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $filter = __webpack_require__(173)(2);
$export($export.P + $export.F * !__webpack_require__(169)([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $some = __webpack_require__(173)(3);
$export($export.P + $export.F * !__webpack_require__(169)([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */) {
return $some(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $every = __webpack_require__(173)(4);
$export($export.P + $export.F * !__webpack_require__(169)([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */) {
return $every(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $reduce = __webpack_require__(181);
$export($export.P + $export.F * !__webpack_require__(169)([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
var aFunction = __webpack_require__(21);
var toObject = __webpack_require__(57);
var IObject = __webpack_require__(33);
var toLength = __webpack_require__(37);
module.exports = function (that, callbackfn, aLen, memo, isRight) {
aFunction(callbackfn);
var O = toObject(that);
var self = IObject(O);
var length = toLength(O.length);
var index = isRight ? length - 1 : 0;
var i = isRight ? -1 : 1;
if (aLen < 2) for (;;) {
if (index in self) {
memo = self[index];
index += i;
break;
}
index += i;
if (isRight ? index < 0 : length <= index) {
throw TypeError('Reduce of empty array with no initial value');
}
}
for (;isRight ? index >= 0 : length > index; index += i) if (index in self) {
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $reduce = __webpack_require__(181);
$export($export.P + $export.F * !__webpack_require__(169)([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $indexOf = __webpack_require__(36)(false);
var $native = [].indexOf;
var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var toIObject = __webpack_require__(32);
var toInteger = __webpack_require__(38);
var toLength = __webpack_require__(37);
var $native = [].lastIndexOf;
var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
// convert -0 to +0
if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0;
var O = toIObject(this);
var length = toLength(O.length);
var index = length - 1;
if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1]));
if (index < 0) index = length + index;
for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0;
return -1;
}
});
/***/ }),
/* 185 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(8);
$export($export.P, 'Array', { copyWithin: __webpack_require__(186) });
__webpack_require__(187)('copyWithin');
/***/ }),
/* 186 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = __webpack_require__(57);
var toAbsoluteIndex = __webpack_require__(39);
var toLength = __webpack_require__(37);
module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
var O = toObject(this);
var len = toLength(O.length);
var to = toAbsoluteIndex(target, len);
var from = toAbsoluteIndex(start, len);
var end = arguments.length > 2 ? arguments[2] : undefined;
var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
var inc = 1;
if (from < to && to < from + count) {
inc = -1;
from += count - 1;
to += count - 1;
}
while (count-- > 0) {
if (from in O) O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__(26)('unscopables');
var ArrayProto = Array.prototype;
if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {});
module.exports = function (key) {
ArrayProto[UNSCOPABLES][key] = true;
};
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(8);
$export($export.P, 'Array', { fill: __webpack_require__(189) });
__webpack_require__(187)('fill');
/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = __webpack_require__(57);
var toAbsoluteIndex = __webpack_require__(39);
var toLength = __webpack_require__(37);
module.exports = function fill(value /* , start = 0, end = @length */) {
var O = toObject(this);
var length = toLength(O.length);
var aLen = arguments.length;
var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length);
var end = aLen > 2 ? arguments[2] : undefined;
var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
while (endPos > index) O[index++] = value;
return O;
};
/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__(8);
var $find = __webpack_require__(173)(5);
var KEY = 'find';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(187)(KEY);
/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = __webpack_require__(8);
var $find = __webpack_require__(173)(6);
var KEY = 'findIndex';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(187)(KEY);
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(193)('Array');
/***/ }),
/* 193 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(4);
var dP = __webpack_require__(11);
var DESCRIPTORS = __webpack_require__(6);
var SPECIES = __webpack_require__(26)('species');
module.exports = function (KEY) {
var C = global[KEY];
if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
configurable: true,
get: function () { return this; }
});
};
/***/ }),
/* 194 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var addToUnscopables = __webpack_require__(187);
var step = __webpack_require__(195);
var Iterators = __webpack_require__(129);
var toIObject = __webpack_require__(32);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(128)(Array, 'Array', function (iterated, kind) {
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
var O = this._t;
var kind = this._k;
var index = this._i++;
if (!O || index >= O.length) {
this._t = undefined;
return step(1);
}
if (kind == 'keys') return step(0, index);
if (kind == 'values') return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ }),
/* 195 */
/***/ (function(module, exports) {
module.exports = function (done, value) {
return { value: value, done: !!done };
};
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4);
var inheritIfRequired = __webpack_require__(87);
var dP = __webpack_require__(11).f;
var gOPN = __webpack_require__(49).f;
var isRegExp = __webpack_require__(134);
var $flags = __webpack_require__(197);
var $RegExp = global.RegExp;
var Base = $RegExp;
var proto = $RegExp.prototype;
var re1 = /a/g;
var re2 = /a/g;
// "new" creates a new object, old webkit buggy here
var CORRECT_NEW = new $RegExp(re1) !== re1;
if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () {
re2[__webpack_require__(26)('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))) {
$RegExp = function RegExp(p, f) {
var tiRE = this instanceof $RegExp;
var piRE = isRegExp(p);
var fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function (key) {
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function () { return Base[key]; },
set: function (it) { Base[key] = it; }
});
};
for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
__webpack_require__(18)(global, 'RegExp', $RegExp);
}
__webpack_require__(193)('RegExp');
/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__(12);
module.exports = function () {
var that = anObject(this);
var result = '';
if (that.global) result += 'g';
if (that.ignoreCase) result += 'i';
if (that.multiline) result += 'm';
if (that.unicode) result += 'u';
if (that.sticky) result += 'y';
return result;
};
/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(199);
var anObject = __webpack_require__(12);
var $flags = __webpack_require__(197);
var DESCRIPTORS = __webpack_require__(6);
var TO_STRING = 'toString';
var $toString = /./[TO_STRING];
var define = function (fn) {
__webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) {
define(function toString() {
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if ($toString.name != TO_STRING) {
define(function toString() {
return $toString.call(this);
});
}
/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {
// 21.2.5.3 get RegExp.prototype.flags()
if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', {
configurable: true,
get: __webpack_require__(197)
});
/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {
// @@match logic
__webpack_require__(201)('match', 1, function (defined, MATCH, $match) {
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp) {
'use strict';
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var hide = __webpack_require__(10);
var redefine = __webpack_require__(18);
var fails = __webpack_require__(7);
var defined = __webpack_require__(35);
var wks = __webpack_require__(26);
module.exports = function (KEY, length, exec) {
var SYMBOL = wks(KEY);
var fns = exec(defined, SYMBOL, ''[KEY]);
var strfn = fns[0];
var rxfn = fns[1];
if (fails(function () {
var O = {};
O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
})) {
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function (string, arg) { return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function (string) { return rxfn.call(string, this); }
);
}
};
/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {
// @@replace logic
__webpack_require__(201)('replace', 2, function (defined, REPLACE, $replace) {
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue) {
'use strict';
var O = defined(this);
var fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {
// @@search logic
__webpack_require__(201)('search', 1, function (defined, SEARCH, $search) {
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp) {
'use strict';
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
/***/ }),
/* 204 */
/***/ (function(module, exports, __webpack_require__) {
// @@split logic
__webpack_require__(201)('split', 2, function (defined, SPLIT, $split) {
'use strict';
var isRegExp = __webpack_require__(134);
var _split = $split;
var $push = [].push;
var $SPLIT = 'split';
var LENGTH = 'length';
var LAST_INDEX = 'lastIndex';
if (
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
) {
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function (separator, limit) {
var string = String(this);
if (separator === undefined && limit === 0) return [];
// If `separator` is not a regex, use native split
if (!isRegExp(separator)) return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while (match = separatorCopy.exec(string)) {
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if (lastIndex > lastLastIndex) {
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
// eslint-disable-next-line no-loop-func
if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () {
for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined;
});
if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if (output[LENGTH] >= splitLimit) break;
}
if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if (lastLastIndex === string[LENGTH]) {
if (lastLength || !separatorCopy.test('')) output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if ('0'[$SPLIT](undefined, 0)[LENGTH]) {
$split = function (separator, limit) {
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit) {
var O = defined(this);
var fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
/***/ }),
/* 205 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(24);
var global = __webpack_require__(4);
var ctx = __webpack_require__(20);
var classof = __webpack_require__(74);
var $export = __webpack_require__(8);
var isObject = __webpack_require__(13);
var aFunction = __webpack_require__(21);
var anInstance = __webpack_require__(206);
var forOf = __webpack_require__(207);
var speciesConstructor = __webpack_require__(208);
var task = __webpack_require__(209).set;
var microtask = __webpack_require__(210)();
var newPromiseCapabilityModule = __webpack_require__(211);
var perform = __webpack_require__(212);
var userAgent = __webpack_require__(213);
var promiseResolve = __webpack_require__(214);
var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var versions = process && process.versions;
var v8 = versions && versions.v8 || '';
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';
var empty = function () { /* empty */ };
var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
var USE_NATIVE = !!function () {
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1);
var FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function (exec) {
exec(empty, empty);
};
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function')
&& promise.then(empty) instanceof FakePromise
// v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// we can't detect it synchronously, so just check versions
&& v8.indexOf('6.6') !== 0
&& userAgent.indexOf('Chrome/66') === -1;
} catch (e) { /* empty */ }
}();
// helpers
var isThenable = function (it) {
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (promise, isReject) {
if (promise._n) return;
promise._n = true;
var chain = promise._c;
microtask(function () {
var value = promise._v;
var ok = promise._s == 1;
var i = 0;
var run = function (reaction) {
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (promise._h == 2) onHandleUnhandled(promise);
promise._h = 1;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // may throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) {
reject(TypeError('Promise-chain cycle'));
} else if (then = isThenable(result)) {
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (e) {
if (domain && !exited) domain.exit();
reject(e);
}
};
while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if (isReject && !promise._h) onUnhandled(promise);
});
};
var onUnhandled = function (promise) {
task.call(global, function () {
var value = promise._v;
var unhandled = isUnhandled(promise);
var result, handler, console;
if (unhandled) {
result = perform(function () {
if (isNode) {
process.emit('unhandledRejection', value, promise);
} else if (handler = global.onunhandledrejection) {
handler({ promise: promise, reason: value });
} else if ((console = global.console) && console.error) {
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if (unhandled && result.e) throw result.v;
});
};
var isUnhandled = function (promise) {
return promise._h !== 1 && (promise._a || promise._c).length === 0;
};
var onHandleUnhandled = function (promise) {
task.call(global, function () {
var handler;
if (isNode) {
process.emit('rejectionHandled', promise);
} else if (handler = global.onrejectionhandled) {
handler({ promise: promise, reason: promise._v });
}
});
};
var $reject = function (value) {
var promise = this;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if (!promise._a) promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function (value) {
var promise = this;
var then;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if (promise === value) throw TypeError("Promise can't be resolved itself");
if (then = isThenable(value)) {
microtask(function () {
var wrapper = { _w: promise, _d: false }; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch (e) {
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch (e) {
$reject.call({ _w: promise, _d: false }, e); // wrap
}
};
// constructor polyfill
if (!USE_NATIVE) {
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor) {
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch (err) {
$reject.call(this, err);
}
};
// eslint-disable-next-line no-unused-vars
Internal = function Promise(executor) {
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__(215)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected) {
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if (this._a) this._a.push(reaction);
if (this._s) notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
OwnPromiseCapability = function () {
var promise = new Internal();
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
return C === $Promise || C === Wrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
__webpack_require__(25)($Promise, PROMISE);
__webpack_require__(193)(PROMISE);
Wrapper = __webpack_require__(9)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r) {
var capability = newPromiseCapability(this);
var $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x) {
return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(166)(function (iter) {
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var values = [];
var index = 0;
var remaining = 1;
forOf(iterable, false, function (promise) {
var $index = index++;
var alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.e) reject(result.v);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var reject = capability.reject;
var result = perform(function () {
forOf(iterable, false, function (promise) {
C.resolve(promise).then(capability.resolve, reject);
});
});
if (result.e) reject(result.v);
return capability.promise;
}
});
/***/ }),
/* 206 */
/***/ (function(module, exports) {
module.exports = function (it, Constructor, name, forbiddenField) {
if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(20);
var call = __webpack_require__(162);
var isArrayIter = __webpack_require__(163);
var anObject = __webpack_require__(12);
var toLength = __webpack_require__(37);
var getIterFn = __webpack_require__(165);
var BREAK = {};
var RETURN = {};
var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
var f = ctx(fn, that, entries ? 2 : 1);
var index = 0;
var length, step, iterator, result;
if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if (result === BREAK || result === RETURN) return result;
} else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
result = call(iterator, f, step.value, entries);
if (result === BREAK || result === RETURN) return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(12);
var aFunction = __webpack_require__(21);
var SPECIES = __webpack_require__(26)('species');
module.exports = function (O, D) {
var C = anObject(O).constructor;
var S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(20);
var invoke = __webpack_require__(77);
var html = __webpack_require__(47);
var cel = __webpack_require__(15);
var global = __webpack_require__(4);
var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function () {
var id = +this;
// eslint-disable-next-line no-prototype-builtins
if (queue.hasOwnProperty(id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function (event) {
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!setTask || !clearTask) {
setTask = function setImmediate(fn) {
var args = [];
var i = 1;
while (arguments.length > i) args.push(arguments[i++]);
queue[++counter] = function () {
// eslint-disable-next-line no-new-func
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (__webpack_require__(34)(process) == 'process') {
defer = function (id) {
process.nextTick(ctx(run, id, 1));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if (MessageChannel) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
defer = function (id) {
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in cel('script')) {
defer = function (id) {
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ }),
/* 210 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4);
var macrotask = __webpack_require__(209).set;
var Observer = global.MutationObserver || global.WebKitMutationObserver;
var process = global.process;
var Promise = global.Promise;
var isNode = __webpack_require__(34)(process) == 'process';
module.exports = function () {
var head, last, notify;
var flush = function () {
var parent, fn;
if (isNode && (parent = process.domain)) parent.exit();
while (head) {
fn = head.fn;
head = head.next;
try {
fn();
} catch (e) {
if (head) notify();
else last = undefined;
throw e;
}
} last = undefined;
if (parent) parent.enter();
};
// Node.js
if (isNode) {
notify = function () {
process.nextTick(flush);
};
// browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
} else if (Observer && !(global.navigator && global.navigator.standalone)) {
var toggle = true;
var node = document.createTextNode('');
new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
notify = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (Promise && Promise.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
var promise = Promise.resolve(undefined);
notify = function () {
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function () {
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function (fn) {
var task = { fn: fn, next: undefined };
if (last) last.next = task;
if (!head) {
head = task;
notify();
} last = task;
};
};
/***/ }),
/* 211 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 25.4.1.5 NewPromiseCapability(C)
var aFunction = __webpack_require__(21);
function PromiseCapability(C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
}
module.exports.f = function (C) {
return new PromiseCapability(C);
};
/***/ }),
/* 212 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return { e: false, v: exec() };
} catch (e) {
return { e: true, v: e };
}
};
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4);
var navigator = global.navigator;
module.exports = navigator && navigator.userAgent || '';
/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(12);
var isObject = __webpack_require__(13);
var newPromiseCapability = __webpack_require__(211);
module.exports = function (C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
var redefine = __webpack_require__(18);
module.exports = function (target, src, safe) {
for (var key in src) redefine(target, key, src[key], safe);
return target;
};
/***/ }),
/* 216 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(217);
var validate = __webpack_require__(218);
var MAP = 'Map';
// 23.1 Map Objects
module.exports = __webpack_require__(219)(MAP, function (get) {
return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key) {
var entry = strong.getEntry(validate(this, MAP), key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value) {
return strong.def(validate(this, MAP), key === 0 ? 0 : key, value);
}
}, strong, true);
/***/ }),
/* 217 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var dP = __webpack_require__(11).f;
var create = __webpack_require__(45);
var redefineAll = __webpack_require__(215);
var ctx = __webpack_require__(20);
var anInstance = __webpack_require__(206);
var forOf = __webpack_require__(207);
var $iterDefine = __webpack_require__(128);
var step = __webpack_require__(195);
var setSpecies = __webpack_require__(193);
var DESCRIPTORS = __webpack_require__(6);
var fastKey = __webpack_require__(22).fastKey;
var validate = __webpack_require__(218);
var SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function (that, key) {
// fast case
var index = fastKey(key);
var entry;
if (index !== 'F') return that._i[index];
// frozen object case
for (entry = that._f; entry; entry = entry.n) {
if (entry.k == key) return entry;
}
};
module.exports = {
getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
that._t = NAME; // collection type
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear() {
for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) {
entry.r = true;
if (entry.p) entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function (key) {
var that = validate(this, NAME);
var entry = getEntry(that, key);
if (entry) {
var next = entry.n;
var prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if (prev) prev.n = next;
if (next) next.p = prev;
if (that._f == entry) that._f = next;
if (that._l == entry) that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /* , that = undefined */) {
validate(this, NAME);
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
var entry;
while (entry = entry ? entry.n : this._f) {
f(entry.v, entry.k, this);
// revert to the last existing entry
while (entry && entry.r) entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key) {
return !!getEntry(validate(this, NAME), key);
}
});
if (DESCRIPTORS) dP(C.prototype, 'size', {
get: function () {
return validate(this, NAME)[SIZE];
}
});
return C;
},
def: function (that, key, value) {
var entry = getEntry(that, key);
var prev, index;
// change existing entry
if (entry) {
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if (!that._f) that._f = entry;
if (prev) prev.n = entry;
that[SIZE]++;
// add to index
if (index !== 'F') that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function (C, NAME, IS_MAP) {
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function (iterated, kind) {
this._t = validate(iterated, NAME); // target
this._k = kind; // kind
this._l = undefined; // previous
}, function () {
var that = this;
var kind = that._k;
var entry = that._l;
// revert to the last existing entry
while (entry && entry.r) entry = entry.p;
// get next entry
if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) {
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if (kind == 'keys') return step(0, entry.k);
if (kind == 'values') return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
/***/ }),
/* 218 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
module.exports = function (it, TYPE) {
if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
return it;
};
/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(4);
var $export = __webpack_require__(8);
var redefine = __webpack_require__(18);
var redefineAll = __webpack_require__(215);
var meta = __webpack_require__(22);
var forOf = __webpack_require__(207);
var anInstance = __webpack_require__(206);
var isObject = __webpack_require__(13);
var fails = __webpack_require__(7);
var $iterDetect = __webpack_require__(166);
var setToStringTag = __webpack_require__(25);
var inheritIfRequired = __webpack_require__(87);
module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
var Base = global[NAME];
var C = Base;
var ADDER = IS_MAP ? 'set' : 'add';
var proto = C && C.prototype;
var O = {};
var fixMethod = function (KEY) {
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function (a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a) {
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
new C().entries().next();
}))) {
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C();
// early implementations not supports chaining
var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });
// most early implementations doesn't supports iterables, most modern - not close it correctly
var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
var BUGGY_ZERO = !IS_WEAK && fails(function () {
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C();
var index = 5;
while (index--) $instance[ADDER](index, index);
return !$instance.has(-0);
});
if (!ACCEPT_ITERABLES) {
C = wrapper(function (target, iterable) {
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base(), target, C);
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
// weak collections should not contains .clear method
if (IS_WEAK && proto.clear) delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);
return C;
};
/***/ }),
/* 220 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(217);
var validate = __webpack_require__(218);
var SET = 'Set';
// 23.2 Set Objects
module.exports = __webpack_require__(219)(SET, function (get) {
return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value) {
return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ }),
/* 221 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var each = __webpack_require__(173)(0);
var redefine = __webpack_require__(18);
var meta = __webpack_require__(22);
var assign = __webpack_require__(68);
var weak = __webpack_require__(222);
var isObject = __webpack_require__(13);
var fails = __webpack_require__(7);
var validate = __webpack_require__(218);
var WEAK_MAP = 'WeakMap';
var getWeak = meta.getWeak;
var isExtensible = Object.isExtensible;
var uncaughtFrozenStore = weak.ufstore;
var tmp = {};
var InternalMap;
var wrapper = function (get) {
return function WeakMap() {
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key) {
if (isObject(key)) {
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value) {
return weak.def(validate(this, WEAK_MAP), key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = __webpack_require__(219)(WEAK_MAP, wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) {
InternalMap = weak.getConstructor(wrapper, WEAK_MAP);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function (key) {
var proto = $WeakMap.prototype;
var method = proto[key];
redefine(proto, key, function (a, b) {
// store frozen objects on internal weakmap shim
if (isObject(a) && !isExtensible(a)) {
if (!this._f) this._f = new InternalMap();
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
/***/ }),
/* 222 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var redefineAll = __webpack_require__(215);
var getWeak = __webpack_require__(22).getWeak;
var anObject = __webpack_require__(12);
var isObject = __webpack_require__(13);
var anInstance = __webpack_require__(206);
var forOf = __webpack_require__(207);
var createArrayMethod = __webpack_require__(173);
var $has = __webpack_require__(5);
var validate = __webpack_require__(218);
var arrayFind = createArrayMethod(5);
var arrayFindIndex = createArrayMethod(6);
var id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function (that) {
return that._l || (that._l = new UncaughtFrozenStore());
};
var UncaughtFrozenStore = function () {
this.a = [];
};
var findUncaughtFrozen = function (store, key) {
return arrayFind(store.a, function (it) {
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function (key) {
var entry = findUncaughtFrozen(this, key);
if (entry) return entry[1];
},
has: function (key) {
return !!findUncaughtFrozen(this, key);
},
set: function (key, value) {
var entry = findUncaughtFrozen(this, key);
if (entry) entry[1] = value;
else this.a.push([key, value]);
},
'delete': function (key) {
var index = arrayFindIndex(this.a, function (it) {
return it[0] === key;
});
if (~index) this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
that._t = NAME; // collection type
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function (key) {
if (!isObject(key)) return false;
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key) {
if (!isObject(key)) return false;
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function (that, key, value) {
var data = getWeak(anObject(key), true);
if (data === true) uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var weak = __webpack_require__(222);
var validate = __webpack_require__(218);
var WEAK_SET = 'WeakSet';
// 23.4 WeakSet Objects
__webpack_require__(219)(WEAK_SET, function (get) {
return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value) {
return weak.def(validate(this, WEAK_SET), value, true);
}
}, weak, false, true);
/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var $typed = __webpack_require__(225);
var buffer = __webpack_require__(226);
var anObject = __webpack_require__(12);
var toAbsoluteIndex = __webpack_require__(39);
var toLength = __webpack_require__(37);
var isObject = __webpack_require__(13);
var ArrayBuffer = __webpack_require__(4).ArrayBuffer;
var speciesConstructor = __webpack_require__(208);
var $ArrayBuffer = buffer.ArrayBuffer;
var $DataView = buffer.DataView;
var $isView = $typed.ABV && ArrayBuffer.isView;
var $slice = $ArrayBuffer.prototype.slice;
var VIEW = $typed.VIEW;
var ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer });
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it) {
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * __webpack_require__(7)(function () {
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end) {
if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength;
var first = toAbsoluteIndex(start, len);
var fin = toAbsoluteIndex(end === undefined ? len : end, len);
var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first));
var viewS = new $DataView(this);
var viewT = new $DataView(result);
var index = 0;
while (first < fin) {
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
__webpack_require__(193)(ARRAY_BUFFER);
/***/ }),
/* 225 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4);
var hide = __webpack_require__(10);
var uid = __webpack_require__(19);
var TYPED = uid('typed_array');
var VIEW = uid('view');
var ABV = !!(global.ArrayBuffer && global.DataView);
var CONSTR = ABV;
var i = 0;
var l = 9;
var Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while (i < l) {
if (Typed = global[TypedArrayConstructors[i++]]) {
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
/***/ }),
/* 226 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(4);
var DESCRIPTORS = __webpack_require__(6);
var LIBRARY = __webpack_require__(24);
var $typed = __webpack_require__(225);
var hide = __webpack_require__(10);
var redefineAll = __webpack_require__(215);
var fails = __webpack_require__(7);
var anInstance = __webpack_require__(206);
var toInteger = __webpack_require__(38);
var toLength = __webpack_require__(37);
var toIndex = __webpack_require__(227);
var gOPN = __webpack_require__(49).f;
var dP = __webpack_require__(11).f;
var arrayFill = __webpack_require__(189);
var setToStringTag = __webpack_require__(25);
var ARRAY_BUFFER = 'ArrayBuffer';
var DATA_VIEW = 'DataView';
var PROTOTYPE = 'prototype';
var WRONG_LENGTH = 'Wrong length!';
var WRONG_INDEX = 'Wrong index!';
var $ArrayBuffer = global[ARRAY_BUFFER];
var $DataView = global[DATA_VIEW];
var Math = global.Math;
var RangeError = global.RangeError;
// eslint-disable-next-line no-shadow-restricted-names
var Infinity = global.Infinity;
var BaseBuffer = $ArrayBuffer;
var abs = Math.abs;
var pow = Math.pow;
var floor = Math.floor;
var log = Math.log;
var LN2 = Math.LN2;
var BUFFER = 'buffer';
var BYTE_LENGTH = 'byteLength';
var BYTE_OFFSET = 'byteOffset';
var $BUFFER = DESCRIPTORS ? '_b' : BUFFER;
var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH;
var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
function packIEEE754(value, mLen, nBytes) {<|fim▁hole|> var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0;
var i = 0;
var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
var e, m, c;
value = abs(value);
// eslint-disable-next-line no-self-compare
if (value != value || value === Infinity) {
// eslint-disable-next-line no-self-compare
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if (value * (c = pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
}
function unpackIEEE754(buffer, mLen, nBytes) {
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = eLen - 7;
var i = nBytes - 1;
var s = buffer[i--];
var e = s & 127;
var m;
s >>= 7;
for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
}
function unpackI32(bytes) {
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
}
function packI8(it) {
return [it & 0xff];
}
function packI16(it) {
return [it & 0xff, it >> 8 & 0xff];
}
function packI32(it) {
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
}
function packF64(it) {
return packIEEE754(it, 52, 8);
}
function packF32(it) {
return packIEEE754(it, 23, 4);
}
function addGetter(C, key, internal) {
dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } });
}
function get(view, bytes, index, isLittleEndian) {
var numIndex = +index;
var intIndex = toIndex(numIndex);
if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b;
var start = intIndex + view[$OFFSET];
var pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
}
function set(view, bytes, index, conversion, value, isLittleEndian) {
var numIndex = +index;
var intIndex = toIndex(numIndex);
if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b;
var start = intIndex + view[$OFFSET];
var pack = conversion(+value);
for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
}
if (!$typed.ABV) {
$ArrayBuffer = function ArrayBuffer(length) {
anInstance(this, $ArrayBuffer, ARRAY_BUFFER);
var byteLength = toIndex(length);
this._b = arrayFill.call(new Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength) {
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH];
var offset = toInteger(byteOffset);
if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if (DESCRIPTORS) {
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset) {
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset) {
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if (!fails(function () {
$ArrayBuffer(1);
}) || !fails(function () {
new $ArrayBuffer(-1); // eslint-disable-line no-new
}) || fails(function () {
new $ArrayBuffer(); // eslint-disable-line no-new
new $ArrayBuffer(1.5); // eslint-disable-line no-new
new $ArrayBuffer(NaN); // eslint-disable-line no-new
return $ArrayBuffer.name != ARRAY_BUFFER;
})) {
$ArrayBuffer = function ArrayBuffer(length) {
anInstance(this, $ArrayBuffer);
return new BaseBuffer(toIndex(length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) {
if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]);
}
if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2));
var $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/ecma262/#sec-toindex
var toInteger = __webpack_require__(38);
var toLength = __webpack_require__(37);
module.exports = function (it) {
if (it === undefined) return 0;
var number = toInteger(it);
var length = toLength(number);
if (number !== length) throw RangeError('Wrong length!');
return length;
};
/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
$export($export.G + $export.W + $export.F * !__webpack_require__(225).ABV, {
DataView: __webpack_require__(226).DataView
});
/***/ }),
/* 229 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(230)('Int8', 1, function (init) {
return function Int8Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
if (__webpack_require__(6)) {
var LIBRARY = __webpack_require__(24);
var global = __webpack_require__(4);
var fails = __webpack_require__(7);
var $export = __webpack_require__(8);
var $typed = __webpack_require__(225);
var $buffer = __webpack_require__(226);
var ctx = __webpack_require__(20);
var anInstance = __webpack_require__(206);
var propertyDesc = __webpack_require__(17);
var hide = __webpack_require__(10);
var redefineAll = __webpack_require__(215);
var toInteger = __webpack_require__(38);
var toLength = __webpack_require__(37);
var toIndex = __webpack_require__(227);
var toAbsoluteIndex = __webpack_require__(39);
var toPrimitive = __webpack_require__(16);
var has = __webpack_require__(5);
var classof = __webpack_require__(74);
var isObject = __webpack_require__(13);
var toObject = __webpack_require__(57);
var isArrayIter = __webpack_require__(163);
var create = __webpack_require__(45);
var getPrototypeOf = __webpack_require__(58);
var gOPN = __webpack_require__(49).f;
var getIterFn = __webpack_require__(165);
var uid = __webpack_require__(19);
var wks = __webpack_require__(26);
var createArrayMethod = __webpack_require__(173);
var createArrayIncludes = __webpack_require__(36);
var speciesConstructor = __webpack_require__(208);
var ArrayIterators = __webpack_require__(194);
var Iterators = __webpack_require__(129);
var $iterDetect = __webpack_require__(166);
var setSpecies = __webpack_require__(193);
var arrayFill = __webpack_require__(189);
var arrayCopyWithin = __webpack_require__(186);
var $DP = __webpack_require__(11);
var $GOPD = __webpack_require__(50);
var dP = $DP.f;
var gOPD = $GOPD.f;
var RangeError = global.RangeError;
var TypeError = global.TypeError;
var Uint8Array = global.Uint8Array;
var ARRAY_BUFFER = 'ArrayBuffer';
var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER;
var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
var PROTOTYPE = 'prototype';
var ArrayProto = Array[PROTOTYPE];
var $ArrayBuffer = $buffer.ArrayBuffer;
var $DataView = $buffer.DataView;
var arrayForEach = createArrayMethod(0);
var arrayFilter = createArrayMethod(2);
var arraySome = createArrayMethod(3);
var arrayEvery = createArrayMethod(4);
var arrayFind = createArrayMethod(5);
var arrayFindIndex = createArrayMethod(6);
var arrayIncludes = createArrayIncludes(true);
var arrayIndexOf = createArrayIncludes(false);
var arrayValues = ArrayIterators.values;
var arrayKeys = ArrayIterators.keys;
var arrayEntries = ArrayIterators.entries;
var arrayLastIndexOf = ArrayProto.lastIndexOf;
var arrayReduce = ArrayProto.reduce;
var arrayReduceRight = ArrayProto.reduceRight;
var arrayJoin = ArrayProto.join;
var arraySort = ArrayProto.sort;
var arraySlice = ArrayProto.slice;
var arrayToString = ArrayProto.toString;
var arrayToLocaleString = ArrayProto.toLocaleString;
var ITERATOR = wks('iterator');
var TAG = wks('toStringTag');
var TYPED_CONSTRUCTOR = uid('typed_constructor');
var DEF_CONSTRUCTOR = uid('def_constructor');
var ALL_CONSTRUCTORS = $typed.CONSTR;
var TYPED_ARRAY = $typed.TYPED;
var VIEW = $typed.VIEW;
var WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function (O, length) {
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function () {
// eslint-disable-next-line no-undef
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () {
new Uint8Array(1).set({});
});
var toOffset = function (it, BYTES) {
var offset = toInteger(it);
if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!');
return offset;
};
var validate = function (it) {
if (isObject(it) && TYPED_ARRAY in it) return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function (C, length) {
if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) {
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function (O, list) {
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function (C, list) {
var index = 0;
var length = list.length;
var result = allocate(C, length);
while (length > index) result[index] = list[index++];
return result;
};
var addGetter = function (it, key, internal) {
dP(it, key, { get: function () { return this._d[internal]; } });
};
var $from = function from(source /* , mapfn, thisArg */) {
var O = toObject(source);
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var iterFn = getIterFn(O);
var i, length, values, result, step, iterator;
if (iterFn != undefined && !isArrayIter(iterFn)) {
for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) {
values.push(step.value);
} O = values;
}
if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2);
for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) {
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/* ...items */) {
var index = 0;
var length = arguments.length;
var result = allocate(this, length);
while (length > index) result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString() {
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /* , end */) {
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /* , thisArg */) {
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /* , thisArg */) {
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /* , thisArg */) {
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /* , thisArg */) {
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /* , thisArg */) {
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /* , fromIndex */) {
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /* , fromIndex */) {
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator) { // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /* , thisArg */) {
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse() {
var that = this;
var length = validate(that).length;
var middle = Math.floor(length / 2);
var index = 0;
var value;
while (index < middle) {
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /* , thisArg */) {
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn) {
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end) {
var O = validate(this);
var length = O.length;
var $begin = toAbsoluteIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end) {
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /* , offset */) {
validate(this);
var offset = toOffset(arguments[1], 1);
var length = this.length;
var src = toObject(arrayLike);
var len = toLength(src.length);
var index = 0;
if (len + offset > length) throw RangeError(WRONG_LENGTH);
while (index < len) this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries() {
return arrayEntries.call(validate(this));
},
keys: function keys() {
return arrayKeys.call(validate(this));
},
values: function values() {
return arrayValues.call(validate(this));
}
};
var isTAIndex = function (target, key) {
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key) {
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc) {
if (isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
) {
target[key] = desc.value;
return target;
} return dP(target, key, desc);
};
if (!ALL_CONSTRUCTORS) {
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if (fails(function () { arrayToString.call({}); })) {
arrayToString = arrayToLocaleString = function toString() {
return arrayJoin.call(this);
};
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function () { /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function () { return this[TYPED_ARRAY]; }
});
// eslint-disable-next-line max-statements
module.exports = function (KEY, BYTES, wrapper, CLAMPED) {
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array';
var GETTER = 'get' + KEY;
var SETTER = 'set' + KEY;
var TypedArray = global[NAME];
var Base = TypedArray || {};
var TAC = TypedArray && getPrototypeOf(TypedArray);
var FORCED = !TypedArray || !$typed.ABV;
var O = {};
var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function (that, index) {
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function (that, index, value) {
var data = that._d;
if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function (that, index) {
dP(that, index, {
get: function () {
return getter(this, index);
},
set: function (value) {
return setter(this, index, value);
},
enumerable: true
});
};
if (FORCED) {
TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME, '_d');
var index = 0;
var offset = 0;
var buffer, byteLength, length, klass;
if (!isObject(data)) {
length = toIndex(data);
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if ($length === undefined) {
if ($len % BYTES) throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if (byteLength < 0) throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if (TYPED_ARRAY in data) {
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while (index < length) addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if (!fails(function () {
TypedArray(1);
}) || !fails(function () {
new TypedArray(-1); // eslint-disable-line no-new
}) || !$iterDetect(function (iter) {
new TypedArray(); // eslint-disable-line no-new
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(1.5); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)) {
TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if (!isObject(data)) return new Base(toIndex(data));
if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if (TYPED_ARRAY in data) return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) {
if (!(key in TypedArray)) hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR];
var CORRECT_ITER_NAME = !!$nativeIterator
&& ($nativeIterator.name == 'values' || $nativeIterator.name == undefined);
var $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) {
dP(TypedArrayPrototype, TAG, {
get: function () { return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES
});
$export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, {
from: $from,
of: $of
});
if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, { set: $set });
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString;
$export($export.P + $export.F * fails(function () {
new TypedArray(1).slice();
}), NAME, { slice: $slice });
$export($export.P + $export.F * (fails(function () {
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString();
}) || !fails(function () {
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, { toLocaleString: $toLocaleString });
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function () { /* empty */ };
/***/ }),
/* 231 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(230)('Uint8', 1, function (init) {
return function Uint8Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(230)('Uint8', 1, function (init) {
return function Uint8ClampedArray(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
}, true);
/***/ }),
/* 233 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(230)('Int16', 2, function (init) {
return function Int16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 234 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(230)('Uint16', 2, function (init) {
return function Uint16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(230)('Int32', 4, function (init) {
return function Int32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 236 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(230)('Uint32', 4, function (init) {
return function Uint32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(230)('Float32', 4, function (init) {
return function Float32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(230)('Float64', 8, function (init) {
return function Float64Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 239 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = __webpack_require__(8);
var aFunction = __webpack_require__(21);
var anObject = __webpack_require__(12);
var rApply = (__webpack_require__(4).Reflect || {}).apply;
var fApply = Function.apply;
// MS Edge argumentsList argument is optional
$export($export.S + $export.F * !__webpack_require__(7)(function () {
rApply(function () { /* empty */ });
}), 'Reflect', {
apply: function apply(target, thisArgument, argumentsList) {
var T = aFunction(target);
var L = anObject(argumentsList);
return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L);
}
});
/***/ }),
/* 240 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = __webpack_require__(8);
var create = __webpack_require__(45);
var aFunction = __webpack_require__(21);
var anObject = __webpack_require__(12);
var isObject = __webpack_require__(13);
var fails = __webpack_require__(7);
var bind = __webpack_require__(76);
var rConstruct = (__webpack_require__(4).Reflect || {}).construct;
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
var NEW_TARGET_BUG = fails(function () {
function F() { /* empty */ }
return !(rConstruct(function () { /* empty */ }, [], F) instanceof F);
});
var ARGS_BUG = !fails(function () {
rConstruct(function () { /* empty */ });
});
$export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', {
construct: function construct(Target, args /* , newTarget */) {
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget);
if (Target == newTarget) {
// w/o altered newTarget, optimization for 0-4 arguments
switch (args.length) {
case 0: return new Target();
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args))();
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype;
var instance = create(isObject(proto) ? proto : Object.prototype);
var result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
/***/ }),
/* 241 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = __webpack_require__(11);
var $export = __webpack_require__(8);
var anObject = __webpack_require__(12);
var toPrimitive = __webpack_require__(16);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * __webpack_require__(7)(function () {
// eslint-disable-next-line no-undef
Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 });
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes) {
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch (e) {
return false;
}
}
});
/***/ }),
/* 242 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = __webpack_require__(8);
var gOPD = __webpack_require__(50).f;
var anObject = __webpack_require__(12);
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey) {
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
/***/ }),
/* 243 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = __webpack_require__(8);
var anObject = __webpack_require__(12);
var Enumerate = function (iterated) {
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = []; // keys
var key;
for (key in iterated) keys.push(key);
};
__webpack_require__(130)(Enumerate, 'Object', function () {
var that = this;
var keys = that._k;
var key;
do {
if (that._i >= keys.length) return { value: undefined, done: true };
} while (!((key = keys[that._i++]) in that._t));
return { value: key, done: false };
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target) {
return new Enumerate(target);
}
});
/***/ }),
/* 244 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = __webpack_require__(50);
var getPrototypeOf = __webpack_require__(58);
var has = __webpack_require__(5);
var $export = __webpack_require__(8);
var isObject = __webpack_require__(13);
var anObject = __webpack_require__(12);
function get(target, propertyKey /* , receiver */) {
var receiver = arguments.length < 3 ? target : arguments[2];
var desc, proto;
if (anObject(target) === receiver) return target[propertyKey];
if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', { get: get });
/***/ }),
/* 245 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = __webpack_require__(50);
var $export = __webpack_require__(8);
var anObject = __webpack_require__(12);
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) {
return gOPD.f(anObject(target), propertyKey);
}
});
/***/ }),
/* 246 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = __webpack_require__(8);
var getProto = __webpack_require__(58);
var anObject = __webpack_require__(12);
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target) {
return getProto(anObject(target));
}
});
/***/ }),
/* 247 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.9 Reflect.has(target, propertyKey)
var $export = __webpack_require__(8);
$export($export.S, 'Reflect', {
has: function has(target, propertyKey) {
return propertyKey in target;
}
});
/***/ }),
/* 248 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.10 Reflect.isExtensible(target)
var $export = __webpack_require__(8);
var anObject = __webpack_require__(12);
var $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target) {
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
/***/ }),
/* 249 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.11 Reflect.ownKeys(target)
var $export = __webpack_require__(8);
$export($export.S, 'Reflect', { ownKeys: __webpack_require__(250) });
/***/ }),
/* 250 */
/***/ (function(module, exports, __webpack_require__) {
// all object keys, includes non-enumerable and symbols
var gOPN = __webpack_require__(49);
var gOPS = __webpack_require__(42);
var anObject = __webpack_require__(12);
var Reflect = __webpack_require__(4).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) {
var keys = gOPN.f(anObject(it));
var getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
/***/ }),
/* 251 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.12 Reflect.preventExtensions(target)
var $export = __webpack_require__(8);
var anObject = __webpack_require__(12);
var $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target) {
anObject(target);
try {
if ($preventExtensions) $preventExtensions(target);
return true;
} catch (e) {
return false;
}
}
});
/***/ }),
/* 252 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = __webpack_require__(11);
var gOPD = __webpack_require__(50);
var getPrototypeOf = __webpack_require__(58);
var has = __webpack_require__(5);
var $export = __webpack_require__(8);
var createDesc = __webpack_require__(17);
var anObject = __webpack_require__(12);
var isObject = __webpack_require__(13);
function set(target, propertyKey, V /* , receiver */) {
var receiver = arguments.length < 4 ? target : arguments[3];
var ownDesc = gOPD.f(anObject(target), propertyKey);
var existingDescriptor, proto;
if (!ownDesc) {
if (isObject(proto = getPrototypeOf(target))) {
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if (has(ownDesc, 'value')) {
if (ownDesc.writable === false || !isObject(receiver)) return false;
if (existingDescriptor = gOPD.f(receiver, propertyKey)) {
if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false;
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
} else dP.f(receiver, propertyKey, createDesc(0, V));
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', { set: set });
/***/ }),
/* 253 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = __webpack_require__(8);
var setProto = __webpack_require__(72);
if (setProto) $export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto) {
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch (e) {
return false;
}
}
});
/***/ }),
/* 254 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/Array.prototype.includes
var $export = __webpack_require__(8);
var $includes = __webpack_require__(36)(true);
$export($export.P, 'Array', {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(187)('includes');
/***/ }),
/* 255 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap
var $export = __webpack_require__(8);
var flattenIntoArray = __webpack_require__(256);
var toObject = __webpack_require__(57);
var toLength = __webpack_require__(37);
var aFunction = __webpack_require__(21);
var arraySpeciesCreate = __webpack_require__(174);
$export($export.P, 'Array', {
flatMap: function flatMap(callbackfn /* , thisArg */) {
var O = toObject(this);
var sourceLen, A;
aFunction(callbackfn);
sourceLen = toLength(O.length);
A = arraySpeciesCreate(O, 0);
flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]);
return A;
}
});
__webpack_require__(187)('flatMap');
/***/ }),
/* 256 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
var isArray = __webpack_require__(44);
var isObject = __webpack_require__(13);
var toLength = __webpack_require__(37);
var ctx = __webpack_require__(20);
var IS_CONCAT_SPREADABLE = __webpack_require__(26)('isConcatSpreadable');
function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) {
var targetIndex = start;
var sourceIndex = 0;
var mapFn = mapper ? ctx(mapper, thisArg, 3) : false;
var element, spreadable;
while (sourceIndex < sourceLen) {
if (sourceIndex in source) {
element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
spreadable = false;
if (isObject(element)) {
spreadable = element[IS_CONCAT_SPREADABLE];
spreadable = spreadable !== undefined ? !!spreadable : isArray(element);
}
if (spreadable && depth > 0) {
targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1;
} else {
if (targetIndex >= 0x1fffffffffffff) throw TypeError();
target[targetIndex] = element;
}
targetIndex++;
}
sourceIndex++;
}
return targetIndex;
}
module.exports = flattenIntoArray;
/***/ }),
/* 257 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten
var $export = __webpack_require__(8);
var flattenIntoArray = __webpack_require__(256);
var toObject = __webpack_require__(57);
var toLength = __webpack_require__(37);
var toInteger = __webpack_require__(38);
var arraySpeciesCreate = __webpack_require__(174);
$export($export.P, 'Array', {
flatten: function flatten(/* depthArg = 1 */) {
var depthArg = arguments[0];
var O = toObject(this);
var sourceLen = toLength(O.length);
var A = arraySpeciesCreate(O, 0);
flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg));
return A;
}
});
__webpack_require__(187)('flatten');
/***/ }),
/* 258 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = __webpack_require__(8);
var $at = __webpack_require__(127)(true);
$export($export.P, 'String', {
at: function at(pos) {
return $at(this, pos);
}
});
/***/ }),
/* 259 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(8);
var $pad = __webpack_require__(260);
var userAgent = __webpack_require__(213);
// https://github.com/zloirock/core-js/issues/280
$export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', {
padStart: function padStart(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
/***/ }),
/* 260 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = __webpack_require__(37);
var repeat = __webpack_require__(90);
var defined = __webpack_require__(35);
module.exports = function (that, maxLength, fillString, left) {
var S = String(defined(that));
var stringLength = S.length;
var fillStr = fillString === undefined ? ' ' : String(fillString);
var intMaxLength = toLength(maxLength);
if (intMaxLength <= stringLength || fillStr == '') return S;
var fillLen = intMaxLength - stringLength;
var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
/***/ }),
/* 261 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(8);
var $pad = __webpack_require__(260);
var userAgent = __webpack_require__(213);
// https://github.com/zloirock/core-js/issues/280
$export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', {
padEnd: function padEnd(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
/***/ }),
/* 262 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(82)('trimLeft', function ($trim) {
return function trimLeft() {
return $trim(this, 1);
};
}, 'trimStart');
/***/ }),
/* 263 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(82)('trimRight', function ($trim) {
return function trimRight() {
return $trim(this, 2);
};
}, 'trimEnd');
/***/ }),
/* 264 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
var $export = __webpack_require__(8);
var defined = __webpack_require__(35);
var toLength = __webpack_require__(37);
var isRegExp = __webpack_require__(134);
var getFlags = __webpack_require__(197);
var RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function (regexp, string) {
this._r = regexp;
this._s = string;
};
__webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next() {
var match = this._r.exec(this._s);
return { value: match, done: match === null };
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp) {
defined(this);
if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!');
var S = String(this);
var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp);
var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
/***/ }),
/* 265 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(28)('asyncIterator');
/***/ }),
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(28)('observable');
/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = __webpack_require__(8);
var ownKeys = __webpack_require__(250);
var toIObject = __webpack_require__(32);
var gOPD = __webpack_require__(50);
var createProperty = __webpack_require__(164);
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
var O = toIObject(object);
var getDesc = gOPD.f;
var keys = ownKeys(O);
var result = {};
var i = 0;
var key, desc;
while (keys.length > i) {
desc = getDesc(O, key = keys[i++]);
if (desc !== undefined) createProperty(result, key, desc);
}
return result;
}
});
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(8);
var $values = __webpack_require__(269)(false);
$export($export.S, 'Object', {
values: function values(it) {
return $values(it);
}
});
/***/ }),
/* 269 */
/***/ (function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(30);
var toIObject = __webpack_require__(32);
var isEnum = __webpack_require__(43).f;
module.exports = function (isEntries) {
return function (it) {
var O = toIObject(it);
var keys = getKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) if (isEnum.call(O, key = keys[i++])) {
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
/***/ }),
/* 270 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(8);
var $entries = __webpack_require__(269)(true);
$export($export.S, 'Object', {
entries: function entries(it) {
return $entries(it);
}
});
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var toObject = __webpack_require__(57);
var aFunction = __webpack_require__(21);
var $defineProperty = __webpack_require__(11);
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
__webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', {
__defineGetter__: function __defineGetter__(P, getter) {
$defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true });
}
});
/***/ }),
/* 272 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// Forced replacement prototype accessors methods
module.exports = __webpack_require__(24) || !__webpack_require__(7)(function () {
var K = Math.random();
// In FF throws only define methods
// eslint-disable-next-line no-undef, no-useless-call
__defineSetter__.call(null, K, function () { /* empty */ });
delete __webpack_require__(4)[K];
});
/***/ }),
/* 273 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var toObject = __webpack_require__(57);
var aFunction = __webpack_require__(21);
var $defineProperty = __webpack_require__(11);
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
__webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', {
__defineSetter__: function __defineSetter__(P, setter) {
$defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true });
}
});
/***/ }),
/* 274 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var toObject = __webpack_require__(57);
var toPrimitive = __webpack_require__(16);
var getPrototypeOf = __webpack_require__(58);
var getOwnPropertyDescriptor = __webpack_require__(50).f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
__webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', {
__lookupGetter__: function __lookupGetter__(P) {
var O = toObject(this);
var K = toPrimitive(P, true);
var D;
do {
if (D = getOwnPropertyDescriptor(O, K)) return D.get;
} while (O = getPrototypeOf(O));
}
});
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(8);
var toObject = __webpack_require__(57);
var toPrimitive = __webpack_require__(16);
var getPrototypeOf = __webpack_require__(58);
var getOwnPropertyDescriptor = __webpack_require__(50).f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
__webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', {
__lookupSetter__: function __lookupSetter__(P) {
var O = toObject(this);
var K = toPrimitive(P, true);
var D;
do {
if (D = getOwnPropertyDescriptor(O, K)) return D.set;
} while (O = getPrototypeOf(O));
}
});
/***/ }),
/* 276 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(8);
$export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(277)('Map') });
/***/ }),
/* 277 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = __webpack_require__(74);
var from = __webpack_require__(278);
module.exports = function (NAME) {
return function toJSON() {
if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
/***/ }),
/* 278 */
/***/ (function(module, exports, __webpack_require__) {
var forOf = __webpack_require__(207);
module.exports = function (iter, ITERATOR) {
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(8);
$export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(277)('Set') });
/***/ }),
/* 280 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-map.of
__webpack_require__(281)('Map');
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/proposal-setmap-offrom/
var $export = __webpack_require__(8);
module.exports = function (COLLECTION) {
$export($export.S, COLLECTION, { of: function of() {
var length = arguments.length;
var A = new Array(length);
while (length--) A[length] = arguments[length];
return new this(A);
} });
};
/***/ }),
/* 282 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-set.of
__webpack_require__(281)('Set');
/***/ }),
/* 283 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of
__webpack_require__(281)('WeakMap');
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of
__webpack_require__(281)('WeakSet');
/***/ }),
/* 285 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-map.from
__webpack_require__(286)('Map');
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/proposal-setmap-offrom/
var $export = __webpack_require__(8);
var aFunction = __webpack_require__(21);
var ctx = __webpack_require__(20);
var forOf = __webpack_require__(207);
module.exports = function (COLLECTION) {
$export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) {
var mapFn = arguments[1];
var mapping, A, n, cb;
aFunction(this);
mapping = mapFn !== undefined;
if (mapping) aFunction(mapFn);
if (source == undefined) return new this();
A = [];
if (mapping) {
n = 0;
cb = ctx(mapFn, arguments[2], 2);
forOf(source, false, function (nextItem) {
A.push(cb(nextItem, n++));
});
} else {
forOf(source, false, A.push, A);
}
return new this(A);
} });
};
/***/ }),
/* 287 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-set.from
__webpack_require__(286)('Set');
/***/ }),
/* 288 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from
__webpack_require__(286)('WeakMap');
/***/ }),
/* 289 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from
__webpack_require__(286)('WeakSet');
/***/ }),
/* 290 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-global
var $export = __webpack_require__(8);
$export($export.G, { global: __webpack_require__(4) });
/***/ }),
/* 291 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-global
var $export = __webpack_require__(8);
$export($export.S, 'System', { global: __webpack_require__(4) });
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-is-error
var $export = __webpack_require__(8);
var cof = __webpack_require__(34);
$export($export.S, 'Error', {
isError: function isError(it) {
return cof(it) === 'Error';
}
});
/***/ }),
/* 293 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(8);
$export($export.S, 'Math', {
clamp: function clamp(x, lower, upper) {
return Math.min(upper, Math.max(lower, x));
}
});
/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(8);
$export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 });
/***/ }),
/* 295 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(8);
var RAD_PER_DEG = 180 / Math.PI;
$export($export.S, 'Math', {
degrees: function degrees(radians) {
return radians * RAD_PER_DEG;
}
});
/***/ }),
/* 296 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(8);
var scale = __webpack_require__(297);
var fround = __webpack_require__(113);
$export($export.S, 'Math', {
fscale: function fscale(x, inLow, inHigh, outLow, outHigh) {
return fround(scale(x, inLow, inHigh, outLow, outHigh));
}
});
/***/ }),
/* 297 */
/***/ (function(module, exports) {
// https://rwaldron.github.io/proposal-math-extensions/
module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) {
if (
arguments.length === 0
// eslint-disable-next-line no-self-compare
|| x != x
// eslint-disable-next-line no-self-compare
|| inLow != inLow
// eslint-disable-next-line no-self-compare
|| inHigh != inHigh
// eslint-disable-next-line no-self-compare
|| outLow != outLow
// eslint-disable-next-line no-self-compare
|| outHigh != outHigh
) return NaN;
if (x === Infinity || x === -Infinity) return x;
return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow;
};
/***/ }),
/* 298 */
/***/ (function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(8);
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1) {
var $x0 = x0 >>> 0;
var $x1 = x1 >>> 0;
var $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
/***/ }),
/* 299 */
/***/ (function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(8);
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1) {
var $x0 = x0 >>> 0;
var $x1 = x1 >>> 0;
var $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
/***/ }),
/* 300 */
/***/ (function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(8);
$export($export.S, 'Math', {
imulh: function imulh(u, v) {
var UINT16 = 0xffff;
var $u = +u;
var $v = +v;
var u0 = $u & UINT16;
var v0 = $v & UINT16;
var u1 = $u >> 16;
var v1 = $v >> 16;
var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
/***/ }),
/* 301 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(8);
$export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI });
/***/ }),
/* 302 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(8);
var DEG_PER_RAD = Math.PI / 180;
$export($export.S, 'Math', {
radians: function radians(degrees) {
return degrees * DEG_PER_RAD;
}
});
/***/ }),
/* 303 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(8);
$export($export.S, 'Math', { scale: __webpack_require__(297) });
/***/ }),
/* 304 */
/***/ (function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(8);
$export($export.S, 'Math', {
umulh: function umulh(u, v) {
var UINT16 = 0xffff;
var $u = +u;
var $v = +v;
var u0 = $u & UINT16;
var v0 = $v & UINT16;
var u1 = $u >>> 16;
var v1 = $v >>> 16;
var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {
// http://jfbastien.github.io/papers/Math.signbit.html
var $export = __webpack_require__(8);
$export($export.S, 'Math', { signbit: function signbit(x) {
// eslint-disable-next-line no-self-compare
return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0;
} });
/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-promise-finally
'use strict';
var $export = __webpack_require__(8);
var core = __webpack_require__(9);
var global = __webpack_require__(4);
var speciesConstructor = __webpack_require__(208);
var promiseResolve = __webpack_require__(214);
$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) {
var C = speciesConstructor(this, core.Promise || global.Promise);
var isFunction = typeof onFinally == 'function';
return this.then(
isFunction ? function (x) {
return promiseResolve(C, onFinally()).then(function () { return x; });
} : onFinally,
isFunction ? function (e) {
return promiseResolve(C, onFinally()).then(function () { throw e; });
} : onFinally
);
} });
/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-promise-try
var $export = __webpack_require__(8);
var newPromiseCapability = __webpack_require__(211);
var perform = __webpack_require__(212);
$export($export.S, 'Promise', { 'try': function (callbackfn) {
var promiseCapability = newPromiseCapability.f(this);
var result = perform(callbackfn);
(result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
return promiseCapability.promise;
} });
/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(309);
var anObject = __webpack_require__(12);
var toMetaKey = metadata.key;
var ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) {
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
} });
/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {
var Map = __webpack_require__(216);
var $export = __webpack_require__(8);
var shared = __webpack_require__(23)('metadata');
var store = shared.store || (shared.store = new (__webpack_require__(221))());
var getOrCreateMetadataMap = function (target, targetKey, create) {
var targetMetadata = store.get(target);
if (!targetMetadata) {
if (!create) return undefined;
store.set(target, targetMetadata = new Map());
}
var keyMetadata = targetMetadata.get(targetKey);
if (!keyMetadata) {
if (!create) return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map());
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function (MetadataKey, O, P) {
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function (MetadataKey, O, P) {
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) {
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function (target, targetKey) {
var metadataMap = getOrCreateMetadataMap(target, targetKey, false);
var keys = [];
if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); });
return keys;
};
var toMetaKey = function (it) {
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function (O) {
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
/***/ }),
/* 310 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(309);
var anObject = __webpack_require__(12);
var toMetaKey = metadata.key;
var getOrCreateMetadataMap = metadata.map;
var store = metadata.store;
metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) {
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]);
var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false;
if (metadataMap.size) return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
} });
/***/ }),
/* 311 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(309);
var anObject = __webpack_require__(12);
var getPrototypeOf = __webpack_require__(58);
var ordinaryHasOwnMetadata = metadata.has;
var ordinaryGetOwnMetadata = metadata.get;
var toMetaKey = metadata.key;
var ordinaryGetMetadata = function (MetadataKey, O, P) {
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) {
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {
var Set = __webpack_require__(220);
var from = __webpack_require__(278);
var metadata = __webpack_require__(309);
var anObject = __webpack_require__(12);
var getPrototypeOf = __webpack_require__(58);
var ordinaryOwnMetadataKeys = metadata.keys;
var toMetaKey = metadata.key;
var ordinaryMetadataKeys = function (O, P) {
var oKeys = ordinaryOwnMetadataKeys(O, P);
var parent = getPrototypeOf(O);
if (parent === null) return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) {
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
} });
/***/ }),
/* 313 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(309);
var anObject = __webpack_require__(12);
var ordinaryGetOwnMetadata = metadata.get;
var toMetaKey = metadata.key;
metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) {
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
/***/ }),
/* 314 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(309);
var anObject = __webpack_require__(12);
var ordinaryOwnMetadataKeys = metadata.keys;
var toMetaKey = metadata.key;
metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) {
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
} });
/***/ }),
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(309);
var anObject = __webpack_require__(12);
var getPrototypeOf = __webpack_require__(58);
var ordinaryHasOwnMetadata = metadata.has;
var toMetaKey = metadata.key;
var ordinaryHasMetadata = function (MetadataKey, O, P) {
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn) return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) {
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
/***/ }),
/* 316 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(309);
var anObject = __webpack_require__(12);
var ordinaryHasOwnMetadata = metadata.has;
var toMetaKey = metadata.key;
metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) {
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
/***/ }),
/* 317 */
/***/ (function(module, exports, __webpack_require__) {
var $metadata = __webpack_require__(309);
var anObject = __webpack_require__(12);
var aFunction = __webpack_require__(21);
var toMetaKey = $metadata.key;
var ordinaryDefineOwnMetadata = $metadata.set;
$metadata.exp({ metadata: function metadata(metadataKey, metadataValue) {
return function decorator(target, targetKey) {
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
} });
/***/ }),
/* 318 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = __webpack_require__(8);
var microtask = __webpack_require__(210)();
var process = __webpack_require__(4).process;
var isNode = __webpack_require__(34)(process) == 'process';
$export($export.G, {
asap: function asap(fn) {
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
/***/ }),
/* 319 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/zenparsing/es-observable
var $export = __webpack_require__(8);
var global = __webpack_require__(4);
var core = __webpack_require__(9);
var microtask = __webpack_require__(210)();
var OBSERVABLE = __webpack_require__(26)('observable');
var aFunction = __webpack_require__(21);
var anObject = __webpack_require__(12);
var anInstance = __webpack_require__(206);
var redefineAll = __webpack_require__(215);
var hide = __webpack_require__(10);
var forOf = __webpack_require__(207);
var RETURN = forOf.RETURN;
var getMethod = function (fn) {
return fn == null ? undefined : aFunction(fn);
};
var cleanupSubscription = function (subscription) {
var cleanup = subscription._c;
if (cleanup) {
subscription._c = undefined;
cleanup();
}
};
var subscriptionClosed = function (subscription) {
return subscription._o === undefined;
};
var closeSubscription = function (subscription) {
if (!subscriptionClosed(subscription)) {
subscription._o = undefined;
cleanupSubscription(subscription);
}
};
var Subscription = function (observer, subscriber) {
anObject(observer);
this._c = undefined;
this._o = observer;
observer = new SubscriptionObserver(this);
try {
var cleanup = subscriber(observer);
var subscription = cleanup;
if (cleanup != null) {
if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); };
else aFunction(cleanup);
this._c = cleanup;
}
} catch (e) {
observer.error(e);
return;
} if (subscriptionClosed(this)) cleanupSubscription(this);
};
Subscription.prototype = redefineAll({}, {
unsubscribe: function unsubscribe() { closeSubscription(this); }
});
var SubscriptionObserver = function (subscription) {
this._s = subscription;
};
SubscriptionObserver.prototype = redefineAll({}, {
next: function next(value) {
var subscription = this._s;
if (!subscriptionClosed(subscription)) {
var observer = subscription._o;
try {
var m = getMethod(observer.next);
if (m) return m.call(observer, value);
} catch (e) {
try {
closeSubscription(subscription);
} finally {
throw e;
}
}
}
},
error: function error(value) {
var subscription = this._s;
if (subscriptionClosed(subscription)) throw value;
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.error);
if (!m) throw value;
value = m.call(observer, value);
} catch (e) {
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
},
complete: function complete(value) {
var subscription = this._s;
if (!subscriptionClosed(subscription)) {
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.complete);
value = m ? m.call(observer, value) : undefined;
} catch (e) {
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
}
}
});
var $Observable = function Observable(subscriber) {
anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber);
};
redefineAll($Observable.prototype, {
subscribe: function subscribe(observer) {
return new Subscription(observer, this._f);
},
forEach: function forEach(fn) {
var that = this;
return new (core.Promise || global.Promise)(function (resolve, reject) {
aFunction(fn);
var subscription = that.subscribe({
next: function (value) {
try {
return fn(value);
} catch (e) {
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
}
});
redefineAll($Observable, {
from: function from(x) {
var C = typeof this === 'function' ? this : $Observable;
var method = getMethod(anObject(x)[OBSERVABLE]);
if (method) {
var observable = anObject(method.call(x));
return observable.constructor === C ? observable : new C(function (observer) {
return observable.subscribe(observer);
});
}
return new C(function (observer) {
var done = false;
microtask(function () {
if (!done) {
try {
if (forOf(x, false, function (it) {
observer.next(it);
if (done) return RETURN;
}) === RETURN) return;
} catch (e) {
if (done) throw e;
observer.error(e);
return;
} observer.complete();
}
});
return function () { done = true; };
});
},
of: function of() {
for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++];
return new (typeof this === 'function' ? this : $Observable)(function (observer) {
var done = false;
microtask(function () {
if (!done) {
for (var j = 0; j < items.length; ++j) {
observer.next(items[j]);
if (done) return;
} observer.complete();
}
});
return function () { done = true; };
});
}
});
hide($Observable.prototype, OBSERVABLE, function () { return this; });
$export($export.G, { Observable: $Observable });
__webpack_require__(193)('Observable');
/***/ }),
/* 320 */
/***/ (function(module, exports, __webpack_require__) {
// ie9- setTimeout & setInterval additional parameters fix
var global = __webpack_require__(4);
var $export = __webpack_require__(8);
var userAgent = __webpack_require__(213);
var slice = [].slice;
var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check
var wrap = function (set) {
return function (fn, time /* , ...args */) {
var boundArgs = arguments.length > 2;
var args = boundArgs ? slice.call(arguments, 2) : false;
return set(boundArgs ? function () {
// eslint-disable-next-line no-new-func
(typeof fn == 'function' ? fn : Function(fn)).apply(this, args);
} : fn, time);
};
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
/***/ }),
/* 321 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(8);
var $task = __webpack_require__(209);
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
/***/ }),
/* 322 */
/***/ (function(module, exports, __webpack_require__) {
var $iterators = __webpack_require__(194);
var getKeys = __webpack_require__(30);
var redefine = __webpack_require__(18);
var global = __webpack_require__(4);
var hide = __webpack_require__(10);
var Iterators = __webpack_require__(129);
var wks = __webpack_require__(26);
var ITERATOR = wks('iterator');
var TO_STRING_TAG = wks('toStringTag');
var ArrayValues = Iterators.Array;
var DOMIterables = {
CSSRuleList: true, // TODO: Not spec compliant, should be false.
CSSStyleDeclaration: false,
CSSValueList: false,
ClientRectList: false,
DOMRectList: false,
DOMStringList: false,
DOMTokenList: true,
DataTransferItemList: false,
FileList: false,
HTMLAllCollection: false,
HTMLCollection: false,
HTMLFormElement: false,
HTMLSelectElement: false,
MediaList: true, // TODO: Not spec compliant, should be false.
MimeTypeArray: false,
NamedNodeMap: false,
NodeList: true,
PaintRequestList: false,
Plugin: false,
PluginArray: false,
SVGLengthList: false,
SVGNumberList: false,
SVGPathSegList: false,
SVGPointList: false,
SVGStringList: false,
SVGTransformList: false,
SourceBufferList: false,
StyleSheetList: true, // TODO: Not spec compliant, should be false.
TextTrackCueList: false,
TextTrackList: false,
TouchList: false
};
for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) {
var NAME = collections[i];
var explicit = DOMIterables[NAME];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
var key;
if (proto) {
if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues);
if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true);
}
}
/***/ }),
/* 323 */
/***/ (function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
!(function(global) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
var inModule = typeof module === "object";
var runtime = global.regeneratorRuntime;
if (runtime) {
if (inModule) {
// If regeneratorRuntime is defined globally and we're in a module,
// make the exports object identical to regeneratorRuntime.
module.exports = runtime;
}
// Don't bother evaluating the rest of this file if the runtime was
// already defined globally.
return;
}
// Define the runtime globally (as expected by generated code) as either
// module.exports (if we're in a module) or a new, empty object.
runtime = global.regeneratorRuntime = inModule ? module.exports : {};
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
runtime.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
runtime.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
runtime.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
runtime.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return Promise.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return Promise.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
resolve(result);
}, reject);
}
}
if (typeof global.process === "object" && global.process.domain) {
invoke = global.process.domain.bind(invoke);
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new Promise(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
runtime.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
runtime.async = function(innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList)
);
return runtime.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
if (delegate.iterator.return) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator";
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
runtime.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
runtime.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
})(
// Among the various tricks for obtaining a reference to the global
// object, this seems to be the most reliable technique that does not
// use indirect eval (which violates Content Security Policy).
typeof global === "object" ? global :
typeof window === "object" ? window :
typeof self === "object" ? self : this
);
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ }),
/* 324 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(325);
module.exports = __webpack_require__(9).RegExp.escape;
/***/ }),
/* 325 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/benjamingr/RexExp.escape
var $export = __webpack_require__(8);
var $re = __webpack_require__(326)(/[\\^$*+?.()|[\]{}]/g, '\\$&');
$export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } });
/***/ }),
/* 326 */
/***/ (function(module, exports) {
module.exports = function (regExp, replace) {
var replacer = replace === Object(replace) ? function (part) {
return replace[part];
} : replace;
return function (it) {
return String(it).replace(regExp, replacer);
};
};
/***/ }),
/* 327 */
/***/ (function(module, exports) {
'use strict';
module.exports = ['dave', 'henry', 'martha'];
/***/ })
/******/ ]);<|fim▁end|> | var buffer = new Array(nBytes);
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1; |
<|file_name|>test_query.py<|end_file_name|><|fim▁begin|># Copyright 2014 Google Inc.
#
# 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.
import unittest
import mock
class TestQuery(unittest.TestCase):
_PROJECT = 'PROJECT'
@staticmethod
def _get_target_class():
from google.cloud.datastore.query import Query
return Query
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def _make_client(self):
return _Client(self._PROJECT)
def test_ctor_defaults(self):
client = self._make_client()
query = self._make_one(client)
self.assertIs(query._client, client)
self.assertEqual(query.project, client.project)
self.assertIsNone(query.kind)
self.assertEqual(query.namespace, client.namespace)
self.assertIsNone(query.ancestor)
self.assertEqual(query.filters, [])
self.assertEqual(query.projection, [])
self.assertEqual(query.order, [])
self.assertEqual(query.distinct_on, [])
def test_ctor_explicit(self):
from google.cloud.datastore.key import Key
_PROJECT = 'OTHER_PROJECT'
_KIND = 'KIND'
_NAMESPACE = 'OTHER_NAMESPACE'
client = self._make_client()
ancestor = Key('ANCESTOR', 123, project=_PROJECT)
FILTERS = [('foo', '=', 'Qux'), ('bar', '<', 17)]
PROJECTION = ['foo', 'bar', 'baz']
ORDER = ['foo', 'bar']
DISTINCT_ON = ['foo']
query = self._make_one(
client,
kind=_KIND,
project=_PROJECT,
namespace=_NAMESPACE,
ancestor=ancestor,
filters=FILTERS,
projection=PROJECTION,
order=ORDER,
distinct_on=DISTINCT_ON,
)
self.assertIs(query._client, client)
self.assertEqual(query.project, _PROJECT)
self.assertEqual(query.kind, _KIND)
self.assertEqual(query.namespace, _NAMESPACE)
self.assertEqual(query.ancestor.path, ancestor.path)
self.assertEqual(query.filters, FILTERS)
self.assertEqual(query.projection, PROJECTION)
self.assertEqual(query.order, ORDER)
self.assertEqual(query.distinct_on, DISTINCT_ON)
def test_ctor_bad_projection(self):
BAD_PROJECTION = object()
self.assertRaises(TypeError, self._make_one, self._make_client(),
projection=BAD_PROJECTION)
def test_ctor_bad_order(self):
BAD_ORDER = object()
self.assertRaises(TypeError, self._make_one, self._make_client(),
order=BAD_ORDER)
def test_ctor_bad_distinct_on(self):
BAD_DISTINCT_ON = object()
self.assertRaises(TypeError, self._make_one, self._make_client(),
distinct_on=BAD_DISTINCT_ON)
def test_ctor_bad_filters(self):
FILTERS_CANT_UNPACK = [('one', 'two')]
self.assertRaises(ValueError, self._make_one, self._make_client(),
filters=FILTERS_CANT_UNPACK)
def test_namespace_setter_w_non_string(self):
query = self._make_one(self._make_client())
def _assign(val):
query.namespace = val
self.assertRaises(ValueError, _assign, object())
def test_namespace_setter(self):
_NAMESPACE = 'OTHER_NAMESPACE'
query = self._make_one(self._make_client())
query.namespace = _NAMESPACE
self.assertEqual(query.namespace, _NAMESPACE)
def test_kind_setter_w_non_string(self):
query = self._make_one(self._make_client())
def _assign(val):
query.kind = val
self.assertRaises(TypeError, _assign, object())
def test_kind_setter_wo_existing(self):
_KIND = 'KIND'
query = self._make_one(self._make_client())
query.kind = _KIND
self.assertEqual(query.kind, _KIND)
def test_kind_setter_w_existing(self):
_KIND_BEFORE = 'KIND_BEFORE'
_KIND_AFTER = 'KIND_AFTER'
query = self._make_one(self._make_client(), kind=_KIND_BEFORE)
self.assertEqual(query.kind, _KIND_BEFORE)
query.kind = _KIND_AFTER
self.assertEqual(query.project, self._PROJECT)
self.assertEqual(query.kind, _KIND_AFTER)
def test_ancestor_setter_w_non_key(self):
query = self._make_one(self._make_client())
def _assign(val):
query.ancestor = val
self.assertRaises(TypeError, _assign, object())
self.assertRaises(TypeError, _assign, ['KIND', 'NAME'])
def test_ancestor_setter_w_key(self):
from google.cloud.datastore.key import Key
_NAME = u'NAME'
key = Key('KIND', 123, project=self._PROJECT)
query = self._make_one(self._make_client())
query.add_filter('name', '=', _NAME)
query.ancestor = key
self.assertEqual(query.ancestor.path, key.path)
def test_ancestor_deleter_w_key(self):
from google.cloud.datastore.key import Key
key = Key('KIND', 123, project=self._PROJECT)
query = self._make_one(client=self._make_client(), ancestor=key)
del query.ancestor
self.assertIsNone(query.ancestor)
def test_add_filter_setter_w_unknown_operator(self):
query = self._make_one(self._make_client())
self.assertRaises(ValueError, query.add_filter,
'firstname', '~~', 'John')
def test_add_filter_w_known_operator(self):
query = self._make_one(self._make_client())
query.add_filter('firstname', '=', u'John')
self.assertEqual(query.filters, [('firstname', '=', u'John')])
def test_add_filter_w_all_operators(self):
query = self._make_one(self._make_client())
query.add_filter('leq_prop', '<=', u'val1')
query.add_filter('geq_prop', '>=', u'val2')
query.add_filter('lt_prop', '<', u'val3')
query.add_filter('gt_prop', '>', u'val4')
query.add_filter('eq_prop', '=', u'val5')
self.assertEqual(len(query.filters), 5)
self.assertEqual(query.filters[0], ('leq_prop', '<=', u'val1'))
self.assertEqual(query.filters[1], ('geq_prop', '>=', u'val2'))
self.assertEqual(query.filters[2], ('lt_prop', '<', u'val3'))
self.assertEqual(query.filters[3], ('gt_prop', '>', u'val4'))
self.assertEqual(query.filters[4], ('eq_prop', '=', u'val5'))
def test_add_filter_w_known_operator_and_entity(self):
from google.cloud.datastore.entity import Entity
query = self._make_one(self._make_client())
other = Entity()
other['firstname'] = u'John'
other['lastname'] = u'Smith'
query.add_filter('other', '=', other)
self.assertEqual(query.filters, [('other', '=', other)])
def test_add_filter_w_whitespace_property_name(self):
query = self._make_one(self._make_client())
PROPERTY_NAME = ' property with lots of space '
query.add_filter(PROPERTY_NAME, '=', u'John')
self.assertEqual(query.filters, [(PROPERTY_NAME, '=', u'John')])
def test_add_filter___key__valid_key(self):
from google.cloud.datastore.key import Key
query = self._make_one(self._make_client())
key = Key('Foo', project=self._PROJECT)
query.add_filter('__key__', '=', key)
self.assertEqual(query.filters, [('__key__', '=', key)])
def test_filter___key__not_equal_operator(self):
from google.cloud.datastore.key import Key
key = Key('Foo', project=self._PROJECT)
query = self._make_one(self._make_client())
query.add_filter('__key__', '<', key)
self.assertEqual(query.filters, [('__key__', '<', key)])
def test_filter___key__invalid_value(self):
query = self._make_one(self._make_client())
self.assertRaises(ValueError, query.add_filter, '__key__', '=', None)
def test_projection_setter_empty(self):
query = self._make_one(self._make_client())
query.projection = []
self.assertEqual(query.projection, [])
def test_projection_setter_string(self):
query = self._make_one(self._make_client())
query.projection = 'field1'
self.assertEqual(query.projection, ['field1'])
def test_projection_setter_non_empty(self):
query = self._make_one(self._make_client())
query.projection = ['field1', 'field2']
self.assertEqual(query.projection, ['field1', 'field2'])
def test_projection_setter_multiple_calls(self):
_PROJECTION1 = ['field1', 'field2']
_PROJECTION2 = ['field3']
query = self._make_one(self._make_client())
query.projection = _PROJECTION1
self.assertEqual(query.projection, _PROJECTION1)
query.projection = _PROJECTION2
self.assertEqual(query.projection, _PROJECTION2)
def test_keys_only(self):
query = self._make_one(self._make_client())
query.keys_only()
self.assertEqual(query.projection, ['__key__'])
def test_key_filter_defaults(self):
from google.cloud.datastore.key import Key
client = self._make_client()
query = self._make_one(client)
self.assertEqual(query.filters, [])
key = Key('Kind', 1234, project='project')
query.key_filter(key)
self.assertEqual(query.filters, [('__key__', '=', key)])
def test_key_filter_explicit(self):
from google.cloud.datastore.key import Key
client = self._make_client()
query = self._make_one(client)
self.assertEqual(query.filters, [])
key = Key('Kind', 1234, project='project')
query.key_filter(key, operator='>')
self.assertEqual(query.filters, [('__key__', '>', key)])
def test_order_setter_empty(self):
query = self._make_one(self._make_client(), order=['foo', '-bar'])
query.order = []
self.assertEqual(query.order, [])
def test_order_setter_string(self):
query = self._make_one(self._make_client())
query.order = 'field'
self.assertEqual(query.order, ['field'])
def test_order_setter_single_item_list_desc(self):
query = self._make_one(self._make_client())
query.order = ['-field']
self.assertEqual(query.order, ['-field'])
def test_order_setter_multiple(self):
query = self._make_one(self._make_client())
query.order = ['foo', '-bar']
self.assertEqual(query.order, ['foo', '-bar'])
def test_distinct_on_setter_empty(self):
query = self._make_one(self._make_client(), distinct_on=['foo', 'bar'])
query.distinct_on = []
self.assertEqual(query.distinct_on, [])
def test_distinct_on_setter_string(self):
query = self._make_one(self._make_client())
query.distinct_on = 'field1'
self.assertEqual(query.distinct_on, ['field1'])
def test_distinct_on_setter_non_empty(self):
query = self._make_one(self._make_client())
query.distinct_on = ['field1', 'field2']
self.assertEqual(query.distinct_on, ['field1', 'field2'])
def test_distinct_on_multiple_calls(self):
_DISTINCT_ON1 = ['field1', 'field2']
_DISTINCT_ON2 = ['field3']
query = self._make_one(self._make_client())
query.distinct_on = _DISTINCT_ON1
self.assertEqual(query.distinct_on, _DISTINCT_ON1)
query.distinct_on = _DISTINCT_ON2
self.assertEqual(query.distinct_on, _DISTINCT_ON2)
<|fim▁hole|> client = self._make_client()
query = self._make_one(client)
iterator = query.fetch()
self.assertIsInstance(iterator, Iterator)
self.assertIs(iterator._query, query)
self.assertIs(iterator.client, client)
self.assertIsNone(iterator.max_results)
self.assertEqual(iterator._offset, 0)
def test_fetch_w_explicit_client(self):
from google.cloud.datastore.query import Iterator
client = self._make_client()
other_client = self._make_client()
query = self._make_one(client)
iterator = query.fetch(limit=7, offset=8, client=other_client)
self.assertIsInstance(iterator, Iterator)
self.assertIs(iterator._query, query)
self.assertIs(iterator.client, other_client)
self.assertEqual(iterator.max_results, 7)
self.assertEqual(iterator._offset, 8)
class TestIterator(unittest.TestCase):
@staticmethod
def _get_target_class():
from google.cloud.datastore.query import Iterator
return Iterator
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_constructor_defaults(self):
query = object()
client = object()
iterator = self._make_one(query, client)
self.assertFalse(iterator._started)
self.assertIs(iterator.client, client)
self.assertIsNotNone(iterator._item_to_value)
self.assertIsNone(iterator.max_results)
self.assertEqual(iterator.page_number, 0)
self.assertIsNone(iterator.next_page_token,)
self.assertEqual(iterator.num_results, 0)
self.assertIs(iterator._query, query)
self.assertIsNone(iterator._offset)
self.assertIsNone(iterator._end_cursor)
self.assertTrue(iterator._more_results)
def test_constructor_explicit(self):
query = object()
client = object()
limit = 43
offset = 9
start_cursor = b'8290\xff'
end_cursor = b'so20rc\ta'
iterator = self._make_one(
query, client, limit=limit, offset=offset,
start_cursor=start_cursor, end_cursor=end_cursor)
self.assertFalse(iterator._started)
self.assertIs(iterator.client, client)
self.assertIsNotNone(iterator._item_to_value)
self.assertEqual(iterator.max_results, limit)
self.assertEqual(iterator.page_number, 0)
self.assertEqual(iterator.next_page_token, start_cursor)
self.assertEqual(iterator.num_results, 0)
self.assertIs(iterator._query, query)
self.assertEqual(iterator._offset, offset)
self.assertEqual(iterator._end_cursor, end_cursor)
self.assertTrue(iterator._more_results)
def test__build_protobuf_empty(self):
from google.cloud.proto.datastore.v1 import query_pb2
from google.cloud.datastore.query import Query
client = _Client(None)
query = Query(client)
iterator = self._make_one(query, client)
pb = iterator._build_protobuf()
expected_pb = query_pb2.Query()
self.assertEqual(pb, expected_pb)
def test__build_protobuf_all_values(self):
from google.cloud.proto.datastore.v1 import query_pb2
from google.cloud.datastore.query import Query
client = _Client(None)
query = Query(client)
limit = 15
offset = 9
start_bytes = b'i\xb7\x1d'
start_cursor = 'abcd'
end_bytes = b'\xc3\x1c\xb3'
end_cursor = 'wxyz'
iterator = self._make_one(
query, client, limit=limit, offset=offset,
start_cursor=start_cursor, end_cursor=end_cursor)
self.assertEqual(iterator.max_results, limit)
iterator.num_results = 4
iterator._skipped_results = 1
pb = iterator._build_protobuf()
expected_pb = query_pb2.Query(
start_cursor=start_bytes,
end_cursor=end_bytes,
offset=offset - iterator._skipped_results,
)
expected_pb.limit.value = limit - iterator.num_results
self.assertEqual(pb, expected_pb)
def test__process_query_results(self):
from google.cloud.proto.datastore.v1 import query_pb2
iterator = self._make_one(None, None,
end_cursor='abcd')
self.assertIsNotNone(iterator._end_cursor)
entity_pbs = [
_make_entity('Hello', 9998, 'PRAHJEKT'),
]
cursor_as_bytes = b'\x9ai\xe7'
cursor = b'mmnn'
skipped_results = 4
more_results_enum = query_pb2.QueryResultBatch.NOT_FINISHED
response_pb = _make_query_response(
entity_pbs, cursor_as_bytes, more_results_enum, skipped_results)
result = iterator._process_query_results(response_pb)
self.assertEqual(result, entity_pbs)
self.assertEqual(iterator._skipped_results, skipped_results)
self.assertEqual(iterator.next_page_token, cursor)
self.assertTrue(iterator._more_results)
def test__process_query_results_done(self):
from google.cloud.proto.datastore.v1 import query_pb2
iterator = self._make_one(None, None,
end_cursor='abcd')
self.assertIsNotNone(iterator._end_cursor)
entity_pbs = [
_make_entity('World', 1234, 'PROJECT'),
]
cursor_as_bytes = b''
skipped_results = 44
more_results_enum = query_pb2.QueryResultBatch.NO_MORE_RESULTS
response_pb = _make_query_response(
entity_pbs, cursor_as_bytes, more_results_enum, skipped_results)
result = iterator._process_query_results(response_pb)
self.assertEqual(result, entity_pbs)
self.assertEqual(iterator._skipped_results, skipped_results)
self.assertIsNone(iterator.next_page_token)
self.assertFalse(iterator._more_results)
def test__process_query_results_bad_enum(self):
iterator = self._make_one(None, None)
more_results_enum = 999
response_pb = _make_query_response(
[], b'', more_results_enum, 0)
with self.assertRaises(ValueError):
iterator._process_query_results(response_pb)
def _next_page_helper(self, txn_id=None):
from google.cloud.iterator import Page
from google.cloud.proto.datastore.v1 import datastore_pb2
from google.cloud.proto.datastore.v1 import entity_pb2
from google.cloud.proto.datastore.v1 import query_pb2
from google.cloud.datastore.query import Query
more_enum = query_pb2.QueryResultBatch.NOT_FINISHED
result = _make_query_response([], b'', more_enum, 0)
project = 'prujekt'
ds_api = _make_datastore_api(result)
if txn_id is None:
client = _Client(project, datastore_api=ds_api)
else:
transaction = mock.Mock(id=txn_id, spec=['id'])
client = _Client(
project, datastore_api=ds_api, transaction=transaction)
query = Query(client)
iterator = self._make_one(query, client)
page = iterator._next_page()
self.assertIsInstance(page, Page)
self.assertIs(page._parent, iterator)
partition_id = entity_pb2.PartitionId(project_id=project)
if txn_id is None:
read_options = datastore_pb2.ReadOptions()
else:
read_options = datastore_pb2.ReadOptions(transaction=txn_id)
empty_query = query_pb2.Query()
ds_api.run_query.assert_called_once_with(
project, partition_id, read_options, query=empty_query)
def test__next_page(self):
self._next_page_helper()
def test__next_page_in_transaction(self):
txn_id = b'1xo1md\xe2\x98\x83'
self._next_page_helper(txn_id)
def test__next_page_no_more(self):
from google.cloud.datastore.query import Query
ds_api = _make_datastore_api()
client = _Client(None, datastore_api=ds_api)
query = Query(client)
iterator = self._make_one(query, client)
iterator._more_results = False
page = iterator._next_page()
self.assertIsNone(page)
ds_api.run_query.assert_not_called()
class Test__item_to_entity(unittest.TestCase):
def _call_fut(self, iterator, entity_pb):
from google.cloud.datastore.query import _item_to_entity
return _item_to_entity(iterator, entity_pb)
def test_it(self):
entity_pb = mock.sentinel.entity_pb
patch = mock.patch(
'google.cloud.datastore.helpers.entity_from_protobuf')
with patch as entity_from_protobuf:
result = self._call_fut(None, entity_pb)
self.assertIs(result, entity_from_protobuf.return_value)
entity_from_protobuf.assert_called_once_with(entity_pb)
class Test__pb_from_query(unittest.TestCase):
def _call_fut(self, query):
from google.cloud.datastore.query import _pb_from_query
return _pb_from_query(query)
def test_empty(self):
from google.cloud.proto.datastore.v1 import query_pb2
pb = self._call_fut(_Query())
self.assertEqual(list(pb.projection), [])
self.assertEqual(list(pb.kind), [])
self.assertEqual(list(pb.order), [])
self.assertEqual(list(pb.distinct_on), [])
self.assertEqual(pb.filter.property_filter.property.name, '')
cfilter = pb.filter.composite_filter
self.assertEqual(cfilter.op,
query_pb2.CompositeFilter.OPERATOR_UNSPECIFIED)
self.assertEqual(list(cfilter.filters), [])
self.assertEqual(pb.start_cursor, b'')
self.assertEqual(pb.end_cursor, b'')
self.assertEqual(pb.limit.value, 0)
self.assertEqual(pb.offset, 0)
def test_projection(self):
pb = self._call_fut(_Query(projection=['a', 'b', 'c']))
self.assertEqual([item.property.name for item in pb.projection],
['a', 'b', 'c'])
def test_kind(self):
pb = self._call_fut(_Query(kind='KIND'))
self.assertEqual([item.name for item in pb.kind], ['KIND'])
def test_ancestor(self):
from google.cloud.datastore.key import Key
from google.cloud.proto.datastore.v1 import query_pb2
ancestor = Key('Ancestor', 123, project='PROJECT')
pb = self._call_fut(_Query(ancestor=ancestor))
cfilter = pb.filter.composite_filter
self.assertEqual(cfilter.op, query_pb2.CompositeFilter.AND)
self.assertEqual(len(cfilter.filters), 1)
pfilter = cfilter.filters[0].property_filter
self.assertEqual(pfilter.property.name, '__key__')
ancestor_pb = ancestor.to_protobuf()
self.assertEqual(pfilter.value.key_value, ancestor_pb)
def test_filter(self):
from google.cloud.proto.datastore.v1 import query_pb2
query = _Query(filters=[('name', '=', u'John')])
query.OPERATORS = {
'=': query_pb2.PropertyFilter.EQUAL,
}
pb = self._call_fut(query)
cfilter = pb.filter.composite_filter
self.assertEqual(cfilter.op, query_pb2.CompositeFilter.AND)
self.assertEqual(len(cfilter.filters), 1)
pfilter = cfilter.filters[0].property_filter
self.assertEqual(pfilter.property.name, 'name')
self.assertEqual(pfilter.value.string_value, u'John')
def test_filter_key(self):
from google.cloud.datastore.key import Key
from google.cloud.proto.datastore.v1 import query_pb2
key = Key('Kind', 123, project='PROJECT')
query = _Query(filters=[('__key__', '=', key)])
query.OPERATORS = {
'=': query_pb2.PropertyFilter.EQUAL,
}
pb = self._call_fut(query)
cfilter = pb.filter.composite_filter
self.assertEqual(cfilter.op, query_pb2.CompositeFilter.AND)
self.assertEqual(len(cfilter.filters), 1)
pfilter = cfilter.filters[0].property_filter
self.assertEqual(pfilter.property.name, '__key__')
key_pb = key.to_protobuf()
self.assertEqual(pfilter.value.key_value, key_pb)
def test_order(self):
from google.cloud.proto.datastore.v1 import query_pb2
pb = self._call_fut(_Query(order=['a', '-b', 'c']))
self.assertEqual([item.property.name for item in pb.order],
['a', 'b', 'c'])
self.assertEqual([item.direction for item in pb.order],
[query_pb2.PropertyOrder.ASCENDING,
query_pb2.PropertyOrder.DESCENDING,
query_pb2.PropertyOrder.ASCENDING])
def test_distinct_on(self):
pb = self._call_fut(_Query(distinct_on=['a', 'b', 'c']))
self.assertEqual([item.name for item in pb.distinct_on],
['a', 'b', 'c'])
class _Query(object):
def __init__(self,
client=object(),
kind=None,
project=None,
namespace=None,
ancestor=None,
filters=(),
projection=(),
order=(),
distinct_on=()):
self._client = client
self.kind = kind
self.project = project
self.namespace = namespace
self.ancestor = ancestor
self.filters = filters
self.projection = projection
self.order = order
self.distinct_on = distinct_on
class _Client(object):
def __init__(self, project, datastore_api=None, namespace=None,
transaction=None):
self.project = project
self._datastore_api = datastore_api
self.namespace = namespace
self._transaction = transaction
@property
def current_transaction(self):
return self._transaction
def _make_entity(kind, id_, project):
from google.cloud.proto.datastore.v1 import entity_pb2
key = entity_pb2.Key()
key.partition_id.project_id = project
elem = key.path.add()
elem.kind = kind
elem.id = id_
return entity_pb2.Entity(key=key)
def _make_query_response(
entity_pbs, cursor_as_bytes, more_results_enum, skipped_results):
from google.cloud.proto.datastore.v1 import datastore_pb2
from google.cloud.proto.datastore.v1 import query_pb2
return datastore_pb2.RunQueryResponse(
batch=query_pb2.QueryResultBatch(
skipped_results=skipped_results,
end_cursor=cursor_as_bytes,
more_results=more_results_enum,
entity_results=[
query_pb2.EntityResult(entity=entity)
for entity in entity_pbs
],
),
)
def _make_datastore_api(result=None):
run_query = mock.Mock(return_value=result, spec=[])
return mock.Mock(run_query=run_query, spec=['run_query'])<|fim▁end|> | def test_fetch_defaults_w_client_attr(self):
from google.cloud.datastore.query import Iterator
|
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>/*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
// TypeScript Version: 2.0
// tslint:disable:max-classes-per-file
/// <reference types="@stdlib/types"/>
import { IterableIterator } from '@stdlib/types/iter';
/**
* List node.
*/
declare class Node {
/**
* List node constructor.
*
* @param value - node value
* @returns Node instance
*
* @example
* var node = new Node( 'foo' );
* // returns <Node>
*/
constructor( value: any );
/**
* Node value.
*/
value: any;
/**
* Next node in the list.
*/
readonly next: Node;
/**
* Previous node in the list.
*/
readonly prev: Node;
/**
* Private field pointing to the next node.
*/
private readonly _next: Node; // tslint:disable-line:variable-name
/**
* Private field pointing to the previous node.
*/
private readonly _prev: Node; // tslint:disable-line:variable-name
}
/**
* Doubly linked list.
*/
declare class DoublyLinkedList {
/**
* Doubly linked list constructor.
*
* @returns linked list instance
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Remove the last value:
* var v = list.pop();
* // returns 'bar'
*
* // Add a new value to the list:
* list.push( 'beep' );
*
* // Remove the first value:
* v = list.shift();
* // returns 'foo'
*/
constructor();
/**
* Clears the list.
*
* @returns list instance
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Peek at the first value:
* var v = list.first().value;
* // returns 'foo'
*
* // Examine the list length:
* var len = list.length;
* // returns 2
*
* // Clear all list items:
* list.clear();
*
* // Peek at the first value:
* v = list.first();
* // returns undefined
*
* // Examine the list length:
* len = list.length;
* // returns 0
*/
clear(): DoublyLinkedList;
/**
* Returns the first list node.
*
* @returns list node
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Peek at the first value:
* var v = list.first().value;
* // returns 'foo'
*/
first(): Node | void;
/**
* Inserts a value into the list either before or after a provided list node.
*
* @param node - node after which to insert the value
* @param value - value to insert
* @param location - location (default: 'after')
* @throws must provide a node belonging to the list
* @throws must provide a recognized location
* @returns list instance
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' ).push( 'beep' );
*
* // Determine the list length:
* var len = list.length;
* // returns 3
*
* // Get the second node:
* var node = list.first().next;
*
* // Insert a value after the second node:
* list.insert( node, 'boop' );
*
* // Determine the list length:
* len = list.length;
* // returns 4
*/
insert( node: Node, value: any, location?: 'before' | 'after' ): DoublyLinkedList; // tslint-disable-line max-line-length
/**
* Returns an iterator for iterating over a list.
*
* ## Notes
*
* - In order to prevent confusion arising from list mutation during iteration, a returned iterator **always** iterates over a list "snapshot", which is defined as the list of elements at the time of this method's invocation.
*
* @param direction - iteration direction (default: 'forward')
* @throws must provide a recognized iteration direction
* @returns iterator
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Create an iterator:
* var it = list.iterator();
*
* // Iterate over the list...
* var v = it.next().value;
* // returns 'foo'
*
* v = it.next().value;
* // returns 'bar'
*
* var bool = it.next().done;
* // returns true
*/
iterator( direction?: 'forward' | 'reverse' ): IterableIterator;
/**
* Returns the last node.
*
* @returns list node
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Peek at the last value:
* var v = list.last().value;
* // returns 'bar'
*/
last(): Node | void;
/**
* List length.
*
* @example
* var list = new DoublyLinkedList();
*
* // Examine the initial list length:
* var len = list.length;
* // returns 0
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Retrieve the current list length:
* len = list.length;
* // returns 2
*/
readonly length: number;
/**
* Removes a value from the end of the list.
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Remove the last value:
* var v = list.pop();
* // returns 'bar'
*
* // Add a new value to the list:
* list.push( 'beep' );
*
* // Remove the last value:
* v = list.pop();
* // returns 'beep'
*/
pop(): any;
/**
* Adds a value to the end of the list.
*
* @returns list instance
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Remove the last value:
* var v = list.pop();
* // returns 'bar'
*
* // Add a new value to the list:
* list.push( 'beep' );
*
* // Remove the last value:
* v = list.pop();
* // returns 'beep'
*/
push(): DoublyLinkedList;
/**
* Removes a list node from the list.
*
* @param node - node to remove
* @throws must provide a node belonging to the list
* @returns removed value
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' ).push( 'beep' );
*
* // Determine the list length:<|fim▁hole|> * var node = list.first().next;
*
* // Remove the second node:
* var v = list.remove( node );
* // returns 'bar'
*
* // Determine the list length:
* len = list.length;
* // returns 2
*/
remove( node: Node ): any;
/**
* Removes a value from the beginning of the list.
*
* @returns removed value
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Remove the first value:
* var v = list.shift();
* // returns 'foo'
*
* // Add a new value to the list:
* list.push( 'beep' );
*
* // Remove the first value:
* v = list.shift();
* // returns 'bar'
*/
shift(): any;
/**
* Returns an array of list values.
*
* @returns list values
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Get an array of list values:
* var vals = list.toArray();
* // returns [ 'foo', 'bar' ]
*/
toArray(): Array<any>;
/**
* Serializes a list as JSON.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a `DoublyLinkedList` instance.
*
* @returns serialized list
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the list:
* list.push( 'foo' ).push( 'bar' );
*
* // Serialize to JSON:
* var o = list.toJSON();
* // returns { 'type': 'doubly-linked-list', 'data': [ 'foo', 'bar' ] }
*/
toJSON(): any;
/**
* Adds a value to the beginning of the list.
*
* @returns list instance
*
* @example
* var list = new DoublyLinkedList();
*
* // Add values to the beginning of the list:
* list.unshift( 'foo' ).unshift( 'bar' );
*
* // Remove the last value:
* var v = list.pop();
* // returns 'foo'
*
* // Add a new value to the beginning of the list:
* list.unshift( 'beep' );
*
* // Remove the last value:
* v = list.pop();
* // returns 'bar'
*/
unshift(): DoublyLinkedList;
}
// EXPORTS //
export = DoublyLinkedList;<|fim▁end|> | * var len = list.length;
* // returns 3
*
* // Get the second node: |
<|file_name|>request.go<|end_file_name|><|fim▁begin|>// Copyright Google Inc.
//
// 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.
package backend
import (
"bytes"
"fmt"
"net/http"
"strings"
)
const NEW_ADDRESS = "https://ampbyexample.com"
const DEFAULT_MAX_AGE = 60
func RedirectToSecureVersion(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, NEW_ADDRESS+r.URL.Path, http.StatusMovedPermanently)
}
func IsInsecureRequest(r *http.Request) bool {
return r.TLS == nil && !strings.HasPrefix(r.Host, "localhost")
}
<|fim▁hole|>func buildSourceOrigin(host string) string {
var sourceOrigin bytes.Buffer
if strings.HasPrefix(host, "localhost") {
sourceOrigin.WriteString("http://")
} else {
sourceOrigin.WriteString("https://")
}
sourceOrigin.WriteString(host)
return sourceOrigin.String()
}
func isFormPostRequest(method string, w http.ResponseWriter) bool {
if method != "POST" {
http.Error(w, "post only", http.StatusMethodNotAllowed)
return false
}
return true
}
func EnableCors(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "https://cdn.ampproject.org")
w.Header().Set("Access-Control-Expose-Headers", "AMP-Access-Control-Allow-Source-Origin")
w.Header().Set("AMP-Access-Control-Allow-Source-Origin", buildSourceOrigin(r.Host))
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
func SetContentTypeJson(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
}
func SetDefaultMaxAge(w http.ResponseWriter) {
SetMaxAge(w, DEFAULT_MAX_AGE)
}
func SetMaxAge(w http.ResponseWriter, age int) {
w.Header().Set("cache-control", fmt.Sprintf("max-age=%d, public, must-revalidate", age))
}
func handlePost(w http.ResponseWriter, r *http.Request, postHandler func(http.ResponseWriter, *http.Request)) {
if r.Method != "POST" {
http.Error(w, "post only", http.StatusMethodNotAllowed)
return
}
postHandler(w, r)
}<|fim▁end|> | |
<|file_name|>StatementExprList.java<|end_file_name|><|fim▁begin|>package org.aikodi.chameleon.support.statement;
import org.aikodi.chameleon.core.declaration.Declaration;
import org.aikodi.chameleon.core.element.ElementImpl;
import org.aikodi.chameleon.core.lookup.DeclarationSelector;
import org.aikodi.chameleon.core.lookup.LookupContext;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.lookup.SelectionResult;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.oo.statement.ExceptionSource;
import org.aikodi.chameleon.oo.statement.Statement;
import org.aikodi.chameleon.util.association.Multi;
import java.util.Collections;
import java.util.List;
/**
* A list of statement expressions as used in the initialization clause of a for
* statement. It contains a list of statement expressions.
*
* @author Marko van Dooren
*/
public class StatementExprList extends ElementImpl implements ForInit, ExceptionSource {
public StatementExprList() {
}
/**
* STATEMENT EXPRESSIONS
*/
private Multi<StatementExpression> _statementExpressions = new Multi<StatementExpression>(this);
public void addStatement(StatementExpression statement) {
add(_statementExpressions, statement);
}
public void removeStatement(StatementExpression statement) {
remove(_statementExpressions, statement);
}
public List<StatementExpression> statements() {
return _statementExpressions.getOtherEnds();
}
@Override
public StatementExprList cloneSelf() {
return new StatementExprList();
}
public int getIndexOf(Statement statement) {
return statements().indexOf(statement) + 1;
}
public int getNbStatements() {
return statements().size();
}<|fim▁hole|> @Override
public List<? extends Declaration> locallyDeclaredDeclarations() throws LookupException {
return declarations();
}
@Override
public List<? extends Declaration> declarations() throws LookupException {
return Collections.EMPTY_LIST;
}
@Override
public LookupContext localContext() throws LookupException {
return language().lookupFactory().createLocalLookupStrategy(this);
}
@Override
public <D extends Declaration> List<? extends SelectionResult<D>> declarations(DeclarationSelector<D> selector)
throws LookupException {
return Collections.emptyList();
}
@Override
public Verification verifySelf() {
return Valid.create();
}
}<|fim▁end|> | |
<|file_name|>atomic_template.hpp<|end_file_name|><|fim▁begin|>/*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Copyright (c) 2011 Helge Bahmann
* Copyright (c) 2013 Tim Blechmann
* Copyright (c) 2014 Andrey Semashev
*/
/*!
* \file atomic/detail/atomic_template.hpp
*
* This header contains interface definition of \c atomic template.
*/
#ifndef BOOST_ATOMIC_DETAIL_ATOMIC_TEMPLATE_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_ATOMIC_TEMPLATE_HPP_INCLUDED_
#include <cstddef>
#include <boost/cstdint.hpp>
#include <boost/assert.hpp>
#include <boost/atomic/detail/config.hpp>
#include <boost/atomic/detail/bitwise_cast.hpp>
#include <boost/atomic/detail/operations_fwd.hpp>
#include <boost/atomic/detail/type_traits/is_signed.hpp>
#include <boost/atomic/detail/type_traits/is_integral.hpp>
#include <boost/atomic/detail/type_traits/is_function.hpp>
#include <boost/atomic/detail/type_traits/conditional.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if defined(BOOST_MSVC)
#pragma warning(push)
// 'boost::atomics::atomic<T>' : multiple assignment operators specified
#pragma warning(disable: 4522)
#endif
/*
* IMPLEMENTATION NOTE: All interface functions MUST be declared with BOOST_FORCEINLINE,
* see comment for convert_memory_order_to_gcc in ops_gcc_atomic.hpp.
*/
namespace boost {
namespace atomics {
namespace detail {
BOOST_FORCEINLINE BOOST_CONSTEXPR memory_order deduce_failure_order(memory_order order) BOOST_NOEXCEPT
{
return order == memory_order_acq_rel ? memory_order_acquire : (order == memory_order_release ? memory_order_relaxed : order);
}
BOOST_FORCEINLINE BOOST_CONSTEXPR bool cas_failure_order_must_not_be_stronger_than_success_order(memory_order success_order, memory_order failure_order) BOOST_NOEXCEPT
{<|fim▁hole|> // 15 == (memory_order_seq_cst | memory_order_consume), see memory_order.hpp
// Given the enum values we can test the strength of memory order requirements with this single condition.
return (failure_order & 15u) <= (success_order & 15u);
}
template< typename T, bool IsFunction = boost::atomics::detail::is_function< T >::value >
struct classify_pointer
{
typedef void* type;
};
template< typename T >
struct classify_pointer< T, true >
{
typedef void type;
};
template< typename T, bool IsInt = boost::atomics::detail::is_integral< T >::value >
struct classify
{
typedef void type;
};
template< typename T >
struct classify< T, true > { typedef int type; };
template< typename T >
struct classify< T*, false > { typedef typename classify_pointer< T >::type type; };
template< >
struct classify< void*, false > { typedef void type; };
template< >
struct classify< const void*, false > { typedef void type; };
template< >
struct classify< volatile void*, false > { typedef void type; };
template< >
struct classify< const volatile void*, false > { typedef void type; };
template< typename T, typename U >
struct classify< T U::*, false > { typedef void type; };
template< bool >
struct boolean_constant {};
typedef boolean_constant< true > true_constant;
typedef boolean_constant< false > false_constant;
template< typename T, typename Kind >
class base_atomic;
//! General template. Implementation for user-defined types, such as structs and enums, and pointers to non-object types
template< typename T >
class base_atomic< T, void >
{
public:
typedef T value_type;
protected:
typedef atomics::detail::operations< storage_size_of< value_type >::value, false > operations;
typedef typename boost::atomics::detail::conditional< sizeof(value_type) <= sizeof(void*), value_type, value_type const& >::type value_arg_type;
public:
typedef typename operations::storage_type storage_type;
private:
typedef boolean_constant< sizeof(value_type) == sizeof(storage_type) > value_matches_storage;
protected:
typename operations::aligned_storage_type m_storage;
public:
BOOST_FORCEINLINE explicit base_atomic(value_arg_type v = value_type()) BOOST_NOEXCEPT : m_storage(atomics::detail::bitwise_cast< storage_type >(v))
{
}
BOOST_FORCEINLINE void store(value_arg_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return atomics::detail::bitwise_cast< value_type >(operations::load(m_storage.value, order));
}
BOOST_FORCEINLINE value_type exchange(value_arg_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::exchange(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
return compare_exchange_strong_impl(expected, desired, success_order, failure_order, value_matches_storage());
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_arg_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
return compare_exchange_weak_impl(expected, desired, success_order, failure_order, value_matches_storage());
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_arg_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
private:
BOOST_FORCEINLINE bool compare_exchange_strong_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, true_constant) volatile BOOST_NOEXCEPT
{
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
return compare_exchange_strong_impl(expected, desired, success_order, failure_order, false_constant());
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, false_constant) volatile BOOST_NOEXCEPT
{
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
}
BOOST_FORCEINLINE bool compare_exchange_weak_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, true_constant) volatile BOOST_NOEXCEPT
{
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
return compare_exchange_weak_impl(expected, desired, success_order, failure_order, false_constant());
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, false_constant) volatile BOOST_NOEXCEPT
{
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
}
};
//! Implementation for integers
template< typename T >
class base_atomic< T, int >
{
public:
typedef T value_type;
typedef T difference_type;
protected:
typedef atomics::detail::operations< storage_size_of< value_type >::value, boost::atomics::detail::is_signed< T >::value > operations;
typedef value_type value_arg_type;
public:
typedef typename operations::storage_type storage_type;
protected:
typename operations::aligned_storage_type m_storage;
public:
BOOST_DEFAULTED_FUNCTION(base_atomic(), {})
BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : m_storage(v) {}
BOOST_FORCEINLINE void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, static_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return static_cast< value_type >(operations::load(m_storage.value, order));
}
BOOST_FORCEINLINE value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_add(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_sub(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::exchange(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = static_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = static_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE value_type fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_and(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_or(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_xor(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type operator++(int) volatile BOOST_NOEXCEPT
{
return fetch_add(1);
}
BOOST_FORCEINLINE value_type operator++() volatile BOOST_NOEXCEPT
{
return fetch_add(1) + 1;
}
BOOST_FORCEINLINE value_type operator--(int) volatile BOOST_NOEXCEPT
{
return fetch_sub(1);
}
BOOST_FORCEINLINE value_type operator--() volatile BOOST_NOEXCEPT
{
return fetch_sub(1) - 1;
}
BOOST_FORCEINLINE value_type operator+=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_add(v) + v;
}
BOOST_FORCEINLINE value_type operator-=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_sub(v) - v;
}
BOOST_FORCEINLINE value_type operator&=(value_type v) volatile BOOST_NOEXCEPT
{
return fetch_and(v) & v;
}
BOOST_FORCEINLINE value_type operator|=(value_type v) volatile BOOST_NOEXCEPT
{
return fetch_or(v) | v;
}
BOOST_FORCEINLINE value_type operator^=(value_type v) volatile BOOST_NOEXCEPT
{
return fetch_xor(v) ^ v;
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
};
//! Implementation for bool
template< >
class base_atomic< bool, int >
{
public:
typedef bool value_type;
protected:
typedef atomics::detail::operations< 1u, false > operations;
typedef value_type value_arg_type;
public:
typedef operations::storage_type storage_type;
protected:
operations::aligned_storage_type m_storage;
public:
BOOST_DEFAULTED_FUNCTION(base_atomic(), {})
BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : m_storage(v) {}
BOOST_FORCEINLINE void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, static_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return !!operations::load(m_storage.value, order);
}
BOOST_FORCEINLINE value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return !!operations::exchange(m_storage.value, static_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = !!old_value;
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = !!old_value;
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
};
//! Implementation for pointers to object types
template< typename T >
class base_atomic< T*, void* >
{
public:
typedef T* value_type;
typedef std::ptrdiff_t difference_type;
protected:
typedef atomics::detail::operations< storage_size_of< value_type >::value, false > operations;
typedef value_type value_arg_type;
public:
typedef typename operations::storage_type storage_type;
protected:
typename operations::aligned_storage_type m_storage;
public:
BOOST_DEFAULTED_FUNCTION(base_atomic(), {})
BOOST_FORCEINLINE explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : m_storage(atomics::detail::bitwise_cast< storage_type >(v))
{
}
BOOST_FORCEINLINE void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return atomics::detail::bitwise_cast< value_type >(operations::load(m_storage.value, order));
}
BOOST_FORCEINLINE value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::fetch_add(m_storage.value, static_cast< storage_type >(v * sizeof(T)), order));
}
BOOST_FORCEINLINE value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::fetch_sub(m_storage.value, static_cast< storage_type >(v * sizeof(T)), order));
}
BOOST_FORCEINLINE value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::exchange(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE value_type operator++(int) volatile BOOST_NOEXCEPT
{
return fetch_add(1);
}
BOOST_FORCEINLINE value_type operator++() volatile BOOST_NOEXCEPT
{
return fetch_add(1) + 1;
}
BOOST_FORCEINLINE value_type operator--(int) volatile BOOST_NOEXCEPT
{
return fetch_sub(1);
}
BOOST_FORCEINLINE value_type operator--() volatile BOOST_NOEXCEPT
{
return fetch_sub(1) - 1;
}
BOOST_FORCEINLINE value_type operator+=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_add(v) + v;
}
BOOST_FORCEINLINE value_type operator-=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_sub(v) - v;
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
};
} // namespace detail
template< typename T >
class atomic :
public atomics::detail::base_atomic< T, typename atomics::detail::classify< T >::type >
{
private:
typedef atomics::detail::base_atomic< T, typename atomics::detail::classify< T >::type > base_type;
typedef typename base_type::value_arg_type value_arg_type;
public:
typedef typename base_type::value_type value_type;
typedef typename base_type::storage_type storage_type;
public:
static BOOST_CONSTEXPR_OR_CONST bool is_always_lock_free = base_type::operations::is_always_lock_free;
public:
BOOST_DEFAULTED_FUNCTION(atomic(), BOOST_NOEXCEPT {})
// NOTE: The constructor is made explicit because gcc 4.7 complains that
// operator=(value_arg_type) is considered ambiguous with operator=(atomic const&)
// in assignment expressions, even though conversion to atomic<> is less preferred
// than conversion to value_arg_type.
BOOST_FORCEINLINE explicit BOOST_CONSTEXPR atomic(value_arg_type v) BOOST_NOEXCEPT : base_type(v) {}
BOOST_FORCEINLINE value_type operator= (value_arg_type v) volatile BOOST_NOEXCEPT
{
this->store(v);
return v;
}
BOOST_FORCEINLINE operator value_type() const volatile BOOST_NOEXCEPT
{
return this->load();
}
BOOST_FORCEINLINE bool is_lock_free() const volatile BOOST_NOEXCEPT
{
// C++17 requires all instances of atomic<> return a value consistent with is_always_lock_free here
return is_always_lock_free;
}
BOOST_FORCEINLINE storage_type& storage() BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_FORCEINLINE storage_type volatile& storage() volatile BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_FORCEINLINE storage_type const& storage() const BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_FORCEINLINE storage_type const volatile& storage() const volatile BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_DELETED_FUNCTION(atomic(atomic const&))
BOOST_DELETED_FUNCTION(atomic& operator= (atomic const&))
BOOST_DELETED_FUNCTION(atomic& operator= (atomic const&) volatile)
};
template< typename T >
BOOST_CONSTEXPR_OR_CONST bool atomic< T >::is_always_lock_free;
typedef atomic< char > atomic_char;
typedef atomic< unsigned char > atomic_uchar;
typedef atomic< signed char > atomic_schar;
typedef atomic< uint8_t > atomic_uint8_t;
typedef atomic< int8_t > atomic_int8_t;
typedef atomic< unsigned short > atomic_ushort;
typedef atomic< short > atomic_short;
typedef atomic< uint16_t > atomic_uint16_t;
typedef atomic< int16_t > atomic_int16_t;
typedef atomic< unsigned int > atomic_uint;
typedef atomic< int > atomic_int;
typedef atomic< uint32_t > atomic_uint32_t;
typedef atomic< int32_t > atomic_int32_t;
typedef atomic< unsigned long > atomic_ulong;
typedef atomic< long > atomic_long;
typedef atomic< uint64_t > atomic_uint64_t;
typedef atomic< int64_t > atomic_int64_t;
#ifdef BOOST_HAS_LONG_LONG
typedef atomic< boost::ulong_long_type > atomic_ullong;
typedef atomic< boost::long_long_type > atomic_llong;
#endif
typedef atomic< void* > atomic_address;
typedef atomic< bool > atomic_bool;
typedef atomic< wchar_t > atomic_wchar_t;
#if !defined(BOOST_NO_CXX11_CHAR16_T)
typedef atomic< char16_t > atomic_char16_t;
#endif
#if !defined(BOOST_NO_CXX11_CHAR32_T)
typedef atomic< char32_t > atomic_char32_t;
#endif
typedef atomic< int_least8_t > atomic_int_least8_t;
typedef atomic< uint_least8_t > atomic_uint_least8_t;
typedef atomic< int_least16_t > atomic_int_least16_t;
typedef atomic< uint_least16_t > atomic_uint_least16_t;
typedef atomic< int_least32_t > atomic_int_least32_t;
typedef atomic< uint_least32_t > atomic_uint_least32_t;
typedef atomic< int_least64_t > atomic_int_least64_t;
typedef atomic< uint_least64_t > atomic_uint_least64_t;
typedef atomic< int_fast8_t > atomic_int_fast8_t;
typedef atomic< uint_fast8_t > atomic_uint_fast8_t;
typedef atomic< int_fast16_t > atomic_int_fast16_t;
typedef atomic< uint_fast16_t > atomic_uint_fast16_t;
typedef atomic< int_fast32_t > atomic_int_fast32_t;
typedef atomic< uint_fast32_t > atomic_uint_fast32_t;
typedef atomic< int_fast64_t > atomic_int_fast64_t;
typedef atomic< uint_fast64_t > atomic_uint_fast64_t;
typedef atomic< intmax_t > atomic_intmax_t;
typedef atomic< uintmax_t > atomic_uintmax_t;
typedef atomic< std::size_t > atomic_size_t;
typedef atomic< std::ptrdiff_t > atomic_ptrdiff_t;
#if defined(BOOST_HAS_INTPTR_T)
typedef atomic< intptr_t > atomic_intptr_t;
typedef atomic< uintptr_t > atomic_uintptr_t;
#endif
} // namespace atomics
} // namespace boost
#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif
#endif // BOOST_ATOMIC_DETAIL_ATOMIC_TEMPLATE_HPP_INCLUDED_<|fim▁end|> | |
<|file_name|>pasta_check_mbox.py<|end_file_name|><|fim▁begin|>"""
PaStA - Patch Stack Analysis
Copyright (c) OTH Regensburg, 2019
Author:
Ralf Ramsauer <[email protected]>
This work is licensed under the terms of the GNU GPL, version 2. See
the COPYING file in the top-level directory.
"""
import os
import sys
from fuzzywuzzy import fuzz
from logging import getLogger
from multiprocessing import Pool, cpu_count
from tqdm import tqdm
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from pypasta import *
log = getLogger(__name__[-15:])
repo = None
def shortlog(repo, hash, prefix=''):
commit = repo[hash]
log.info('%s%s: %s' % (prefix, hash, commit.subject))
def load_subject(message_id):
# FIXME respect non-unique message ids
message = repo.mbox.get_messages(message_id)[0]
subject = message['Subject']
if subject is None or not isinstance(subject, str):
return None
return message_id, subject
def check_mbox(config, argv):
parser = argparse.ArgumentParser(prog='check_mbox',
description='Check consistency of mailbox '
'result')
parser.add_argument('-v', dest='verbose', default=False,
action='store_true', help='Also dump detected patches')
parser.add_argument('-l', dest='lookup', default=False, action='store_true',
help='Perform a simple lookup')
parser.add_argument('-rd', dest='respect_date', default=False,
action='store_true', help='Respect author date')
parser.add_argument('range', type=str, nargs=1, help='Revision range')
args = parser.parse_args(argv)
if config.mode != config.Mode.MBOX:
log.error('Only works in Mbox mode!')
return -1
global repo
repo = config.repo
# !FIXME Not aligned with current API
_, cluster = config.load_patch_groups()
range = repo.get_commithash_range(args.range[0])
repo.cache_commits(range)
found = []
not_found = []<|fim▁hole|>
for commit_hash in range:
commit = repo[commit_hash]
if commit_hash not in cluster:
not_found.append(commit_hash)
continue
mails = cluster.get_downstream(commit_hash)
if len(mails) == 0:
not_found.append(commit_hash)
continue
if not args.respect_date:
found.append(commit_hash)
continue
# We have to respect the author date in order to filter out backports.
if PatchComposition.is_forwardport(repo, cluster, date_selector, commit_hash):
found.append(commit_hash)
else:
not_found.append(commit_hash)
if args.verbose:
for detected in found:
shortlog(repo, detected)
for message_id in cluster.get_downstream(detected):
shortlog(repo, message_id, ' -> ')
log.info('Commit hashes with no mapped Message-Id:')
for missing in not_found:
shortlog(repo, missing)
log.info('Stats: %d/%d clusters have at least one mail assigned' %
(len(found), len(found) + len(not_found)))
if not args.lookup:
return 0
ids = repo.mbox.get_ids(allow_invalid=True)
valid_ids = repo.mbox.get_ids(allow_invalid=False)
with Pool(cpu_count()) as p:
result = tqdm(p.imap(load_subject, ids), total=len(ids))
result = dict(filter(None, result))
for missing in not_found:
commit = repo[missing]
original_subject = commit.subject.lower()
printed = False
for message_id, subject in result.items():
subject = subject.lower()
is_patch = ' PATCH' if message_id in valid_ids else 'NO PATCH'
if fuzz.ratio(original_subject, subject) > 80:
if not printed:
log.info('%s ("%s") might be...' %
(missing, commit.subject))
printed = True
log.info(' -> (%s) %s ("%s")' %
(is_patch, message_id.ljust(55), subject))<|fim▁end|> |
log.info('Processing %s' % args.range[0])
date_selector = get_date_selector(repo, None, 'AD') |
<|file_name|>plot_cluster.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# spikeplot - plot_cluster.py
#
# Philipp Meier <pmeier82 at googlemail dot com>
# 2011-09-29
#
"""scatter plot for clustering data"""
__docformat__ = 'restructuredtext'
__all__ = ['cluster']
##---IMPORTS
from .common import COLOURS, save_figure, check_plotting_handle, mpl, plt
##---FUNCTION
def cluster(data, data_dim=(0, 1), plot_handle=None, plot_mean=True,<|fim▁hole|> :Parameters:
data : object
Preferably a dictionary with ndarray entries.
data_dim : tuple
A 2-tuple giving the dimension (entries per datapoint/columns) to
use for the scatter plot of the cluster.
plot_handle : figure or axis
A reference to a figure or axis, or None if one has to be created.
plot_mean : bool or float
If False, do nothing. If True or positive integer,
plot the cluster
means with a strong cross, if positive float, additionally plot a
unit circle of that radius (makes sense for prewhitened pca data),
thus interpreting the value as the std of the cluster.
Default=True
colours : list
List of colors in any matplotlib conform colour representation
Default=None
title : str
A title for the plot. No title if None or ''.
xlabel : str
A label for the x-axis. No label if None or ''.
ylabel : str
A label for the y-axis. No label if None or ''.
filename : str
It given and a valid path on the local system, save the figure.
show : bool
If True, show the figure.
:Returns:
matplotlib.figure
Reference th the figure plotted on
"""
# colour list
if colours is None:
col_lst = COLOURS
else:
col_lst = colours
# setup Figure if necessary
fig, ax = check_plotting_handle(plot_handle)
if not isinstance(data, dict):
data = {'0':data}
# plot single cluster members
col_idx = 0
for k in sorted(data.keys()):
ax.plot(
data[k][:, data_dim[0]],
data[k][:, data_dim[1]],
marker='.',
lw=0,
c=col_lst[col_idx % len(col_lst)])
col_idx += 1
# plot cluster means
if plot_mean is not False:
col_idx = 0
for k in sorted(data.keys()):
my_mean = data[k][:, data_dim].mean(axis=0)
ax.plot(
[my_mean[0]],
[my_mean[1]],
lw=0,
marker='x',
mfc=col_lst[col_idx % len(col_lst)],
ms=10,
mew=1,
mec='k')
# plot density estimates
if plot_mean is not True:
ax.add_artist(
mpl.patches.Ellipse(
xy=my_mean,
width=plot_mean * 2,
height=plot_mean * 2,
facecolor='none',
edgecolor=col_lst[col_idx % len(col_lst)]))
col_idx += 1
# fancy stuff
if title is not None:
ax.set_title(title)
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
# produce plots
if filename is not None:
save_figure(fig, filename, '')
if show is True:
plt.show()
return fig
##---MAIN
if __name__ == '__main__':
pass<|fim▁end|> | colours=None, title=None, xlabel=None, ylabel=None, filename=None,
show=True):
"""plot a set of clusters with different colors each
|
<|file_name|>socket_command.cpp<|end_file_name|><|fim▁begin|>//
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// 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 "command/socket_command.h"
#include "component/socket_component.h"
#include "component/tunnel_component.h"
#include "entity/entity.h"
#include "http/http_socket.h"
#include "message/request/request_message.h"
#include "message/response/response_message.h"
namespace eja
{
// Client
socket_request_message::ptr client_socket_command::execute(const entity::ptr router)
{
return socket_request_message::create();
}
void client_socket_command::execute(const entity::ptr router, const std::shared_ptr<socket_response_message> response)
{
// N/A
}
// Router
socket_response_message::ptr router_socket_command::execute(const entity::ptr client, const http_socket::ptr socket, const socket_request_message::ptr request)
{
// Socket
const auto socket_set = m_entity->get<socket_set_component>();
{
thread_lock(socket_set);
socket_set->erase(socket);<|fim▁hole|> {
thread_lock(tunnel_list);
tunnel_list->push_back(socket);
}
return socket_response_message::create();
}
}<|fim▁end|> | }
// Tunnel
const auto tunnel_list = client->get<tunnel_list_component>(); |
<|file_name|>drives.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2002-2015 The DOSBox Team
*
* 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 "dosbox.h"
#include "dos_system.h"
#include "drives.h"
#include "setup.h"
#include "mapper.h"
#include "support.h"
#include "../save_state.h"
bool WildFileCmp(const char * file, const char * wild)
{
char file_name[9];
char file_ext[4];
char wild_name[9];
char wild_ext[4];
const char * find_ext;
Bitu r;
strcpy(file_name," ");
strcpy(file_ext," ");
strcpy(wild_name," ");
strcpy(wild_ext," ");
find_ext=strrchr(file,'.');
if (find_ext) {
Bitu size=(Bitu)(find_ext-file);
if (size>8) size=8;
memcpy(file_name,file,size);
find_ext++;
memcpy(file_ext,find_ext,(strlen(find_ext)>3) ? 3 : strlen(find_ext));
} else {
memcpy(file_name,file,(strlen(file) > 8) ? 8 : strlen(file));
}
upcase(file_name);upcase(file_ext);
find_ext=strrchr(wild,'.');
if (find_ext) {
Bitu size=(Bitu)(find_ext-wild);
if (size>8) size=8;
memcpy(wild_name,wild,size);
find_ext++;
memcpy(wild_ext,find_ext,(strlen(find_ext)>3) ? 3 : strlen(find_ext));
} else {
memcpy(wild_name,wild,(strlen(wild) > 8) ? 8 : strlen(wild));
}
upcase(wild_name);upcase(wild_ext);
/* Names are right do some checking */
r=0;
while (r<8) {
if (wild_name[r]=='*') goto checkext;
if (wild_name[r]!='?' && wild_name[r]!=file_name[r]) return false;
r++;
}
checkext:
r=0;
while (r<3) {
if (wild_ext[r]=='*') return true;
if (wild_ext[r]!='?' && wild_ext[r]!=file_ext[r]) return false;
r++;
}
return true;
}
void Set_Label(char const * const input, char * const output, bool cdrom) {
Bitu togo = 8;
Bitu vnamePos = 0;
Bitu labelPos = 0;
bool point = false;
//spacepadding the filenamepart to include spaces after the terminating zero is more closely to the specs. (not doing this now)
// HELLO\0' '' '
while (togo > 0) {
if (input[vnamePos]==0) break;
if (!point && (input[vnamePos]=='.')) { togo=4; point=true; }
//another mscdex quirk. Label is not always uppercase. (Daggerfall)
output[labelPos] = (cdrom?input[vnamePos]:toupper(input[vnamePos]));
labelPos++; vnamePos++;
togo--;
if ((togo==0) && !point) {
if (input[vnamePos]=='.') vnamePos++;
output[labelPos]='.'; labelPos++; point=true; togo=3;
}
};
output[labelPos]=0;
//Remove trailing dot. except when on cdrom and filename is exactly 8 (9 including the dot) letters. MSCDEX feature/bug (fifa96 cdrom detection)
if((labelPos > 0) && (output[labelPos-1] == '.') && !(cdrom && labelPos ==9))
output[labelPos-1] = 0;
}
DOS_Drive::DOS_Drive() {
curdir[0]=0;
info[0]=0;
}
const char * DOS_Drive::GetInfo(void) {
return info;
}
// static members variables
int DriveManager::currentDrive;
DriveManager::DriveInfo DriveManager::driveInfos[26];
void DriveManager::AppendDisk(int drive, DOS_Drive* disk) {
driveInfos[drive].disks.push_back(disk);
}
void DriveManager::InitializeDrive(int drive) {
currentDrive = drive;
DriveInfo& driveInfo = driveInfos[currentDrive];
if (driveInfo.disks.size() > 0) {
driveInfo.currentDisk = 0;
DOS_Drive* disk = driveInfo.disks[driveInfo.currentDisk];
Drives[currentDrive] = disk;
disk->Activate();
}
}
/*
void DriveManager::CycleDrive(bool pressed) {
if (!pressed) return;
// do one round through all drives or stop at the next drive with multiple disks
int oldDrive = currentDrive;
do {
currentDrive = (currentDrive + 1) % DOS_DRIVES;
int numDisks = driveInfos[currentDrive].disks.size();
if (numDisks > 1) break;
} while (currentDrive != oldDrive);
}
void DriveManager::CycleDisk(bool pressed) {
if (!pressed) return;
int numDisks = driveInfos[currentDrive].disks.size();
if (numDisks > 1) {
// cycle disk
int currentDisk = driveInfos[currentDrive].currentDisk;
DOS_Drive* oldDisk = driveInfos[currentDrive].disks[currentDisk];
currentDisk = (currentDisk + 1) % numDisks;
DOS_Drive* newDisk = driveInfos[currentDrive].disks[currentDisk];
driveInfos[currentDrive].currentDisk = currentDisk;
// copy working directory, acquire system resources and finally switch to next drive
strcpy(newDisk->curdir, oldDisk->curdir);
newDisk->Activate();
Drives[currentDrive] = newDisk;
}
}
*/
void DriveManager::CycleAllDisks(void) {
for (int idrive=0; idrive<2; idrive++) { /* Cycle all DISKS meaning A: and B: */
int numDisks = (int)driveInfos[idrive].disks.size();
if (numDisks > 1) {
// cycle disk
int currentDisk = driveInfos[idrive].currentDisk;
DOS_Drive* oldDisk = driveInfos[idrive].disks[currentDisk];
currentDisk = (currentDisk + 1) % numDisks;
DOS_Drive* newDisk = driveInfos[idrive].disks[currentDisk];
driveInfos[idrive].currentDisk = currentDisk;
// copy working directory, acquire system resources and finally switch to next drive
strcpy(newDisk->curdir, oldDisk->curdir);
newDisk->Activate();
Drives[idrive] = newDisk;
LOG_MSG("Drive %c: disk %d of %d now active", 'A'+idrive, currentDisk+1, numDisks);
}
}
}
void DriveManager::CycleAllCDs(void) {
for (int idrive=2; idrive<DOS_DRIVES; idrive++) { /* Cycle all CDs in C: D: ... Z: */
int numDisks = (int)driveInfos[idrive].disks.size();
if (numDisks > 1) {
// cycle disk
int currentDisk = driveInfos[idrive].currentDisk;
DOS_Drive* oldDisk = driveInfos[idrive].disks[currentDisk];
currentDisk = (currentDisk + 1) % numDisks;
DOS_Drive* newDisk = driveInfos[idrive].disks[currentDisk];
driveInfos[idrive].currentDisk = currentDisk;
// copy working directory, acquire system resources and finally switch to next drive
strcpy(newDisk->curdir, oldDisk->curdir);
newDisk->Activate();
Drives[idrive] = newDisk;
LOG_MSG("Drive %c: disk %d of %d now active", 'A'+idrive, currentDisk+1, numDisks);
}
}
}
int DriveManager::UnmountDrive(int drive) {
int result = 0;
// unmanaged drive
if (driveInfos[drive].disks.size() == 0) {
result = Drives[drive]->UnMount();
} else {
// managed drive
int currentDisk = driveInfos[drive].currentDisk;
result = driveInfos[drive].disks[currentDisk]->UnMount();
// only delete on success, current disk set to NULL because of UnMount
if (result == 0) {
driveInfos[drive].disks[currentDisk] = NULL;
for (int i = 0; i < (int)driveInfos[drive].disks.size(); i++) {
delete driveInfos[drive].disks[i];
}
driveInfos[drive].disks.clear();
}
}
return result;
}
bool int13_extensions_enable = true;
void DriveManager::Init(Section* s) {
Section_prop * section=static_cast<Section_prop *>(s);
int13_extensions_enable = section->Get_bool("int 13 extensions");
// setup driveInfos structure
currentDrive = 0;
for(int i = 0; i < DOS_DRIVES; i++) {
driveInfos[i].currentDisk = 0;
}
// MAPPER_AddHandler(&CycleDisk, MK_f3, MMOD1, "cycledisk", "Cycle Disk");
// MAPPER_AddHandler(&CycleDrive, MK_f3, MMOD2, "cycledrive", "Cycle Drv");
}
void DRIVES_Init(Section* sec) {
DriveManager::Init(sec);
}
char * DOS_Drive::GetBaseDir(void) {
return info + 16;
}
// save state support
void DOS_Drive::SaveState( std::ostream& stream )
{
// - pure data
WRITE_POD( &curdir, curdir );
WRITE_POD( &info, info );
}
void DOS_Drive::LoadState( std::istream& stream )
{
// - pure data
READ_POD( &curdir, curdir );
READ_POD( &info, info );
}
void DriveManager::SaveState( std::ostream& stream )
{
// - pure data
WRITE_POD( ¤tDrive, currentDrive );
}
void DriveManager::LoadState( std::istream& stream )
{
// - pure data
READ_POD( ¤tDrive, currentDrive );
}
void POD_Save_DOS_DriveManager( std::ostream& stream )
{
DriveManager::SaveState(stream);
}
void POD_Load_DOS_DriveManager( std::istream& stream )
{
DriveManager::LoadState(stream);
}
/*
ykhwong svn-daum 2012-05-21
class DriveManager
// - pure data
int currentDrive;
// - system data
static struct DriveInfo {
std::vector<DOS_Drive*> disks;
Bit32u currentDisk;
} driveInfos[DOS_DRIVES];<|fim▁hole|>
class DOS_Drive
// - pure data
char curdir[DOS_PATHLENGTH];
char info[256];
*/<|fim▁end|> | |
<|file_name|>highlight.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Basic html highlighting functionality
//!
//! This module uses libsyntax's lexer to provide token-based highlighting for
//! the HTML documentation generated by rustdoc.
use html::escape::Escape;
use std::io;
use syntax::parse::lexer;
use syntax::parse::token;
use syntax::parse;
/// Highlights some source code, returning the HTML output.
pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String {
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
src.to_string(),
"<stdin>".to_string());
let mut out = io::MemWriter::new();
doit(&sess,
lexer::StringReader::new(&sess.span_diagnostic, fm),
class,
id,
&mut out).unwrap();
String::from_utf8_lossy(out.unwrap().as_slice()).into_string()
}
/// Exhausts the `lexer` writing the output into `out`.
///
/// The general structure for this method is to iterate over each token,
/// possibly giving it an HTML span with a class specifying what flavor of token
/// it's used. All source code emission is done as slices from the source map,
/// not from the tokens themselves, in order to stay true to the original
/// source.
fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
class: Option<&str>, id: Option<&str>,
out: &mut Writer) -> io::IoResult<()> {
use syntax::parse::lexer::Reader;
try!(write!(out, "<pre "));
match id {
Some(id) => try!(write!(out, "id='{}' ", id)),
None => {}
}
try!(write!(out, "class='rust {}'>\n", class.unwrap_or("")));
let mut is_attribute = false;
let mut is_macro = false;
let mut is_macro_nonterminal = false;
loop {
let next = lexer.next_token();
let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap();
if next.tok == token::Eof { break }
let klass = match next.tok {
token::Whitespace => {
try!(write!(out, "{}", Escape(snip(next.sp).as_slice())));
continue
},
token::Comment => {
try!(write!(out, "<span class='comment'>{}</span>",
Escape(snip(next.sp).as_slice())));
continue
},
token::Shebang(s) => {
try!(write!(out, "{}", Escape(s.as_str())));
continue
},
// If this '&' token is directly adjacent to another token, assume
// that it's the address-of operator instead of the and-operator.
// This allows us to give all pointers their own class (`Box` and
// `@` are below).<|fim▁hole|> // leading identifier
token::Not if is_macro => { is_macro = false; "macro" }
// operators
token::Eq | token::Lt | token::Le | token::EqEq | token::Ne | token::Ge | token::Gt |
token::AndAnd | token::OrOr | token::Not | token::BinOp(..) | token::RArrow |
token::BinOpEq(..) | token::FatArrow => "op",
// miscellaneous, no highlighting
token::Dot | token::DotDot | token::DotDotDot | token::Comma | token::Semi |
token::Colon | token::ModSep | token::LArrow | token::OpenDelim(_) |
token::CloseDelim(token::Brace) | token::CloseDelim(token::Paren) |
token::Question => "",
token::Dollar => {
if lexer.peek().tok.is_ident() {
is_macro_nonterminal = true;
"macro-nonterminal"
} else {
""
}
}
// This is the start of an attribute. We're going to want to
// continue highlighting it as an attribute until the ending ']' is
// seen, so skip out early. Down below we terminate the attribute
// span when we see the ']'.
token::Pound => {
is_attribute = true;
try!(write!(out, r"<span class='attribute'>#"));
continue
}
token::CloseDelim(token::Bracket) => {
if is_attribute {
is_attribute = false;
try!(write!(out, "]</span>"));
continue
} else {
""
}
}
// text literals
token::LitByte(..) | token::LitBinary(..) | token::LitBinaryRaw(..) |
token::LitChar(..) | token::LitStr(..) | token::LitStrRaw(..) => "string",
// number literals
token::LitInteger(..) | token::LitFloat(..) => "number",
// keywords are also included in the identifier set
token::Ident(ident, _is_mod_sep) => {
match token::get_ident(ident).get() {
"ref" | "mut" => "kw-2",
"self" => "self",
"false" | "true" => "boolval",
"Option" | "Result" => "prelude-ty",
"Some" | "None" | "Ok" | "Err" => "prelude-val",
_ if next.tok.is_any_keyword() => "kw",
_ => {
if is_macro_nonterminal {
is_macro_nonterminal = false;
"macro-nonterminal"
} else if lexer.peek().tok == token::Not {
is_macro = true;
"macro"
} else {
"ident"
}
}
}
}
token::Lifetime(..) => "lifetime",
token::DocComment(..) => "doccomment",
token::Underscore | token::Eof | token::Interpolated(..) |
token::MatchNt(..) | token::SubstNt(..) => "",
};
// as mentioned above, use the original source code instead of
// stringifying this token
let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap();
if klass == "" {
try!(write!(out, "{}", Escape(snip.as_slice())));
} else {
try!(write!(out, "<span class='{}'>{}</span>", klass,
Escape(snip.as_slice())));
}
}
write!(out, "</pre>\n")
}<|fim▁end|> | token::BinOp(token::And) if lexer.peek().sp.lo == next.sp.hi => "kw-2",
token::At | token::Tilde => "kw-2",
// consider this as part of a macro invocation if there was a |
<|file_name|>tiny-slider.js<|end_file_name|><|fim▁begin|>var tns = (function (){
// keys
if (!Object.keys) {
Object.keys = function (object) {
var keys = [];
for (var name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
keys.push(name);
}
}
return keys;
};
}
// ChildNode.remove
(function () {
"use strict";
if(!("remove" in Element.prototype)){
Element.prototype.remove = function(){
if(this.parentNode) {
this.parentNode.removeChild(this);
}
};
}
})();
var win = window;
var raf = win.requestAnimationFrame
|| win.webkitRequestAnimationFrame
|| win.mozRequestAnimationFrame
|| win.msRequestAnimationFrame
|| function(cb) { return setTimeout(cb, 16); };
var win$1 = window;
var caf = win$1.cancelAnimationFrame
|| win$1.mozCancelAnimationFrame
|| function(id){ clearTimeout(id); };
function extend() {
var obj, name, copy,
target = arguments[0] || {},
i = 1,
length = arguments.length;
for (; i < length; i++) {
if ((obj = arguments[i]) !== null) {
for (name in obj) {
copy = obj[name];
if (target === copy) {
continue;
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
}
function checkStorageValue (value) {
return ['true', 'false'].indexOf(value) >= 0 ? JSON.parse(value) : value;
}
function setLocalStorage(key, value) {
localStorage.setItem(key, value);
return value;
}
function getSlideId() {
var id = window.tnsId;
window.tnsId = !id ? 1 : id + 1;
return 'tns' + window.tnsId;
}
function getBody () {
var doc = document,
body = doc.body;
if (!body) {
body = doc.createElement('body');
body.fake = true;
}
return body;
}
var docElement = document.documentElement;
function setFakeBody (body) {
var docOverflow = '';
if (body.fake) {
docOverflow = docElement.style.overflow;
//avoid crashing IE8, if background image is used
body.style.background = '';
//Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
body.style.overflow = docElement.style.overflow = 'hidden';
docElement.appendChild(body);
}
return docOverflow;
}
function resetFakeBody (body, docOverflow) {
if (body.fake) {
body.remove();
docElement.style.overflow = docOverflow;
// Trigger layout so kinetic scrolling isn't disabled in iOS6+
// eslint-disable-next-line
docElement.offsetHeight;
}
}
// get css-calc
function calc() {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
result = false;
body.appendChild(div);
try {
var vals = ['calc(10px)', '-moz-calc(10px)', '-webkit-calc(10px)'], val;
for (var i = 0; i < 3; i++) {
val = vals[i];
div.style.width = val;
if (div.offsetWidth === 10) {
result = val.replace('(10px)', '');
break;
}
}
} catch (e) {}
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return result;
}
// get subpixel support value
function subpixelLayout() {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
parent = doc.createElement('div'),
child1 = doc.createElement('div'),
child2,
supported;
parent.style.cssText = 'width: 10px';
child1.style.cssText = 'float: left; width: 5.5px; height: 10px;';
child2 = child1.cloneNode(true);
parent.appendChild(child1);
parent.appendChild(child2);
body.appendChild(parent);
supported = child1.offsetTop !== child2.offsetTop;
body.fake ? resetFakeBody(body, docOverflow) : parent.remove();
return supported;
}
function mediaquerySupport () {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
style = doc.createElement('style'),
rule = '@media all and (min-width:1px){.tns-mq-test{position:absolute}}',
position;
style.type = 'text/css';
div.className = 'tns-mq-test';
body.appendChild(style);
body.appendChild(div);
if (style.styleSheet) {
style.styleSheet.cssText = rule;
} else {
style.appendChild(doc.createTextNode(rule));
}
position = window.getComputedStyle ? window.getComputedStyle(div).position : div.currentStyle['position'];
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return position === "absolute";
}
// create and append style sheet
function createStyleSheet (media) {
// Create the <style> tag
var style = document.createElement("style");
// style.setAttribute("type", "text/css");
// Add a media (and/or media query) here if you'd like!
// style.setAttribute("media", "screen")
// style.setAttribute("media", "only screen and (max-width : 1024px)")
if (media) { style.setAttribute("media", media); }
// WebKit hack :(
// style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.querySelector('head').appendChild(style);
return style.sheet ? style.sheet : style.styleSheet;
}
// cross browsers addRule method
function addCSSRule(sheet, selector, rules, index) {
// return raf(function() {
'insertRule' in sheet ?
sheet.insertRule(selector + '{' + rules + '}', index) :
sheet.addRule(selector, rules, index);
// });
}
function getCssRulesLength(sheet) {
var rule = ('insertRule' in sheet) ? sheet.cssRules : sheet.rules;
return rule.length;
}
function toDegree (y, x) {
return Math.atan2(y, x) * (180 / Math.PI);
}
function getTouchDirection(angle, range) {
var direction = false,
gap = Math.abs(90 - Math.abs(angle));
if (gap >= 90 - range) {
direction = 'horizontal';
} else if (gap <= range) {
direction = 'vertical';
}
return direction;
}
// https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/
function forEachNodeList (arr, callback, scope) {
for (var i = 0, l = arr.length; i < l; i++) {
callback.call(scope, arr[i], i);
}
}
var classListSupport = 'classList' in document.createElement('_');
var hasClass = classListSupport ?
function (el, str) { return el.classList.contains(str); } :
function (el, str) { return el.className.indexOf(str) >= 0; };
var addClass = classListSupport ?
function (el, str) {
if (!hasClass(el, str)) { el.classList.add(str); }
} :
function (el, str) {
if (!hasClass(el, str)) { el.className += ' ' + str; }
};
var removeClass = classListSupport ?
function (el, str) {
if (hasClass(el, str)) { el.classList.remove(str); }
} :
function (el, str) {
if (hasClass(el, str)) { el.className = el.className.replace(str, ''); }
};
function hasAttr(el, attr) {
return el.hasAttribute(attr);
}
function getAttr(el, attr) {
return el.getAttribute(attr);
}
function isNodeList(el) {
// Only NodeList has the "item()" function
return typeof el.item !== "undefined";
}
function setAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
if (Object.prototype.toString.call(attrs) !== '[object Object]') { return; }
for (var i = els.length; i--;) {
for(var key in attrs) {
els[i].setAttribute(key, attrs[key]);
}
}
}
function removeAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
attrs = (attrs instanceof Array) ? attrs : [attrs];
var attrLength = attrs.length;
for (var i = els.length; i--;) {
for (var j = attrLength; j--;) {
els[i].removeAttribute(attrs[j]);
}
}
}
function removeElementStyles(el) {
el.style.cssText = '';
}
function arrayFromNodeList (nl) {
var arr = [];
for (var i = 0, l = nl.length; i < l; i++) {
arr.push(nl[i]);
}
return arr;
}
function hideElement(el) {
if (!hasAttr(el, 'hidden')) {
setAttrs(el, {'hidden': ''});
}
}
function showElement(el) {
if (hasAttr(el, 'hidden')) {
removeAttrs(el, 'hidden');
}
}
function isVisible(el) {
return el.offsetWidth > 0 && el.offsetHeight > 0;
}
function whichProperty(props){
if (typeof props === 'string') {
var arr = [props],
Props = props.charAt(0).toUpperCase() + props.substr(1),
prefixes = ['Webkit', 'Moz', 'ms', 'O'];
prefixes.forEach(function(prefix) {
if (prefix !== 'ms' || props === 'transform') {
arr.push(prefix + Props);
}
});
props = arr;
}
var el = document.createElement('fakeelement'),
len = props.length;
for(var i = 0; i < props.length; i++){
var prop = props[i];
if( el.style[prop] !== undefined ){ return prop; }
}
return false; // explicit for ie9-
}
function has3D(tf){
if (!window.getComputedStyle) { return false; }
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
el = doc.createElement('p'),
has3d,
cssTF = tf.length > 9 ? '-' + tf.slice(0, -9).toLowerCase() + '-' : '';
cssTF += 'transform';
// Add it to the body to get the computed style
body.insertBefore(el, null);
el.style[tf] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el).getPropertyValue(cssTF);
body.fake ? resetFakeBody(body, docOverflow) : el.remove();
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}
// get transitionend, animationend based on transitionDuration
// @propin: string
// @propOut: string, first-letter uppercase
// Usage: getEndProperty('WebkitTransitionDuration', 'Transition') => webkitTransitionEnd
function getEndProperty(propIn, propOut) {
var endProp = false;
if (/^Webkit/.test(propIn)) {
endProp = 'webkit' + propOut + 'End';
} else if (/^O/.test(propIn)) {
endProp = 'o' + propOut + 'End';
} else if (propIn) {
endProp = propOut.toLowerCase() + 'end';
}
return endProp;
}
// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true;
}
});
window.addEventListener("test", null, opts);
} catch (e) {}
var passiveOption = supportsPassive ? { passive: true } : false;
function addEvents(el, obj) {
for (var prop in obj) {
var option = (prop === 'touchstart' || prop === 'touchmove') ? passiveOption : false;
el.addEventListener(prop, obj[prop], option);
}
}
function removeEvents(el, obj) {
for (var prop in obj) {
var option = ['touchstart', 'touchmove'].indexOf(prop) >= 0 ? passiveOption : false;
el.removeEventListener(prop, obj[prop], option);
}
}
function Events() {
return {
topics: {},
on: function (eventName, fn) {
this.topics[eventName] = this.topics[eventName] || [];
this.topics[eventName].push(fn);
},
off: function(eventName, fn) {
if (this.topics[eventName]) {
for (var i = 0; i < this.topics[eventName].length; i++) {
if (this.topics[eventName][i] === fn) {
this.topics[eventName].splice(i, 1);
break;
}
}
}
},
emit: function (eventName, data) {
if (this.topics[eventName]) {
this.topics[eventName].forEach(function(fn) {
fn(data);
});
}
}
};
}
function jsTransform(element, attr, prefix, postfix, to, duration, callback) {
var tick = Math.min(duration, 10),
unit = (to.indexOf('%') >= 0) ? '%' : 'px',
to = to.replace(unit, ''),
from = Number(element.style[attr].replace(prefix, '').replace(postfix, '').replace(unit, '')),
positionTick = (to - from) / duration * tick,
running;
setTimeout(moveElement, tick);
function moveElement() {
duration -= tick;
from += positionTick;
element.style[attr] = prefix + from + unit + postfix;
if (duration > 0) {
setTimeout(moveElement, tick);
} else {
callback();
}
}
}
// Format: IIFE
var tns = function(options) {
options = extend({
container: '.slider',
mode: 'carousel',
axis: 'horizontal',
items: 1,
gutter: 0,
edgePadding: 0,
fixedWidth: false,
fixedWidthViewportWidth: false,
slideBy: 1,
controls: true,
controlsText: ['prev', 'next'],
controlsContainer: false,
prevButton: false,
nextButton: false,
nav: true,
navContainer: false,
navAsThumbnails: false,
arrowKeys: false,
speed: 300,
autoplay: false,
autoplayTimeout: 5000,
autoplayDirection: 'forward',
autoplayText: ['start', 'stop'],
autoplayHoverPause: false,
autoplayButton: false,
autoplayButtonOutput: true,
autoplayResetOnVisibility: true,
// animateIn: 'tns-fadeIn',
// animateOut: 'tns-fadeOut',
// animateNormal: 'tns-normal',
// animateDelay: false,
loop: true,
rewind: false,
autoHeight: false,
responsive: false,
lazyload: false,
touch: true,
mouseDrag: false,
swipeAngle: 15,
nested: false,
freezable: true,
// startIndex: 0,
onInit: false,
useLocalStorage: true
}, options || {});
var doc = document,
win = window,
KEYS = {
ENTER: 13,
SPACE: 32,
PAGEUP: 33,
PAGEDOWN: 34,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
},
CALC,
SUBPIXEL,
CSSMQ,
TRANSFORM,
HAS3D,
TRANSITIONDURATION,
TRANSITIONDELAY,
ANIMATIONDURATION,
ANIMATIONDELAY,
TRANSITIONEND,
ANIMATIONEND,
localStorageAccess = true;
if (options.useLocalStorage) {
// check browser version and local storage
// if browser upgraded,
// 1. delete browser ralated data from local storage and
// 2. recheck these options and save them to local storage
var browserInfo = navigator.userAgent,
tnsStorage = {};
// tC => calc
// tSP => subpixel
// tMQ => mediaquery
// tTf => transform
// tTDu => transitionDuration
// tTDe => transitionDelay
// tADu => animationDuration
// tADe => animationDelay
// tTE => transitionEnd
// tAE => animationEnd
try {
tnsStorage = localStorage;
// remove storage when browser version changes
if (tnsStorage['tnsApp'] && tnsStorage['tnsApp'] !== browserInfo) {
['tC', 'tSP', 'tMQ', 'tTf', 't3D', 'tTDu', 'tTDe', 'tADu', 'tADe', 'tTE', 'tAE'].forEach(function(item) { tnsStorage.removeItem(item); });
}
// update browserInfo
tnsStorage['tnsApp'] = browserInfo;
} catch(e) {
localStorageAccess = false;
}
// reset tnsStorage when localStorage is null (on some versions of Chrome Mobile #134)
// https://stackoverflow.com/questions/8701015/html-localstorage-is-null-on-android-when-using-webview
if (!localStorage) {
tnsStorage = {};
localStorageAccess = false;
}
// get browser related data from local storage if they exist
// otherwise, run the functions again and save these data to local storage
// checkStorageValue() convert non-string value to its original value: 'true' > true
if (localStorageAccess) {
if (tnsStorage['tC']) {
CALC = checkStorageValue(tnsStorage['tC']);
SUBPIXEL = checkStorageValue(tnsStorage['tSP']);
CSSMQ = checkStorageValue(tnsStorage['tMQ']);
TRANSFORM = checkStorageValue(tnsStorage['tTf']);
HAS3D = checkStorageValue(tnsStorage['t3D']);
TRANSITIONDURATION = checkStorageValue(tnsStorage['tTDu']);
TRANSITIONDELAY = checkStorageValue(tnsStorage['tTDe']);
ANIMATIONDURATION = checkStorageValue(tnsStorage['tADu']);
ANIMATIONDELAY = checkStorageValue(tnsStorage['tADe']);
TRANSITIONEND = checkStorageValue(tnsStorage['tTE']);
ANIMATIONEND = checkStorageValue(tnsStorage['tAE']);
} else {
CALC = setLocalStorage('tC', calc());
SUBPIXEL = setLocalStorage('tSP', subpixelLayout());
CSSMQ = setLocalStorage('tMQ', mediaquerySupport());
TRANSFORM = setLocalStorage('tTf', whichProperty('transform'));
HAS3D = setLocalStorage('t3D', has3D(TRANSFORM));
TRANSITIONDURATION = setLocalStorage('tTDu', whichProperty('transitionDuration'));
TRANSITIONDELAY = setLocalStorage('tTDe', whichProperty('transitionDelay'));
ANIMATIONDURATION = setLocalStorage('tADu', whichProperty('animationDuration'));
ANIMATIONDELAY = setLocalStorage('tADe', whichProperty('animationDelay'));
TRANSITIONEND = setLocalStorage('tTE', getEndProperty(TRANSITIONDURATION, 'Transition'));
ANIMATIONEND = setLocalStorage('tAE', getEndProperty(ANIMATIONDURATION, 'Animation'));
}
}
} else {
localStorageAccess = false;
}
if (!localStorageAccess) {
CALC = calc();
SUBPIXEL = subpixelLayout();
CSSMQ = mediaquerySupport();
TRANSFORM = whichProperty('transform');
HAS3D = has3D(TRANSFORM);
TRANSITIONDURATION = whichProperty('transitionDuration');
TRANSITIONDELAY = whichProperty('transitionDelay');
ANIMATIONDURATION = whichProperty('animationDuration');
ANIMATIONDELAY = whichProperty('animationDelay');
TRANSITIONEND = getEndProperty(TRANSITIONDURATION, 'Transition');
ANIMATIONEND = getEndProperty(ANIMATIONDURATION, 'Animation');
}
// reset SUBPIXEL for IE8
if (!CSSMQ) { SUBPIXEL = false; }
// get element nodes from selectors
var supportConsoleWarn = win.console && typeof win.console.warn === "function";
var list = ['container', 'controlsContainer', 'prevButton', 'nextButton', 'navContainer', 'autoplayButton'];
for (var i = list.length; i--;) {
var item = list[i];
if (typeof options[item] === 'string') {
var el = doc.querySelector(options[item]);
if (el && el.nodeName) {
options[item] = el;
} else {
if (supportConsoleWarn) { console.warn('Can\'t find', options[item]); }
return;
}
}
}
// make sure at least 1 slide
if (options.container.children && options.container.children.length < 1) {
if (supportConsoleWarn) { console.warn('No slides found in', options.container); }
return;
}
// update responsive
// from: {
// 300: 2,
// 800: {
// loop: false
// }
// }
// to: {
// 300: {
// items: 2
// },
// 800: {
// loop: false
// }
// }
if (options.responsive) {
var resTem = {}, res = options.responsive;
for(var key in res) {
var val = res[key];
resTem[key] = typeof val === 'number' ? {items: val} : val;
}
options.responsive = resTem;
resTem = null;
// apply responsive[0] to options and remove it
if (0 in options.responsive) {
options = extend(options, options.responsive[0]);
delete options.responsive[0];
}
}
// === define and set variables ===
var carousel = options.mode === 'carousel' ? true : false;
if (!carousel) {
options.axis = 'horizontal';
// options.rewind = false;
// options.loop = true;
options.edgePadding = false;
var animateIn = 'tns-fadeIn',
animateOut = 'tns-fadeOut',
animateDelay = false,
animateNormal = options.animateNormal || 'tns-normal';
if (TRANSITIONEND && ANIMATIONEND) {
animateIn = options.animateIn || animateIn;
animateOut = options.animateOut || animateOut;
animateDelay = options.animateDelay || animateDelay;
}
}
var horizontal = options.axis === 'horizontal' ? true : false,
outerWrapper = doc.createElement('div'),
innerWrapper = doc.createElement('div'),
container = options.container,
containerParent = container.parentNode,
slideItems = container.children,
slideCount = slideItems.length,
vpInner,
responsive = options.responsive,
responsiveItems = [],
breakpoints = false,
breakpointZone = 0,
windowWidth = getWindowWidth(),
isOn;
if (options.fixedWidth) { var vpOuter = getViewportWidth(containerParent); }
if (responsive) {
breakpoints = Object.keys(responsive)
.map(function (x) { return parseInt(x); })
.sort(function (a, b) { return a - b; });
// get all responsive items
breakpoints.forEach(function(bp) {
responsiveItems = responsiveItems.concat(Object.keys(responsive[bp]));
});
// remove duplicated items
var arr = [];
responsiveItems.forEach(function (item) { if (arr.indexOf(item) < 0) { arr.push(item); } });
responsiveItems = arr;
setBreakpointZone();
}
var items = getOption('items'),
slideBy = getOption('slideBy') === 'page' ? items : getOption('slideBy'),
nested = options.nested,
gutter = getOption('gutter'),
edgePadding = getOption('edgePadding'),
fixedWidth = getOption('fixedWidth'),
fixedWidthViewportWidth = options.fixedWidthViewportWidth,
arrowKeys = getOption('arrowKeys'),
speed = getOption('speed'),
rewind = options.rewind,
loop = rewind ? false : options.loop,
autoHeight = getOption('autoHeight'),
sheet = createStyleSheet(),
lazyload = options.lazyload,
slideOffsetTops, // collection of slide offset tops
slideItemsOut = [],
hasEdgePadding = checkOption('edgePadding'),
cloneCount = loop ? getCloneCountForLoop() : 0,
slideCountNew = !carousel ? slideCount + cloneCount : slideCount + cloneCount * 2,
hasRightDeadZone = fixedWidth && !loop && !edgePadding ? true : false,
updateIndexBeforeTransform = (!carousel || !loop) ? true : false,
// transform
transformAttr = horizontal ? 'left' : 'top',
transformPrefix = '',
transformPostfix = '',
// index
startIndex = getOption('startIndex'),
index = startIndex ? updateStartIndex(startIndex) : !carousel ? 0 : cloneCount,
indexCached = index,
indexMin = 0,
indexMax = getIndexMax(),
// resize
resizeTimer,
swipeAngle = options.swipeAngle,
moveDirectionExpected = swipeAngle ? '?' : true,
running = false,
onInit = options.onInit,
events = new Events(),
// id, class
containerIdCached = container.id,
classContainer = ' tns-slider tns-' + options.mode,
slideId = container.id || getSlideId(),
disable = getOption('disable'),
freezable = options.freezable,
freeze = disable ? true : freezable ? slideCount <= items : false,
frozen,
importantStr = nested === 'inner' ? ' !important' : '',
controlsEvents = {
'click': onControlsClick,
'keydown': onControlsKeydown
},
navEvents = {
'click': onNavClick,
'keydown': onNavKeydown
},
hoverEvents = {
'mouseover': mouseoverPause,
'mouseout': mouseoutRestart
},
visibilityEvent = {'visibilitychange': onVisibilityChange},
docmentKeydownEvent = {'keydown': onDocumentKeydown},
touchEvents = {
'touchstart': onPanStart,
'touchmove': onPanMove,
'touchend': onPanEnd,
'touchcancel': onPanEnd
}, dragEvents = {
'mousedown': onPanStart,
'mousemove': onPanMove,
'mouseup': onPanEnd,
'mouseleave': onPanEnd
},
hasControls = checkOption('controls'),
hasNav = checkOption('nav'),
navAsThumbnails = options.navAsThumbnails,
hasAutoplay = checkOption('autoplay'),
hasTouch = checkOption('touch'),
hasMouseDrag = checkOption('mouseDrag'),
slideActiveClass = 'tns-slide-active',
imgCompleteClass = 'tns-complete',
imgEvents = {
'load': imgLoadedOrError,
'error': imgLoadedOrError
},
imgsComplete;
// controls
if (hasControls) {
var controls = getOption('controls'),
controlsText = getOption('controlsText'),
controlsContainer = options.controlsContainer,
prevButton = options.prevButton,
nextButton = options.nextButton,
prevIsButton,
nextIsButton;
}
// nav
if (hasNav) {
var nav = getOption('nav'),
navContainer = options.navContainer,
navItems,
visibleNavIndexes = [],
visibleNavIndexesCached = visibleNavIndexes,
navClicked = -1,
navCurrentIndex = getAbsIndex(),
navCurrentIndexCached = navCurrentIndex,
navActiveClass = 'tns-nav-active';
}
// autoplay
if (hasAutoplay) {
var autoplay = getOption('autoplay'),
autoplayTimeout = getOption('autoplayTimeout'),
autoplayDirection = options.autoplayDirection === 'forward' ? 1 : -1,
autoplayText = getOption('autoplayText'),
autoplayHoverPause = getOption('autoplayHoverPause'),
autoplayButton = options.autoplayButton,
autoplayResetOnVisibility = getOption('autoplayResetOnVisibility'),
autoplayHtmlStrings = ['<span class=\'tns-visually-hidden\'>', ' animation</span>'],
autoplayTimer,
animating,
autoplayHoverPaused,
autoplayUserPaused,
autoplayVisibilityPaused;
}
if (hasTouch || hasMouseDrag) {
var initPosition = {},
lastPosition = {},
translateInit,
disX,
disY,
panStart = false,
rafIndex = 0,
getDist = horizontal ?
function(a, b) { return a.x - b.x; } :
function(a, b) { return a.y - b.y; };
}
// touch
if (hasTouch) {
var touch = getOption('touch');
}
// mouse drag
if (hasMouseDrag) {
var mouseDrag = getOption('mouseDrag');
}
// disable slider when slidecount <= items
if (freeze) {
controls = nav = touch = mouseDrag = arrowKeys = autoplay = autoplayHoverPause = autoplayResetOnVisibility = false;
}
if (TRANSFORM) {
transformAttr = TRANSFORM;
transformPrefix = 'translate';
if (HAS3D) {
transformPrefix += horizontal ? '3d(' : '3d(0px, ';
transformPostfix = horizontal ? ', 0px, 0px)' : ', 0px)';
} else {
transformPrefix += horizontal ? 'X(' : 'Y(';
transformPostfix = ')';
}
}
// === COMMON FUNCTIONS === //
function getIndexMax () {
return carousel || loop ? Math.max(0, slideCountNew - items) : slideCountNew - 1;
}
function updateStartIndex (indexTem) {
indexTem = indexTem%slideCount;
if (indexTem < 0) { indexTem += slideCount; }
indexTem = Math.min(indexTem, slideCountNew - items);
return indexTem;
}
function getAbsIndex (i) {
if (i === undefined) { i = index; }
if (carousel) {
while (i < cloneCount) { i += slideCount; }
i -= cloneCount;
}
return i ? i%slideCount : i;
}
function getItemsMax () {
if (fixedWidth && !fixedWidthViewportWidth) {
return slideCount - 1;
} else {
var str = fixedWidth ? 'fixedWidth' : 'items',
arr = [];
if (fixedWidth || options[str] < slideCount) { arr.push(options[str]); }
if (breakpoints && responsiveItems.indexOf(str) >= 0) {
breakpoints.forEach(function(bp) {
var tem = responsive[bp][str];
if (tem && (fixedWidth || tem < slideCount)) { arr.push(tem); }
});
}
if (!arr.length) { arr.push(0); }
return fixedWidth ? Math.ceil(fixedWidthViewportWidth / Math.min.apply(null, arr)) :
Math.max.apply(null, arr);
}
}
function getCloneCountForLoop () {
var itemsMax = getItemsMax(),
result = carousel ? Math.ceil((itemsMax * 5 - slideCount)/2) : (itemsMax * 4 - slideCount);
result = Math.max(itemsMax, result);
return hasEdgePadding ? result + 1 : result;
}
function getWindowWidth () {
return win.innerWidth || doc.documentElement.clientWidth || doc.body.clientWidth;
}
function getViewportWidth (el) {
return el.clientWidth || getViewportWidth(el.parentNode);
}
function checkOption (item) {
var result = options[item];
if (!result && breakpoints && responsiveItems.indexOf(item) >= 0) {
breakpoints.forEach(function (bp) {
if (responsive[bp][item]) { result = true; }
});
}
return result;
}
function getOption (item, viewport) {
viewport = viewport ? viewport : windowWidth;
var obj = {
slideBy: 'page',
edgePadding: false
},
result;
if (!carousel && item in obj) {
result = obj[item];
} else {
if (item === 'items' && getOption('fixedWidth')) {
result = Math.floor(vpOuter / (getOption('fixedWidth') + getOption('gutter')));
} else if (item === 'autoHeight' && nested === 'outer') {
result = true;
} else {
result = options[item];
if (breakpoints && responsiveItems.indexOf(item) >= 0) {
for (var i = 0, len = breakpoints.length; i < len; i++) {
var bp = breakpoints[i];
if (viewport >= bp) {
if (item in responsive[bp]) { result = responsive[bp][item]; }
} else { break; }
}
}
}
}
if (item === 'slideBy' && result === 'page') { result = getOption('items'); }
return result;
}
function getSlideMarginLeft (i) {
var str = CALC ?
CALC + '(' + i * 100 + '% / ' + slideCountNew + ')' :
i * 100 / slideCountNew + '%';
return str;
}
function getInnerWrapperStyles (edgePaddingTem, gutterTem, fixedWidthTem, speedTem) {
var str = '';
if (edgePaddingTem) {
var gap = edgePaddingTem;
if (gutterTem) { gap += gutterTem; }
if (fixedWidthTem) {
str = 'margin: 0px ' + (vpOuter%(fixedWidthTem + gutterTem) + gutterTem) / 2 + 'px;';
} else {
str = horizontal ?
'margin: 0 ' + edgePaddingTem + 'px 0 ' + gap + 'px;' :
'padding: ' + gap + 'px 0 ' + edgePaddingTem + 'px 0;';
}
} else if (gutterTem && !fixedWidthTem) {
var gutterTemUnit = '-' + gutterTem + 'px',
dir = horizontal ? gutterTemUnit + ' 0 0' : '0 ' + gutterTemUnit + ' 0';
str = 'margin: 0 ' + dir + ';';
}
if (TRANSITIONDURATION && speedTem) { str += getTrsnsitionDurationStyle(speedTem); }
return str;
}
function getContainerWidth (fixedWidthTem, gutterTem, itemsTem) {
var str;
if (fixedWidthTem) {
str = (fixedWidthTem + gutterTem) * slideCountNew + 'px';
} else {
str = CALC ?
CALC + '(' + slideCountNew * 100 + '% / ' + itemsTem + ')' :
slideCountNew * 100 / itemsTem + '%';
}
return str;
}
function getSlideWidthStyle (fixedWidthTem, gutterTem, itemsTem) {
var str = '';
if (horizontal) {
str = 'width:';
if (fixedWidthTem) {
str += (fixedWidthTem + gutterTem) + 'px';
} else {
var dividend = carousel ? slideCountNew : itemsTem;
str += CALC ?
CALC + '(100% / ' + dividend + ')' :
100 / dividend + '%';
}
str += importantStr + ';';
}
return str;
}
function getSlideGutterStyle (gutterTem) {
var str = '';
// gutter maybe interger || 0
// so can't use 'if (gutter)'
if (gutterTem !== false) {
var prop = horizontal ? 'padding-' : 'margin-',
dir = horizontal ? 'right' : 'bottom';
str = prop + dir + ': ' + gutterTem + 'px;';
}
return str;
}
function getCSSPrefix (name, num) {
var prefix = name.substring(0, name.length - num).toLowerCase();
if (prefix) { prefix = '-' + prefix + '-'; }
return prefix;
}
function getTrsnsitionDurationStyle (speed) {
return getCSSPrefix(TRANSITIONDURATION, 18) + 'transition-duration:' + speed / 1000 + 's;';
}
function getAnimationDurationStyle (speed) {
return getCSSPrefix(ANIMATIONDURATION, 17) + 'animation-duration:' + speed / 1000 + 's;';
}
(function sliderInit () {
// First thing first, wrap container with 'outerWrapper > innerWrapper',
// to get the correct view width
outerWrapper.appendChild(innerWrapper);
containerParent.insertBefore(outerWrapper, container);
innerWrapper.appendChild(container);
vpInner = getViewportWidth(innerWrapper);
var classOuter = 'tns-outer',
classInner = 'tns-inner',
hasGutter = checkOption('gutter');
if (carousel) {
if (horizontal) {
if (checkOption('edgePadding') || hasGutter && !options.fixedWidth) {
classOuter += ' tns-ovh';
} else {
classInner += ' tns-ovh';
}
} else {
classInner += ' tns-ovh';
}
} else if (hasGutter) {
classOuter += ' tns-ovh';
}
outerWrapper.className = classOuter;
innerWrapper.className = classInner;
innerWrapper.id = slideId + '-iw';
if (autoHeight) { innerWrapper.className += ' tns-ah'; }
// set container properties
if (container.id === '') { container.id = slideId; }
classContainer += SUBPIXEL ? ' tns-subpixel' : ' tns-no-subpixel';
classContainer += CALC ? ' tns-calc' : ' tns-no-calc';
if (carousel) { classContainer += ' tns-' + options.axis; }
container.className += classContainer;
// add event
if (carousel && TRANSITIONEND) {
var eve = {};
eve[TRANSITIONEND] = onTransitionEnd;
addEvents(container, eve);
}
// delete datas after init
classOuter = classInner = null;
// add id, class, aria attributes
// before clone slides
for (var x = 0; x < slideCount; x++) {
var item = slideItems[x];
if (!item.id) { item.id = slideId + '-item' + x; }
addClass(item, 'tns-item');
if (!carousel && animateNormal) { addClass(item, animateNormal); }
setAttrs(item, {
'aria-hidden': 'true',
'tabindex': '-1'
});
}
// clone slides
if (loop || edgePadding) {
var fragmentBefore = doc.createDocumentFragment(),
fragmentAfter = doc.createDocumentFragment();
for (var j = cloneCount; j--;) {
var num = j%slideCount,
cloneFirst = slideItems[num].cloneNode(true);
removeAttrs(cloneFirst, 'id');
fragmentAfter.insertBefore(cloneFirst, fragmentAfter.firstChild);
if (carousel) {
var cloneLast = slideItems[slideCount - 1 - num].cloneNode(true);
removeAttrs(cloneLast, 'id');
fragmentBefore.appendChild(cloneLast);
}
}
container.insertBefore(fragmentBefore, container.firstChild);
container.appendChild(fragmentAfter);
slideItems = container.children;
}
// add image events
if (checkOption('autoHeight') || !carousel) {
var imgs = container.querySelectorAll('img');
// check all image complete status
// add complete class if true
forEachNodeList(imgs, function(img) {
addEvents(img, imgEvents);
var src = img.src;
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
});
// set imgsComplete to true
// when all images are compulete (loaded or error)
raf(function(){ checkImagesLoaded(arrayFromNodeList(imgs), function() {
imgsComplete = true;
}); });
}
// activate visible slides
// add aria attrs
// set animation classes and left value for gallery slider
// use slide count when slides are fewer than items
for (var i = index, l = index + Math.min(slideCount, items); i < l; i++) {
var item = slideItems[i];
setAttrs(item, {'aria-hidden': 'false'});
removeAttrs(item, ['tabindex']);
addClass(item, slideActiveClass);
if (!carousel) {
item.style.left = (i - index) * 100 / items + '%';
addClass(item, animateIn);
removeClass(item, animateNormal);
}
}
if (carousel && horizontal) {
// set font-size rules
// for modern browsers
if (SUBPIXEL) {
// set slides font-size first
addCSSRule(sheet, '#' + slideId + ' > .tns-item', 'font-size:' + win.getComputedStyle(slideItems[0]).fontSize + ';', getCssRulesLength(sheet));
addCSSRule(sheet, '#' + slideId, 'font-size:0;', getCssRulesLength(sheet));
// slide left margin
// for IE8 & webkit browsers (no subpixel)
} else {
forEachNodeList(slideItems, function (slide, i) {
slide.style.marginLeft = getSlideMarginLeft(i);
});
}
}
// all browsers which support CSS transitions support CSS media queries
if (CSSMQ) {
// inner wrapper styles
var str = getInnerWrapperStyles(options.edgePadding, options.gutter, options.fixedWidth, options.speed);
addCSSRule(sheet, '#' + slideId + '-iw', str, getCssRulesLength(sheet));
// container styles
if (carousel) {
str = horizontal ? 'width:' + getContainerWidth(options.fixedWidth, options.gutter, options.items) + ';' : '';
if (TRANSITIONDURATION) { str += getTrsnsitionDurationStyle(speed); }
addCSSRule(sheet, '#' + slideId, str, getCssRulesLength(sheet));
}
// slide styles
if (horizontal || options.gutter) {
str = getSlideWidthStyle(options.fixedWidth, options.gutter, options.items) +
getSlideGutterStyle(options.gutter);
// set gallery items transition-duration
if (!carousel) {
if (TRANSITIONDURATION) { str += getTrsnsitionDurationStyle(speed); }
if (ANIMATIONDURATION) { str += getAnimationDurationStyle(speed); }
}
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
// non CSS mediaqueries: IE8
// ## update inner wrapper, container, slides if needed
// set inline styles for inner wrapper & container
// insert stylesheet (one line) for slides only (since slides are many)
} else {
// inner wrapper styles
innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth);
// container styles
if (carousel && horizontal) {
container.style.width = getContainerWidth(fixedWidth, gutter, items);
}
// slide styles
if (horizontal || gutter) {
var str = getSlideWidthStyle(fixedWidth, gutter, items) +
getSlideGutterStyle(gutter);
// append to the last line
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
}
if (!horizontal && !disable) {
getSlideOffsetTops();
updateContentWrapperHeight();
}
// media queries
if (responsive && CSSMQ) {
breakpoints.forEach(function(bp) {
var opts = responsive[bp],
str = '',
innerWrapperStr = '',
containerStr = '',
slideStr = '',
itemsBP = getOption('items', bp),
fixedWidthBP = getOption('fixedWidth', bp),
speedBP = getOption('speed', bp),
edgePaddingBP = getOption('edgePadding', bp),
gutterBP = getOption('gutter', bp);
// inner wrapper string
if ('edgePadding' in opts || 'gutter' in opts) {
innerWrapperStr = '#' + slideId + '-iw{' + getInnerWrapperStyles(edgePaddingBP, gutterBP, fixedWidthBP, speedBP) + '}';
}
// container string
if (carousel && horizontal && ('fixedWidth' in opts || 'gutter' in opts || 'items' in opts)) {
containerStr = 'width:' + getContainerWidth(fixedWidthBP, gutterBP, itemsBP) + ';';
}
if (TRANSITIONDURATION && 'speed' in opts) {
containerStr += getTrsnsitionDurationStyle(speedBP);
}
if (containerStr) {
containerStr = '#' + slideId + '{' + containerStr + '}';
}
// slide string
if ('fixedWidth' in opts || checkOption('fixedWidth') && 'gutter' in opts || !carousel && 'items' in opts) {
slideStr += getSlideWidthStyle(fixedWidthBP, gutterBP, itemsBP);
}
if ('gutter' in opts) {
slideStr += getSlideGutterStyle(gutterBP);
}
// set gallery items transition-duration
if (!carousel && 'speed' in opts) {
if (TRANSITIONDURATION) { slideStr += getTrsnsitionDurationStyle(speedBP); }
if (ANIMATIONDURATION) { slideStr += getAnimationDurationStyle(speedBP); }
}
if (slideStr) { slideStr = '#' + slideId + ' > .tns-item{' + slideStr + '}'; }
// add up
str = innerWrapperStr + containerStr + slideStr;
if (str) {
sheet.insertRule('@media (min-width: ' + bp / 16 + 'em) {' + str + '}', sheet.cssRules.length);
}
});
}
// set container transform property
if (carousel && !disable) {
doContainerTransformSilent();
}
// == msInit ==
// for IE10
if (navigator.msMaxTouchPoints) {
addClass(container, 'ms-touch');
addEvents(container, {'scroll': ie10Scroll});
setSnapInterval();
}
// == navInit ==
if (hasNav) {
var initIndex = !carousel ? 0 : cloneCount;
// customized nav
// will not hide the navs in case they're thumbnails
if (navContainer) {
setAttrs(navContainer, {'aria-label': 'Carousel Pagination'});
navItems = navContainer.children;
forEachNodeList(navItems, function (item, i) {
setAttrs(item, {
'data-nav': i,
'tabindex': '-1',
'aria-selected': 'false',
'aria-controls': slideItems[initIndex + i].id,
});
});
// generated nav
} else {
var navHtml = '',
hiddenStr = navAsThumbnails ? '' : 'hidden';
for (var i = 0; i < slideCount; i++) {
// hide nav items by default
navHtml += '<button data-nav="' + i +'" tabindex="-1" aria-selected="false" aria-controls="' + slideItems[initIndex + i].id + '" ' + hiddenStr + ' type="button"></button>';
}
navHtml = '<div class="tns-nav" aria-label="Carousel Pagination">' + navHtml + '</div>';
outerWrapper.insertAdjacentHTML('afterbegin', navHtml);
navContainer = outerWrapper.querySelector('.tns-nav');
navItems = navContainer.children;
}
updateNavVisibility();
// add transition
if (TRANSITIONDURATION) {
var prefix = TRANSITIONDURATION.substring(0, TRANSITIONDURATION.length - 18).toLowerCase(),
str = 'transition: all ' + speed / 1000 + 's';
if (prefix) {
str = '-' + prefix + '-' + str;
}
addCSSRule(sheet, '[aria-controls^=' + slideId + '-item]', str, getCssRulesLength(sheet));
}
setAttrs(navItems[navCurrentIndex], {'tabindex': '0', 'aria-selected': 'true'});
addClass(navItems[navCurrentIndex], navActiveClass);
// add events
addEvents(navContainer, navEvents);
if (!nav) { hideElement(navContainer); }
}
// == autoplayInit ==
if (hasAutoplay) {
var txt = autoplay ? 'stop' : 'start';
if (autoplayButton) {
setAttrs(autoplayButton, {'data-action': txt});
} else if (options.autoplayButtonOutput) {
innerWrapper.insertAdjacentHTML('beforebegin', '<button data-action="' + txt + '" type="button">' + autoplayHtmlStrings[0] + txt + autoplayHtmlStrings[1] + autoplayText[0] + '</button>');
autoplayButton = outerWrapper.querySelector('[data-action]');
}
// add event
if (autoplayButton) {
addEvents(autoplayButton, {'click': toggleAutoplay});
}
if (!autoplay) {
if (autoplayButton) {
hideElement(autoplayButton);
}
} else {
startAutoplay();
if (autoplayHoverPause) { addEvents(container, hoverEvents); }
if (autoplayResetOnVisibility) { addEvents(container, visibilityEvent); }
}
}
// == controlsInit ==
if (hasControls) {
if (controlsContainer || (prevButton && nextButton)) {
if (controlsContainer) {
prevButton = controlsContainer.children[0];
nextButton = controlsContainer.children[1];
setAttrs(controlsContainer, {
'aria-label': 'Carousel Navigation',
'tabindex': '0'
});
setAttrs(controlsContainer.children, {
'aria-controls': slideId,
'tabindex': '-1',
});
}
setAttrs(prevButton, {'data-controls' : 'prev'});
setAttrs(nextButton, {'data-controls' : 'next'});
} else {
outerWrapper.insertAdjacentHTML('afterbegin', '<div class="tns-controls" aria-label="Carousel Navigation" tabindex="0"><button data-controls="prev" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[0] + '</button><button data-controls="next" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[1] + '</button></div>');
controlsContainer = outerWrapper.querySelector('.tns-controls');
prevButton = controlsContainer.children[0];
nextButton = controlsContainer.children[1];
}
prevIsButton = isButton(prevButton);
nextIsButton = isButton(nextButton);
updateControlsStatus();
// add events
if (controlsContainer) {
addEvents(controlsContainer, controlsEvents);
} else {
addEvents(prevButton, controlsEvents);
addEvents(nextButton, controlsEvents);
}
if (!controls) { hideElement(controlsContainer); }
}
// if (!navigator.msMaxTouchPoints) {
if (carousel) {
if (touch) { addEvents(container, touchEvents); }
if (mouseDrag) { addEvents(container, dragEvents); }
}
// }
if (arrowKeys) { addEvents(doc, docmentKeydownEvent); }
if (nested === 'inner') {
events.on('outerResized', function () {
resizeTasks();
events.emit('innerLoaded', info());
});
} else {
addEvents(win, {'resize': onResize});
}
if (nested === 'outer') {
events.on('innerLoaded', runAutoHeight);
} else if ((autoHeight || !carousel) && !disable) {
runAutoHeight();
}
lazyLoad();
toggleSlideDisplayAndEdgePadding();
updateFixedWidthInnerWrapperStyle();
events.on('indexChanged', additionalUpdates);
if (typeof onInit === 'function') { onInit(info()); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
if (disable) { disableSlider(true); }
isOn = true;
})();
// === ON RESIZE ===
function onResize (e) {
raf(function(){ resizeTasks(getEvent(e)); });
}
function resizeTasks (e) {
if (!isOn) { return; }
windowWidth = getWindowWidth();
if (nested === 'outer') { events.emit('outerResized', info(e)); }
var breakpointZoneTem = breakpointZone,
indexTem = index,
itemsTem = items,
freezeTem = freeze,
needContainerTransform = false;
if (fixedWidth) { vpOuter = getViewportWidth(outerWrapper); }
vpInner = getViewportWidth(innerWrapper);
if (breakpoints) { setBreakpointZone(); }
// things do when breakpoint zone change
if (breakpointZoneTem !== breakpointZone || fixedWidth) {
var slideByTem = slideBy,
arrowKeysTem = arrowKeys,
autoHeightTem = autoHeight,
fixedWidthTem = fixedWidth,
edgePaddingTem = edgePadding,
gutterTem = gutter,
disableTem = disable;
// update variables
items = getOption('items');
slideBy = getOption('slideBy');
disable = getOption('disable');
freeze = disable ? true : freezable ? slideCount <= items : false;
if (items !== itemsTem) {
indexMax = getIndexMax();
// check index before transform in case
// slider reach the right edge then items become bigger
updateIndex();
}
if (disable !== disableTem) {
disableSlider(disable);
}
if (freeze !== freezeTem) {
// reset index to initial status
if (freeze) { index = !carousel ? 0 : cloneCount; }
toggleSlideDisplayAndEdgePadding();
}
if (breakpointZoneTem !== breakpointZone) {
speed = getOption('speed');
edgePadding = getOption('edgePadding');
gutter = getOption('gutter');
fixedWidth = getOption('fixedWidth');
if (!disable && fixedWidth !== fixedWidthTem) {
needContainerTransform = true;
}
autoHeight = getOption('autoHeight');
if (autoHeight !== autoHeightTem) {
if (!autoHeight) { innerWrapper.style.height = ''; }
}
}
arrowKeys = freeze ? false : getOption('arrowKeys');
if (arrowKeys !== arrowKeysTem) {
arrowKeys ?
addEvents(doc, docmentKeydownEvent) :
removeEvents(doc, docmentKeydownEvent);
}
if (hasControls) {
var controlsTem = controls,
controlsTextTem = controlsText;
controls = freeze ? false : getOption('controls');
controlsText = getOption('controlsText');
if (controls !== controlsTem) {
controls ?
showElement(controlsContainer) :
hideElement(controlsContainer);
}
if (controlsText !== controlsTextTem) {
prevButton.innerHTML = controlsText[0];
nextButton.innerHTML = controlsText[1];
}
}
if (hasNav) {
var navTem = nav;
nav = freeze ? false : getOption('nav');
if (nav !== navTem) {
if (nav) {
showElement(navContainer);
updateNavVisibility();
} else {
hideElement(navContainer);
}
}
}
if (hasTouch) {
var touchTem = touch;
touch = freeze ? false : getOption('touch');
if (touch !== touchTem && carousel) {
touch ?
addEvents(container, touchEvents) :
removeEvents(container, touchEvents);
}
}
if (hasMouseDrag) {
var mouseDragTem = mouseDrag;
mouseDrag = freeze ? false : getOption('mouseDrag');
if (mouseDrag !== mouseDragTem && carousel) {
mouseDrag ?
addEvents(container, dragEvents) :
removeEvents(container, dragEvents);
}
}
if (hasAutoplay) {
var autoplayTem = autoplay,
autoplayHoverPauseTem = autoplayHoverPause,
autoplayResetOnVisibilityTem = autoplayResetOnVisibility,
autoplayTextTem = autoplayText;
if (freeze) {
autoplay = autoplayHoverPause = autoplayResetOnVisibility = false;
} else {
autoplay = getOption('autoplay');
if (autoplay) {
autoplayHoverPause = getOption('autoplayHoverPause');
autoplayResetOnVisibility = getOption('autoplayResetOnVisibility');
} else {
autoplayHoverPause = autoplayResetOnVisibility = false;
}
}
autoplayText = getOption('autoplayText');
autoplayTimeout = getOption('autoplayTimeout');
if (autoplay !== autoplayTem) {
if (autoplay) {
if (autoplayButton) { showElement(autoplayButton); }
if (!animating && !autoplayUserPaused) { startAutoplay(); }
} else {
if (autoplayButton) { hideElement(autoplayButton); }
if (animating) { stopAutoplay(); }
}
}
if (autoplayHoverPause !== autoplayHoverPauseTem) {
autoplayHoverPause ?
addEvents(container, hoverEvents) :
removeEvents(container, hoverEvents);
}
if (autoplayResetOnVisibility !== autoplayResetOnVisibilityTem) {
autoplayResetOnVisibility ?
addEvents(doc, visibilityEvent) :
removeEvents(doc, visibilityEvent);
}
if (autoplayButton && autoplayText !== autoplayTextTem) {
var i = autoplay ? 1 : 0,
html = autoplayButton.innerHTML,
len = html.length - autoplayTextTem[i].length;
if (html.substring(len) === autoplayTextTem[i]) {
autoplayButton.innerHTML = html.substring(0, len) + autoplayText[i];
}
}
}
// IE8
// ## update inner wrapper, container, slides if needed
// set inline styles for inner wrapper & container
// insert stylesheet (one line) for slides only (since slides are many)
if (!CSSMQ) {
// inner wrapper styles
if (!freeze && (edgePadding !== edgePaddingTem || gutter !== gutterTem)) {
innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth);
}
// container styles
if (carousel && horizontal && (fixedWidth !== fixedWidthTem || gutter !== gutterTem || items !== itemsTem)) {
container.style.width = getContainerWidth(fixedWidth, gutter, items);
}
// slide styles
if (horizontal && (items !== itemsTem || gutter !== gutterTem || fixedWidth != fixedWidthTem)) {
var str = getSlideWidthStyle(fixedWidth, gutter, items) +
getSlideGutterStyle(gutter);
// remove the last line and
// add new styles
sheet.removeRule(getCssRulesLength(sheet) - 1);
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
if (!fixedWidth) { needContainerTransform = true; }
}
if (index !== indexTem) {
events.emit('indexChanged', info());
needContainerTransform = true;
}
if (items !== itemsTem) {
additionalUpdates();
updateSlidePosition();
if (navigator.msMaxTouchPoints) { setSnapInterval(); }
}
}
// things always do regardless of breakpoint zone changing
if (!horizontal && !disable) {
getSlideOffsetTops();
updateContentWrapperHeight();
needContainerTransform = true;
}
if (needContainerTransform) {
doContainerTransformSilent();
indexCached = index;
}
updateFixedWidthInnerWrapperStyle(true);
// auto height
if ((autoHeight || !carousel) && !disable) { runAutoHeight(); }
}
// === INITIALIZATION FUNCTIONS === //
function setBreakpointZone () {
breakpointZone = 0;
breakpoints.forEach(function(bp, i) {
if (windowWidth >= bp) { breakpointZone = i + 1; }
});
}
function loopNumber (num, min, max) {
return index >= indexMin && index <= indexMax ? index : index > indexMax ? index - slideCount : index + slideCount;
}
function cutindexber (index, min, indexMax) {
return index >= indexMin && index <= indexMax ? index : index > indexMax ? indexMax : indexMin;
}
// (slideBy, indexMin, indexMax) => index
var updateIndex = (function () {
return loop ?
carousel ?
// loop + carousel
function () {
var leftEdge = indexMin,
rightEdge = indexMax;
leftEdge += slideBy;
rightEdge -= slideBy;
// adjust edges when edge padding is true
// or fixed-width slider with extra space on the right side
if (edgePadding) {
leftEdge += 1;
rightEdge -= 1;
} else if (fixedWidth) {
var gt = gutter ? gutter : 0;
if (vpOuter%(fixedWidth + gt) > gt) { rightEdge -= 1; }
}
if (cloneCount) {
if (index > rightEdge) {
index -= slideCount;
} else if (index < leftEdge) {
index += slideCount;
}
}
} :
// loop + gallery
function() {
if (index > indexMax) {
while (index >= indexMin + slideCount) { index -= slideCount; }
} else if (index < indexMin) {
while (index <= indexMax - slideCount) { index += slideCount; }
}
} :
// non-loop
function() {
index = (index >= indexMin && index <= indexMax) ? index :
index > indexMax ? indexMax : indexMin;
};
})();
function toggleSlideDisplayAndEdgePadding () {
// if (cloneCount) {
// if (fixedWidth && cloneCount) {
var str = 'tns-transparent';
if (freeze) {
if (!frozen) {
// remove edge padding from inner wrapper
if (edgePadding) { innerWrapper.style.margin = '0px'; }
// add class tns-transparent to cloned slides
if (cloneCount) {
for (var i = cloneCount; i--;) {
if (carousel) { addClass(slideItems[i], str); }
addClass(slideItems[slideCountNew - i - 1], str);
}
}
frozen = true;
}
} else if (frozen) {
// restore edge padding for inner wrapper
// for mordern browsers
if (edgePadding && !fixedWidth && CSSMQ) { innerWrapper.style.margin = ''; }
// remove class tns-transparent to cloned slides
if (cloneCount) {
for (var i = cloneCount; i--;) {
if (carousel) { removeClass(slideItems[i], str); }
removeClass(slideItems[slideCountNew - i - 1], str);
}
}
frozen = false;
}
// }
}
function updateFixedWidthInnerWrapperStyle (resize) {
if (fixedWidth && edgePadding) {
// remove edge padding when freeze or viewport narrower than one slide
if (freeze || vpOuter <= (fixedWidth + gutter)) {
if (innerWrapper.style.margin !== '0px') { innerWrapper.style.margin = '0px'; }
// update edge padding on resize
} else if (resize) {
innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth);
}
}
}
function disableSlider (disable) {
var len = slideItems.length;
if (disable) {
sheet.disabled = true;
container.className = container.className.replace(classContainer.substring(1), '');
removeElementStyles(container);
if (loop) {
for (var j = cloneCount; j--;) {
if (carousel) { hideElement(slideItems[j]); }
hideElement(slideItems[len - j - 1]);
}
}
// vertical slider
if (!horizontal || !carousel) { removeElementStyles(innerWrapper); }
// gallery
if (!carousel) {
for (var i = index, l = index + slideCount; i < l; i++) {
var item = slideItems[i];
removeElementStyles(item);
removeClass(item, animateIn);
removeClass(item, animateNormal);
}
}
} else {
sheet.disabled = false;
container.className += classContainer;
// vertical slider: get offsetTops before container transform
if (!horizontal) { getSlideOffsetTops(); }
doContainerTransformSilent();
if (loop) {
for (var j = cloneCount; j--;) {
if (carousel) { showElement(slideItems[j]); }
showElement(slideItems[len - j - 1]);
}
}
// gallery
if (!carousel) {
for (var i = index, l = index + slideCount; i < l; i++) {
var item = slideItems[i],
classN = i < index + items ? animateIn : animateNormal;
item.style.left = (i - index) * 100 / items + '%';
addClass(item, classN);
}
}
}
}
// lazyload
function lazyLoad () {
if (lazyload && !disable) {
var i = index,
len = index + items;
if (edgePadding) {
i -=1;
len +=1;
}
i = Math.max(i, 0);
len = Math.min(len, slideCountNew);
for(; i < len; i++) {
forEachNodeList(slideItems[i].querySelectorAll('.tns-lazy-img'), function (img) {
// stop propagationl transitionend event to container
var eve = {};
eve[TRANSITIONEND] = function (e) { e.stopPropagation(); };
addEvents(img, eve);
if (!hasClass(img, 'loaded')) {
img.src = getAttr(img, 'data-src');
addClass(img, 'loaded');
}
});
}
}
}
function imgLoadedOrError (e) {
var img = getTarget(e);
addClass(img, imgCompleteClass);
removeEvents(img, imgEvents);
}
function getImageArray (slideStart, slideRange) {
var imgs = [];
for (var i = slideStart, l = slideStart + slideRange; i < l; i++) {
forEachNodeList(slideItems[i].querySelectorAll('img'), function (img) {
imgs.push(img);
});
}
return imgs;
}
// check if all visible images are loaded
// and update container height if it's done
function runAutoHeight () {
var imgs = autoHeight ?
getImageArray(index, items) :
getImageArray(cloneCount, slideCount);
raf(function(){ checkImagesLoaded(imgs, updateInnerWrapperHeight); });
}
function checkImagesLoaded (imgs, cb) {
// directly execute callback function if all images are complete
if (imgsComplete) { return cb(); }
// check selected image classes otherwise
imgs.forEach(function (img, index) {
if (hasClass(img, imgCompleteClass)) { imgs.splice(index, 1); }
});
// execute callback function if selected images are all complete
if (!imgs.length) { return cb(); }
// otherwise execute this functiona again
raf(function(){ checkImagesLoaded(imgs, cb); });
}
function additionalUpdates () {
lazyLoad();
updateSlideStatus();
updateControlsStatus();
updateNavVisibility();
updateNavStatus();
}
function getMaxSlideHeight (slideStart, slideRange) {
var heights = [];
for (var i = slideStart, l = slideStart + slideRange; i < l; i++) {
heights.push(slideItems[i].offsetHeight);
}
return Math.max.apply(null, heights);
}
// update inner wrapper height
// 1. get the max-height of the visible slides
// 2. set transitionDuration to speed
// 3. update inner wrapper height to max-height
// 4. set transitionDuration to 0s after transition done
function updateInnerWrapperHeight () {
var maxHeight = autoHeight ?
getMaxSlideHeight(index, items) :
getMaxSlideHeight(cloneCount, slideCount);
if (innerWrapper.style.height !== maxHeight) { innerWrapper.style.height = maxHeight + 'px'; }
}
// get the distance from the top edge of the first slide to each slide
// (init) => slideOffsetTops
function getSlideOffsetTops () {
slideOffsetTops = [0];
var topFirst = slideItems[0].getBoundingClientRect().top, attr;
for (var i = 1; i < slideCountNew; i++) {
attr = slideItems[i].getBoundingClientRect().top;
slideOffsetTops.push(attr - topFirst);
}
}
// set snapInterval (for IE10)
function setSnapInterval () {
outerWrapper.style.msScrollSnapPointsX = 'snapInterval(0%, ' + (100 / items) + '%)';
}
// update slide
function updateSlideStatus () {
var l = index + Math.min(slideCount, items);
for (var i = slideCountNew; i--;) {
var item = slideItems[i];
// visible slides
if (i >= index && i < l) {
if (hasAttr(item, 'tabindex')) {
setAttrs(item, {'aria-hidden': 'false'});
removeAttrs(item, ['tabindex']);
addClass(item, slideActiveClass);
}
// hidden slides
} else {
if (!hasAttr(item, 'tabindex')) {
setAttrs(item, {
'aria-hidden': 'true',
'tabindex': '-1'
});
}
if (hasClass(item, slideActiveClass)) {
removeClass(item, slideActiveClass);
}
}
}
}
// gallery: update slide position
function updateSlidePosition () {
if (!carousel) {
var l = index + Math.min(slideCount, items);
for (var i = slideCountNew; i--;) {
var item = slideItems[i];
if (i >= index && i < l) {
// add transitions to visible slides when adjusting their positions
addClass(item, 'tns-moving');
item.style.left = (i - index) * 100 / items + '%';
addClass(item, animateIn);
removeClass(item, animateNormal);
} else if (item.style.left) {
item.style.left = '';
addClass(item, animateNormal);
removeClass(item, animateIn);
}
// remove outlet animation
removeClass(item, animateOut);
}
// removing '.tns-moving'
setTimeout(function() {
forEachNodeList(slideItems, function(el) {
removeClass(el, 'tns-moving');
});
}, 300);
}
}
// set tabindex & aria-selected on Nav
function updateNavStatus () {
// get current nav
if (nav) {
navCurrentIndex = navClicked !== -1 ? navClicked : getAbsIndex();
navClicked = -1;
if (navCurrentIndex !== navCurrentIndexCached) {
var navPrev = navItems[navCurrentIndexCached],
navCurrent = navItems[navCurrentIndex];
setAttrs(navPrev, {
'tabindex': '-1',
'aria-selected': 'false'
});
setAttrs(navCurrent, {
'tabindex': '0',
'aria-selected': 'true'
});
removeClass(navPrev, navActiveClass);
addClass(navCurrent, navActiveClass);
}
}
}
function getLowerCaseNodeName (el) {
return el.nodeName.toLowerCase();
}
function isButton (el) {
return getLowerCaseNodeName(el) === 'button';
}
function isAriaDisabled (el) {
return el.getAttribute('aria-disabled') === 'true';
}
function disEnableElement (isButton, el, val) {
if (isButton) {
el.disabled = val;
} else {
el.setAttribute('aria-disabled', val.toString());
}
}
// set 'disabled' to true on controls when reach the edges
function updateControlsStatus () {
if (!controls || rewind || loop) { return; }
var prevDisabled = (prevIsButton) ? prevButton.disabled : isAriaDisabled(prevButton),
nextDisabled = (nextIsButton) ? nextButton.disabled : isAriaDisabled(nextButton),
disablePrev = (index === indexMin) ? true : false,
disableNext = (!rewind && index === indexMax) ? true : false;
if (disablePrev && !prevDisabled) {
disEnableElement(prevIsButton, prevButton, true);
}
if (!disablePrev && prevDisabled) {
disEnableElement(prevIsButton, prevButton, false);
}
if (disableNext && !nextDisabled) {
disEnableElement(nextIsButton, nextButton, true);
}
if (!disableNext && nextDisabled) {
disEnableElement(nextIsButton, nextButton, false);
}
}
// set duration
function resetDuration (el, str) {
if (TRANSITIONDURATION) { el.style[TRANSITIONDURATION] = str; }
}
function getContainerTransformValue () {
var val;
if (horizontal) {
if (fixedWidth) {
val = - (fixedWidth + gutter) * index + 'px';
} else {
var denominator = TRANSFORM ? slideCountNew : items;
val = - index * 100 / denominator + '%';
}
} else {
val = - slideOffsetTops[index] + 'px';
}
return val;
}
function doContainerTransformSilent (val) {
resetDuration(container, '0s');
doContainerTransform(val);
setTimeout(function() { resetDuration(container, ''); }, 0);
}
function doContainerTransform (val, test) {
if (!val) { val = getContainerTransformValue(); }
container.style[transformAttr] = transformPrefix + val + transformPostfix;
}
function animateSlide (number, classOut, classIn, isOut) {
var l = number + items;
if (!loop) { l = Math.min(l, slideCountNew); }
for (var i = number; i < l; i++) {
var item = slideItems[i];
// set item positions
if (!isOut) { item.style.left = (i - index) * 100 / items + '%'; }
if (animateDelay && TRANSITIONDELAY) {
item.style[TRANSITIONDELAY] = item.style[ANIMATIONDELAY] = animateDelay * (i - number) / 1000 + 's';
}
removeClass(item, classOut);
addClass(item, classIn);
if (isOut) { slideItemsOut.push(item); }
}
}
// make transfer after click/drag:
// 1. change 'transform' property for mordern browsers
// 2. change 'left' property for legacy browsers
var transformCore = (function () {
return carousel ?
function (duration, distance) {
if (!distance) { distance = getContainerTransformValue(); }
// constrain the distance when non-loop no-edgePadding fixedWidth reaches the right edge
if (hasRightDeadZone && index === indexMax) {
distance = - ((fixedWidth + gutter) * slideCountNew - vpInner) + 'px';
}
if (TRANSITIONDURATION || !duration) {
// for morden browsers with non-zero duration or
// zero duration for all browsers
doContainerTransform(distance);
// run fallback function manually
// when duration is 0 / container is hidden
if (!duration || !isVisible(container)) { onTransitionEnd(); }
} else {
// for old browser with non-zero duration
jsTransform(container, transformAttr, transformPrefix, transformPostfix, distance, speed, onTransitionEnd);
}
if (!horizontal) { updateContentWrapperHeight(); }
} :
function (duration) {
slideItemsOut = [];
var eve = {};
eve[TRANSITIONEND] = eve[ANIMATIONEND] = onTransitionEnd;
removeEvents(slideItems[indexCached], eve);
addEvents(slideItems[index], eve);
animateSlide(indexCached, animateIn, animateOut, true);
animateSlide(index, animateNormal, animateIn);
// run fallback function manually
// when transition or animation not supported / duration is 0
if (!TRANSITIONEND || !ANIMATIONEND || !duration) { onTransitionEnd(); }
};
})();
function doTransform (duration, distance) {
// check duration is defined and is a number
if (isNaN(duration)) { duration = speed; }
// if container is hidden, set duration to 0
// to fix an issue where browser doesn't fire ontransitionend on hidden element
if (animating && !isVisible(container)) { duration = 0; }
transformCore(duration, distance);
}
function render (e, sliderMoved) {
if (updateIndexBeforeTransform) { updateIndex(); }
// render when slider was moved (touch or drag) even though index may not change
if (index !== indexCached || sliderMoved) {
// events
events.emit('indexChanged', info());
events.emit('transitionStart', info());
// pause autoplay when click or keydown from user
if (animating && e && ['click', 'keydown'].indexOf(e.type) >= 0) { stopAutoplay(); }
running = true;
doTransform();
}
}
/*
* Transfer prefixed properties to the same format
* CSS: -Webkit-Transform => webkittransform
* JS: WebkitTransform => webkittransform
* @param {string} str - property
*
*/
function strTrans (str) {
return str.toLowerCase().replace(/-/g, '');
}
// AFTER TRANSFORM
// Things need to be done after a transfer:
// 1. check index
// 2. add classes to visible slide
// 3. disable controls buttons when reach the first/last slide in non-loop slider
// 4. update nav status
// 5. lazyload images
// 6. update container height
function onTransitionEnd (event) {
// check running on gallery mode
// make sure trantionend/animationend events run only once
if (carousel || running) {
events.emit('transitionEnd', info(event));
if (!carousel && slideItemsOut.length > 0) {
for (var i = 0; i < slideItemsOut.length; i++) {
var item = slideItemsOut[i];
// set item positions
item.style.left = '';
if (ANIMATIONDELAY && TRANSITIONDELAY) {
item.style[ANIMATIONDELAY] = '';
item.style[TRANSITIONDELAY] = '';
}
removeClass(item, animateOut);
addClass(item, animateNormal);
}
}
/* update slides, nav, controls after checking ...
* => legacy browsers who don't support 'event'
* have to check event first, otherwise event.target will cause an error
* => or 'gallery' mode:
* + event target is slide item
* => or 'carousel' mode:
* + event target is container,
* + event.property is the same with transform attribute
*/
if (!event ||
!carousel && event.target.parentNode === container ||
event.target === container && strTrans(event.propertyName) === strTrans(transformAttr)) {
if (!updateIndexBeforeTransform) {
var indexTem = index;
updateIndex();
if (index !== indexTem) {
events.emit('indexChanged', info());
doContainerTransformSilent();
}
}
if (autoHeight) { runAutoHeight(); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
running = false;
navCurrentIndexCached = navCurrentIndex;
indexCached = index;
}
}
}
// # ACTIONS
function goTo (targetIndex, e) {
if (freeze) { return; }
// prev slideBy
if (targetIndex === 'prev') {
onControlsClick(e, -1);
// next slideBy
} else if (targetIndex === 'next') {
onControlsClick(e, 1);
// go to exact slide
} else {
if (running) { onTransitionEnd(); }
// } else if (!running) {
var absIndex = getAbsIndex(),
indexGap = 0;
if (absIndex < 0) { absIndex += slideCount; }
if (targetIndex === 'first') {
indexGap = - absIndex;
} else if (targetIndex === 'last') {
indexGap = carousel ? slideCount - items - absIndex : slideCount - 1 - absIndex;
} else {
if (typeof targetIndex !== 'number') { targetIndex = parseInt(targetIndex); }
if (!isNaN(targetIndex)) {
var absTargetIndex = getAbsIndex(targetIndex);
if (absTargetIndex < 0) { absTargetIndex += slideCount; }
indexGap = absTargetIndex - absIndex;
}
}
index += indexGap;
// if index is changed, start rendering
if (getAbsIndex(index) !== getAbsIndex(indexCached)) {
render(e);
}
}
}
// on controls click
function onControlsClick (e, dir) {
// if (!running) {
if (running) { onTransitionEnd(); }
var passEventObject;
if (!dir) {
e = getEvent(e);
var target = e.target || e.srcElement;
while (target !== controlsContainer && [prevButton, nextButton].indexOf(target) < 0) { target = target.parentNode; }
var targetIn = [prevButton, nextButton].indexOf(target);
if (targetIn >= 0) {
passEventObject = true;
dir = targetIn === 0 ? -1 : 1;
}
}
if (rewind) {
if (index === indexMin && dir === -1) {
goTo('last', e);
return;
} else if (index === indexMax && dir === 1) {
goTo(0, e);
return;
}
}
if (dir) {
index += slideBy * dir;
// pass e when click control buttons or keydown
render((passEventObject || (e && e.type === 'keydown')) ? e : null);
}
// }
}
// on nav click
function onNavClick (e) {
// if (!running) {
if (running) { onTransitionEnd(); }
e = getEvent(e);
var target = e.target || e.srcElement,
navIndex;
// find the clicked nav item
while (target !== navContainer && !hasAttr(target, 'data-nav')) { target = target.parentNode; }
if (hasAttr(target, 'data-nav')) {
navIndex = navClicked = [].indexOf.call(navItems, target);
goTo(navIndex + cloneCount, e);
}
// }
}
// autoplay functions
function setAutoplayTimer () {
autoplayTimer = setInterval(function () {
onControlsClick(null, autoplayDirection);
}, autoplayTimeout);
animating = true;
}
function stopAutoplayTimer () {
clearInterval(autoplayTimer);
animating = false;
}
function updateAutoplayButton (action, txt) {
setAttrs(autoplayButton, {'data-action': action});
autoplayButton.innerHTML = autoplayHtmlStrings[0] + action + autoplayHtmlStrings[1] + txt;
}
function startAutoplay () {
setAutoplayTimer();
if (autoplayButton) { updateAutoplayButton('stop', autoplayText[1]); }
}
function stopAutoplay () {
stopAutoplayTimer();
if (autoplayButton) { updateAutoplayButton('start', autoplayText[0]); }
}
// programaitcally play/pause the slider
function play () {
if (autoplay && !animating) {
startAutoplay();
autoplayUserPaused = false;
}
}
function pause () {
if (animating) {
stopAutoplay();
autoplayUserPaused = true;
}
}
function toggleAutoplay () {
if (animating) {
stopAutoplay();
autoplayUserPaused = true;
} else {
startAutoplay();
autoplayUserPaused = false;
}
}
function onVisibilityChange () {
if (doc.hidden) {
if (animating) {
stopAutoplayTimer();
autoplayVisibilityPaused = true;
}
} else if (autoplayVisibilityPaused) {
setAutoplayTimer();
autoplayVisibilityPaused = false;
}
}
function mouseoverPause () {
if (animating) {
stopAutoplayTimer();
autoplayHoverPaused = true;
}
}
function mouseoutRestart () {
if (autoplayHoverPaused) {
setAutoplayTimer();
autoplayHoverPaused = false;
}
}
// keydown events on document
function onDocumentKeydown (e) {
e = getEvent(e);
switch(e.keyCode) {
case KEYS.LEFT:
onControlsClick(e, -1);
break;
case KEYS.RIGHT:
onControlsClick(e, 1);
}
}
// on key control
function onControlsKeydown (e) {
e = getEvent(e);
var code = e.keyCode;
switch (code) {
case KEYS.LEFT:
case KEYS.UP:
case KEYS.PAGEUP:
if (!prevButton.disabled) {
onControlsClick(e, -1);
}
break;
case KEYS.RIGHT:
case KEYS.DOWN:
case KEYS.PAGEDOWN:
if (!nextButton.disabled) {
onControlsClick(e, 1);
}
break;
case KEYS.HOME:
goTo(0, e);
break;
case KEYS.END:
goTo(slideCount - 1, e);
break;
}
}
// set focus
function setFocus (focus) {
focus.focus();
}
// on key nav
function onNavKeydown (e) {
var curElement = doc.activeElement;
if (!hasAttr(curElement, 'data-nav')) { return; }
e = getEvent(e);
var code = e.keyCode,
navIndex = [].indexOf.call(navItems, curElement),
len = visibleNavIndexes.length,
current = visibleNavIndexes.indexOf(navIndex);
if (options.navContainer) {
len = slideCount;
current = navIndex;
}
function getNavIndex (num) {
return options.navContainer ? num : visibleNavIndexes[num];
}
switch(code) {
case KEYS.LEFT:
case KEYS.PAGEUP:
if (current > 0) { setFocus(navItems[getNavIndex(current - 1)]); }
break;
case KEYS.UP:
case KEYS.HOME:
if (current > 0) { setFocus(navItems[getNavIndex(0)]); }
break;
case KEYS.RIGHT:<|fim▁hole|> case KEYS.PAGEDOWN:
if (current < len - 1) { setFocus(navItems[getNavIndex(current + 1)]); }
break;
case KEYS.DOWN:
case KEYS.END:
if (current < len - 1) { setFocus(navItems[getNavIndex(len - 1)]); }
break;
// Can't use onNavClick here,
// Because onNavClick require event.target as nav items
case KEYS.ENTER:
case KEYS.SPACE:
navClicked = navIndex;
goTo(navIndex + cloneCount, e);
break;
}
}
// IE10 scroll function
function ie10Scroll () {
transformCore(0, container.scrollLeft);
indexCached = index;
}
function getEvent (e) {
e = e || win.event;
return isTouchEvent(e) ? e.changedTouches[0] : e;
}
function getTarget (e) {
return e.target || win.event.srcElement;
}
function isTouchEvent (e) {
return e.type.indexOf('touch') >= 0;
}
function preventDefaultBehavior (e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
function onPanStart (e) {
if (running) { onTransitionEnd(); }
panStart = true;
caf(rafIndex);
rafIndex = raf(function(){ panUpdate(e); });
var $ = getEvent(e);
events.emit(isTouchEvent(e) ? 'touchStart' : 'dragStart', info(e));
if (!isTouchEvent(e) && ['img', 'a'].indexOf(getLowerCaseNodeName(getTarget(e))) >= 0) {
preventDefaultBehavior(e);
}
lastPosition.x = initPosition.x = parseInt($.clientX);
lastPosition.y = initPosition.y = parseInt($.clientY);
translateInit = parseFloat(container.style[transformAttr].replace(transformPrefix, '').replace(transformPostfix, ''));
resetDuration(container, '0s');
}
function onPanMove (e) {
if (panStart) {
var $ = getEvent(e);
lastPosition.x = parseInt($.clientX);
lastPosition.y = parseInt($.clientY);
}
}
function panUpdate (e) {
if (!moveDirectionExpected) {
panStart = false;
return;
}
caf(rafIndex);
if (panStart) { rafIndex = raf(function(){ panUpdate(e); }); }
if (
moveDirectionExpected === '?' &&
lastPosition.x !== initPosition.x &&
lastPosition.y !== initPosition.y) {
moveDirectionExpected = getTouchDirection(toDegree(lastPosition.y - initPosition.y, lastPosition.x - initPosition.x), swipeAngle) === options.axis;
}
if (moveDirectionExpected) {
events.emit(isTouchEvent(e) ? 'touchMove' : 'dragMove', info(e));
var x = translateInit,
dist = getDist(lastPosition, initPosition);
if (!horizontal || fixedWidth) {
x += dist;
x += 'px';
} else {
var percentageX = TRANSFORM ? dist * items * 100 / (vpInner * slideCountNew): dist * 100 / vpInner;
x += percentageX;
x += '%';
}
container.style[transformAttr] = transformPrefix + x + transformPostfix;
}
}
function onPanEnd (e) {
if (swipeAngle) { moveDirectionExpected = '?'; } // reset
if (panStart) {
caf(rafIndex);
resetDuration(container, '');
panStart = false;
var $ = getEvent(e);
lastPosition.x = parseInt($.clientX);
lastPosition.y = parseInt($.clientY);
var dist = getDist(lastPosition, initPosition);
// initPosition = {x:0, y:0}; // reset positions
// lastPosition = {x:0, y:0}; // reset positions
if (Math.abs(dist) >= 5) {
// drag vs click
if (!isTouchEvent(e)) {
// prevent "click"
var target = getTarget(e);
addEvents(target, {'click': function preventClick (e) {
preventDefaultBehavior(e);
removeEvents(target, {'click': preventClick});
}});
}
rafIndex = raf(function() {
events.emit(isTouchEvent(e) ? 'touchEnd' : 'dragEnd', info(e));
if (horizontal) {
var indexMoved = - dist * items / vpInner;
indexMoved = dist > 0 ? Math.floor(indexMoved) : Math.ceil(indexMoved);
index += indexMoved;
} else {
var moved = - (translateInit + dist);
if (moved <= 0) {
index = indexMin;
} else if (moved >= slideOffsetTops[slideOffsetTops.length - 1]) {
index = indexMax;
} else {
var i = 0;
do {
i++;
index = dist < 0 ? i + 1 : i;
} while (i < slideCountNew && moved >= slideOffsetTops[i + 1]);
}
}
render(e, dist);
});
}
}
}
// === RESIZE FUNCTIONS === //
// (slideOffsetTops, index, items) => vertical_conentWrapper.height
function updateContentWrapperHeight () {
innerWrapper.style.height = slideOffsetTops[index + items] - slideOffsetTops[index] + 'px';
}
/*
* get nav item indexes per items
* add 1 more if the nav items cann't cover all slides
* [0, 1, 2, 3, 4] / 3 => [0, 3]
*/
function getVisibleNavIndex () {
// reset visibleNavIndexes
visibleNavIndexes = [];
var absIndexMin = getAbsIndex()%items;
while (absIndexMin < slideCount) {
if (carousel && !loop && absIndexMin + items > slideCount) { absIndexMin = slideCount - items; }
visibleNavIndexes.push(absIndexMin);
absIndexMin += items;
}
// nav count * items < slide count means
// some slides can not be displayed only by nav clicking
if (loop && visibleNavIndexes.length * items < slideCount ||
!loop && visibleNavIndexes[0] > 0) {
visibleNavIndexes.unshift(0);
}
}
/*
* 1. update visible nav items list
* 2. add "hidden" attributes to previous visible nav items
* 3. remove "hidden" attrubutes to new visible nav items
*/
function updateNavVisibility () {
if (!nav || navAsThumbnails) { return; }
getVisibleNavIndex();
if (visibleNavIndexes !== visibleNavIndexesCached) {
forEachNodeList(navItems, function(el, i) {
if (visibleNavIndexes.indexOf(i) < 0) {
hideElement(el);
} else {
showElement(el);
}
});
// cache visible nav indexes
visibleNavIndexesCached = visibleNavIndexes;
}
}
function info (e) {
return {
container: container,
slideItems: slideItems,
navContainer: navContainer,
navItems: navItems,
controlsContainer: controlsContainer,
hasControls: hasControls,
prevButton: prevButton,
nextButton: nextButton,
items: items,
slideBy: slideBy,
cloneCount: cloneCount,
slideCount: slideCount,
slideCountNew: slideCountNew,
index: index,
indexCached: indexCached,
navCurrentIndex: navCurrentIndex,
navCurrentIndexCached: navCurrentIndexCached,
visibleNavIndexes: visibleNavIndexes,
visibleNavIndexesCached: visibleNavIndexesCached,
sheet: sheet,
event: e || {},
};
}
return {
getInfo: info,
events: events,
goTo: goTo,
play: play,
pause: pause,
isOn: isOn,
updateSliderHeight: updateInnerWrapperHeight,
rebuild: function() {
return tns(options);
},
destroy: function () {
// remove win event listeners
removeEvents(win, {'resize': onResize});
// remove arrowKeys eventlistener
removeEvents(doc, docmentKeydownEvent);
// sheet
sheet.disabled = true;
// cloned items
if (loop) {
for (var j = cloneCount; j--;) {
if (carousel) { slideItems[0].remove(); }
slideItems[slideItems.length - 1].remove();
}
}
// Slide Items
var slideClasses = ['tns-item', slideActiveClass];
if (!carousel) { slideClasses = slideClasses.concat('tns-normal', animateIn); }
for (var i = slideCount; i--;) {
var slide = slideItems[i];
if (slide.id.indexOf(slideId + '-item') >= 0) { slide.id = ''; }
slideClasses.forEach(function(cl) { removeClass(slide, cl); });
}
removeAttrs(slideItems, ['style', 'aria-hidden', 'tabindex']);
slideItems = slideId = slideCount = slideCountNew = cloneCount = null;
// controls
if (controls) {
removeEvents(controlsContainer, controlsEvents);
if (options.controlsContainer) {
removeAttrs(controlsContainer, ['aria-label', 'tabindex']);
removeAttrs(controlsContainer.children, ['aria-controls', 'aria-disabled', 'tabindex']);
}
controlsContainer = prevButton = nextButton = null;
}
// nav
if (nav) {
removeEvents(navContainer, navEvents);
if (options.navContainer) {
removeAttrs(navContainer, ['aria-label']);
removeAttrs(navItems, ['aria-selected', 'aria-controls', 'tabindex']);
}
navContainer = navItems = null;
}
// auto
if (autoplay) {
clearInterval(autoplayTimer);
if (autoplayButton) {
removeEvents(autoplayButton, {'click': toggleAutoplay});
}
removeEvents(container, hoverEvents);
removeEvents(container, visibilityEvent);
if (options.autoplayButton) {
removeAttrs(autoplayButton, ['data-action']);
}
}
// container
container.id = containerIdCached || '';
container.className = container.className.replace(classContainer, '');
removeElementStyles(container);
if (carousel && TRANSITIONEND) {
var eve = {};
eve[TRANSITIONEND] = onTransitionEnd;
removeEvents(container, eve);
}
removeEvents(container, touchEvents);
removeEvents(container, dragEvents);
// outerWrapper
containerParent.insertBefore(container, outerWrapper);
outerWrapper.remove();
outerWrapper = innerWrapper = container =
index = indexCached = items = slideBy = navCurrentIndex = navCurrentIndexCached = hasControls = visibleNavIndexes = visibleNavIndexesCached =
this.getInfo = this.events = this.goTo = this.play = this.pause = this.destroy = null;
this.isOn = isOn = false;
}
};
};
return tns;
})();<|fim▁end|> | |
<|file_name|>issue-25145.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.<|fim▁hole|>struct S;
impl S {
const N: usize = 3;
}
static STUFF: [u8; S::N] = [0; S::N];
fn main() {
assert_eq!(STUFF, [0; 3]);
}<|fim▁end|> |
// run-pass
|
<|file_name|>variantproperty.cpp<|end_file_name|><|fim▁begin|>/**************************************************************************
**
** This file is part of Qt Creator
**<|fim▁hole|>**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "variantproperty.h"
#include "internalproperty.h"
#include "internalvariantproperty.h"
#include "invalidmodelnodeexception.h"
#include "invalidpropertyexception.h"
#include "invalidargumentexception.h"
#include "internalnode_p.h"
#include "model.h"
#include "model_p.h"
namespace QmlDesigner {
VariantProperty::VariantProperty()
{}
VariantProperty::VariantProperty(const VariantProperty &property, AbstractView *view)
: AbstractProperty(property.name(), property.internalNode(), property.model(), view)
{
}
VariantProperty::VariantProperty(const QString &propertyName, const Internal::InternalNodePointer &internalNode, Model* model, AbstractView *view) :
AbstractProperty(propertyName, internalNode, model, view)
{
}
void VariantProperty::setValue(const QVariant &value)
{
Internal::WriteLocker locker(model());
if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
if (value.isNull())
throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, name());
if (internalNode()->hasProperty(name())) { //check if oldValue != value
Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name());
if (internalProperty->isVariantProperty()
&& internalProperty->toVariantProperty()->value() == value
&& dynamicTypeName().isEmpty())
return;
}
if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isVariantProperty())
model()->d->removeProperty(internalNode()->property(name()));
model()->d->setVariantProperty(internalNode(), name(), value);
}
QVariant VariantProperty::value() const
{
if (internalNode()->hasProperty(name())
&& internalNode()->property(name())->isVariantProperty())
return internalNode()->variantProperty(name())->value();
return QVariant();
}
VariantProperty& VariantProperty::operator= (const QVariant &value)
{
setValue(value);
return *this;
}
void VariantProperty::setDynamicTypeNameAndValue(const QString &type, const QVariant &value)
{
Internal::WriteLocker locker(model());
if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
if (type.isEmpty()) {
throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, name());
}
if (internalNode()->hasProperty(name())) { //check if oldValue != value
Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name());
if (internalProperty->isVariantProperty()
&& internalProperty->toVariantProperty()->value() == value
&& internalProperty->toVariantProperty()->dynamicTypeName() == type)
return;
}
if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isVariantProperty())
model()->d->removeProperty(internalNode()->property(name()));
model()->d->setDynamicVariantProperty(internalNode(), name(), type, value);
}
VariantProperty& VariantProperty::operator= (const QPair<QString, QVariant> &typeValuePair)
{
setDynamicTypeNameAndValue(typeValuePair.first, typeValuePair.second);
return *this;
}
QDebug operator<<(QDebug debug, const VariantProperty &VariantProperty)
{
return debug.nospace() << "VariantProperty(" << VariantProperty.name() << ')';
}
QTextStream& operator<<(QTextStream &stream, const VariantProperty &property)
{
stream << "VariantProperty(" << property.name() << ')';
return stream;
}
} // namespace QmlDesigner<|fim▁end|> | ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
** |
<|file_name|>match-bot-fail.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at<|fim▁hole|>// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern:explicit failure
#![allow(unreachable_code)]
#![allow(unused_variable)]
fn foo(s: String) { }
fn main() {
let i =
match Some::<int>(3) { None::<int> => { fail!() } Some::<int>(_) => { fail!() } };
foo(i);
}<|fim▁end|> | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
<|file_name|>element.ts<|end_file_name|><|fim▁begin|>import {
propValues,
isConstructor,
initializeProps,
parseAttributeValue,
ICustomElement,
ConstructableComponent,
FunctionComponent,
PropsDefinition,
} from "./utils";
let currentElement: HTMLElement & ICustomElement;
export function getCurrentElement() {
return currentElement;
}
export function noShadowDOM() {
Object.defineProperty(currentElement, "renderRoot", {
value: currentElement,
});
}
export function createElementType<T>(
BaseElement: typeof HTMLElement,
propDefinition: PropsDefinition<T>
) {
const propKeys = Object.keys(propDefinition) as Array<
keyof PropsDefinition<T>
>;
return class CustomElement extends BaseElement implements ICustomElement {
[prop: string]: any;
__initialized?: boolean;
__released: boolean;
__releaseCallbacks: any[];
__propertyChangedCallbacks: any[];
__updating: { [prop: string]: any };
props: { [prop: string]: any };
static get observedAttributes() {
return propKeys.map((k) => propDefinition[k].attribute);
}
constructor() {
super();
this.__initialized = false;
this.__released = false;
this.__releaseCallbacks = [];
this.__propertyChangedCallbacks = [];
this.__updating = {};
this.props = {};
}
connectedCallback() {
if (this.__initialized) return;
this.__releaseCallbacks = [];
this.__propertyChangedCallbacks = [];
this.__updating = {};
this.props = initializeProps(this as any, propDefinition);
const props = propValues<T>(this.props as PropsDefinition<T>),
ComponentType = this.Component as
| Function
| { new (...args: any[]): any },
outerElement = currentElement;
try {
currentElement = this;
this.__initialized = true;
if (isConstructor(ComponentType))
new (ComponentType as ConstructableComponent<T>)(props, {
element: this as ICustomElement,
});
else
(ComponentType as FunctionComponent<T>)(props, {
element: this as ICustomElement,
});
} finally {
currentElement = outerElement;
}
}
async disconnectedCallback() {
// prevent premature releasing when element is only temporarely removed from DOM
await Promise.resolve();
if (this.isConnected) return;
this.__propertyChangedCallbacks.length = 0;
let callback = null;
while ((callback = this.__releaseCallbacks.pop())) callback(this);
delete this.__initialized;
this.__released = true;
}
attributeChangedCallback(name: string, oldVal: string, newVal: string) {
if (!this.__initialized) return;
if (this.__updating[name]) return;
name = this.lookupProp(name)!;
if (name in propDefinition) {
if (newVal == null && !this[name]) return;
this[name] = propDefinition[name as keyof T].parse
? parseAttributeValue(newVal)
: newVal;
}
}
lookupProp(attrName: string) {
if (!propDefinition) return;
return propKeys.find(
(k) => attrName === k || attrName === propDefinition[k].attribute<|fim▁hole|>
get renderRoot() {
return this.shadowRoot || this.attachShadow({ mode: "open" });
}
addReleaseCallback(fn: () => void) {
this.__releaseCallbacks.push(fn);
}
addPropertyChangedCallback(fn: (name: string, value: any) => void) {
this.__propertyChangedCallbacks.push(fn);
}
};
}<|fim▁end|> | ) as string | undefined;
} |
<|file_name|>pat-ref-enum.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at<|fim▁hole|>//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn matcher(x: Option<isize>) {
match x {
ref Some(i) => {} //~ ERROR expected identifier, found enum pattern
None => {}
}
}
fn main() {}<|fim▁end|> | // http://rust-lang.org/COPYRIGHT. |
<|file_name|>helpers.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use std::env;
use std::str;
use std::sync::Arc;
use rustc_serialize::hex::FromHex;
use env_logger::LogBuilder;
use ServerBuilder;<|fim▁hole|>use util::{Bytes, Address, Mutex, ToPretty};
use devtools::http_client;
const REGISTRAR: &'static str = "8e4e9b13d4b45cb0befc93c3061b1408f67316b2";
const URLHINT: &'static str = "deadbeefcafe0000000000000000000000000000";
const SIGNER_PORT: u16 = 18180;
pub struct FakeRegistrar {
pub calls: Arc<Mutex<Vec<(String, String)>>>,
pub responses: Mutex<Vec<Result<Bytes, String>>>,
}
impl FakeRegistrar {
fn new() -> Self {
FakeRegistrar {
calls: Arc::new(Mutex::new(Vec::new())),
responses: Mutex::new(
vec![
Ok(format!("000000000000000000000000{}", URLHINT).from_hex().unwrap()),
Ok(Vec::new())
]
),
}
}
}
impl ContractClient for FakeRegistrar {
fn registrar(&self) -> Result<Address, String> {
Ok(REGISTRAR.parse().unwrap())
}
fn call(&self, address: Address, data: Bytes) -> Result<Bytes, String> {
self.calls.lock().push((address.to_hex(), data.to_hex()));
self.responses.lock().remove(0)
}
}
fn init_logger() {
// Initialize logger
if let Ok(log) = env::var("RUST_LOG") {
let mut builder = LogBuilder::new();
builder.parse(&log);
builder.init().expect("Logger is initialized only once.");
}
}
pub fn init_server(hosts: Option<Vec<String>>, is_syncing: bool) -> (Server, Arc<FakeRegistrar>) {
init_logger();
let registrar = Arc::new(FakeRegistrar::new());
let mut dapps_path = env::temp_dir();
dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading");
let mut builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar.clone());
builder.with_sync_status(Arc::new(move || is_syncing));
builder.with_signer_address(Some(("127.0.0.1".into(), SIGNER_PORT)));
(
builder.start_unsecured_http(&"127.0.0.1:0".parse().unwrap(), hosts).unwrap(),
registrar,
)
}
pub fn serve_with_auth(user: &str, pass: &str) -> Server {
init_logger();
let registrar = Arc::new(FakeRegistrar::new());
let mut dapps_path = env::temp_dir();
dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading");
let mut builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar);
builder.with_signer_address(Some(("127.0.0.1".into(), SIGNER_PORT)));
builder.start_basic_auth_http(&"127.0.0.1:0".parse().unwrap(), None, user, pass).unwrap()
}
pub fn serve_hosts(hosts: Option<Vec<String>>) -> Server {
init_server(hosts, false).0
}
pub fn serve_with_registrar() -> (Server, Arc<FakeRegistrar>) {
init_server(None, false)
}
pub fn serve_with_registrar_and_sync() -> (Server, Arc<FakeRegistrar>) {
init_server(None, true)
}
pub fn serve() -> Server {
init_server(None, false).0
}
pub fn request(server: Server, request: &str) -> http_client::Response {
http_client::request(server.addr(), request)
}
pub fn assert_security_headers(headers: &[String]) {
http_client::assert_security_headers_present(headers, None)
}
pub fn assert_security_headers_for_embed(headers: &[String]) {
http_client::assert_security_headers_present(headers, Some(SIGNER_PORT))
}<|fim▁end|> | use Server;
use hash_fetch::urlhint::ContractClient; |
<|file_name|>array.js<|end_file_name|><|fim▁begin|>module.exports.sum = function (arr, prop, exp) {
var total = 0
for (var i = 0, _len = arr.length; i < _len; i++) {
var value = arr[i][prop];
<|fim▁hole|> } else {
total += value * 1;
}
}
return total
};<|fim▁end|> | if (exp) {
if (arr[i][exp.field] == exp.value) {
total += value * 1;
}
|
<|file_name|>test_cutlass.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import math
import pytest
import tvm
from tvm import relay
import numpy as np
from tvm.runtime.vm import VirtualMachine
from tvm.relay.op.contrib.cutlass import partition_for_cutlass
from tvm.contrib.cutlass import (
tune_cutlass_kernels,
build_cutlass_kernels,
build_cutlass_kernels_vm,
)
logging.basicConfig(level=logging.INFO)
def has_cublas():
return tvm.get_global_func("tvm.contrib.cublas.matmul", True) != None
def has_cutlass():
return tvm.get_global_func("relay.ext.cutlass", True) != None
def get_ref_rt_mod(mod, params, target="cuda"):
with tvm.transform.PassContext(opt_level=3):
lib = relay.build(mod, target=target, params=params)
dev = tvm.device(target, 0)
rt_mod = tvm.contrib.graph_executor.GraphModule(lib["default"](dev))
return rt_mod, dev
def get_ref_vm(mod, params, target="cuda"):
with tvm.transform.PassContext(opt_level=3):
vm_exec = relay.vm.compile(mod, target=target, params=params)
code, lib = vm_exec.save()
dev = tvm.device(target, 0)
vm_exec = tvm.runtime.vm.Executable.load_exec(code, lib)
return VirtualMachine(vm_exec, dev), dev
def get_output(rt_mod, names, inputs):
for name, inp in zip(names, inputs):
rt_mod.set_input(name, inp)
rt_mod.run()
return rt_mod.get_output(0).asnumpy()
def get_output_vm(vm, names, inputs):
params = dict(zip(names, inputs))
return vm.invoke("main", **params).numpy()
def get_dense_with_shape(data_shape, weight_shape, out_dtype="float16"):
data = relay.var("data", shape=data_shape, dtype="float16")
weight = relay.var("weight", shape=weight_shape, dtype="float16")
return relay.nn.dense(data, weight, out_dtype=out_dtype)
def get_dense(M, N, K, out_dtype="float16"):
return get_dense_with_shape((M, K), (N, K), out_dtype)
def get_dense_bias(M, N, K, out_dtype="float16"):
dense = get_dense(M, N, K, out_dtype=out_dtype)
bias = relay.var("bias", shape=(N,), dtype=out_dtype)
return relay.nn.bias_add(dense, bias)
def get_dense_bias_relu(M, N, K, out_dtype="float16"):
return relay.nn.relu(get_dense_bias(M, N, K, out_dtype=out_dtype))
def get_dense_bias_gelu(M, N, K, out_dtype="float16"):
bias_add = get_dense_bias(M, N, K, out_dtype)
mul = bias_add * relay.const((1.0 / math.sqrt(2.0)), dtype=out_dtype)
if out_dtype == "float16":
erf = relay.cast(relay.op.erf(relay.cast(mul, "float32")), "float16")
else:
erf = relay.op.erf(mul)
mul_half = erf * relay.const(0.5, dtype=out_dtype)
add = mul_half + relay.const(0.5, dtype=out_dtype)
return add * bias_add
def get_batch_matmul_with_shape(x_shape, y_shape, out_dtype="float16"):
x = relay.var("x", shape=x_shape, dtype="float16")
y = relay.var("y", shape=y_shape, dtype="float16")
return relay.nn.batch_matmul(x, y, out_dtype=out_dtype)
def get_batch_matmul(batch, M, N, K, out_dtype="float16"):
return get_batch_matmul_with_shape((batch, M, K), (batch, N, K), out_dtype="float16")
def get_conv2d_nchw(d_shape, w_shape, padding, out_dtype="float16"):
data = relay.var("data", shape=d_shape, dtype="float16")
weight = relay.var("weight", shape=w_shape, dtype="float16")
out_channel = w_shape[0]
return relay.nn.conv2d(
data=data,
weight=weight,
kernel_size=w_shape[2:],
channels=out_channel,
padding=padding,
out_dtype=out_dtype,
)
def get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype="float16"):
conv2d = get_conv2d_nchw(d_shape, w_shape, padding, out_dtype=out_dtype)
bias = relay.var("bias", shape=(w_shape[0],), dtype=out_dtype)
return relay.nn.bias_add(conv2d, bias)
def silu(x):
return x * relay.sigmoid(x)
def hardswish(x, out_dtype="float16"):
return x * (
relay.clip(x + relay.const(3, dtype=out_dtype), a_min=0, a_max=6)
/ relay.const(6, dtype=out_dtype)
)
def get_conv2d_nchw_bias_relu(d_shape, w_shape, padding, out_dtype="float16"):
return relay.nn.relu(get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype=out_dtype))
def get_conv2d_nchw_bias_sigmoid(d_shape, w_shape, padding, out_dtype="float16"):
return relay.sigmoid(get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype=out_dtype))
def get_conv2d_nchw_bias_silu(d_shape, w_shape, padding, out_dtype="float16"):
conv_out = get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype=out_dtype)
return silu(conv_out)
def get_conv2d_nchw_bias_hardswish(d_shape, w_shape, padding, out_dtype="float16"):
conv_out = get_conv2d_nchw_bias(d_shape, w_shape, padding, out_dtype=out_dtype)
return hardswish(conv_out, out_dtype)
def get_conv2d_nchw_bias_residual(d_shape, w_shape, padding, out_dtype="float16"):
data = relay.var("data", shape=d_shape, dtype="float16")
weight = relay.var("weight", shape=w_shape, dtype="float16")
bias = relay.var("bias", shape=(w_shape[0],), dtype=out_dtype)
out_channel = w_shape[0]
conv2d = relay.nn.conv2d(
data=data,
weight=weight,
kernel_size=w_shape[2:],
channels=out_channel,
padding=padding,
out_dtype=out_dtype,
)
bias_add = relay.nn.bias_add(conv2d, bias)
return bias_add, data
def profile_and_build(mod, params, sm, tmp_dir="./tmp", lib_path="compile.so", use_fast_math=False):
mod = partition_for_cutlass(mod)
mod, num_cutlass_partition = tune_cutlass_kernels(
mod, sm, profile_all=False, use_multiprocessing=False, tmp_dir=tmp_dir
)
with tvm.transform.PassContext(opt_level=3):
lib = relay.build(mod, target="cuda", params=params)
lib = build_cutlass_kernels(lib, sm, tmp_dir, lib_path, use_fast_math=use_fast_math)
dev = tvm.device("cuda", 0)
rt_mod = tvm.contrib.graph_executor.GraphModule(lib["default"](dev))
return rt_mod, dev, num_cutlass_partition
def profile_and_build_vm(
mod,
params,
sm,
tmp_dir="./tmp",
lib_path="compile.so",
vmcode_path="vmcode.ro",
use_fast_math=False,
):
mod = partition_for_cutlass(mod)
mod, num_cutlass_partition = tune_cutlass_kernels(mod, sm, tmp_dir=tmp_dir)
with tvm.transform.PassContext(opt_level=3):
vm_exec = relay.vm.compile(mod, target="cuda", params=params)
vm_exec = build_cutlass_kernels_vm(
vm_exec, sm, tmp_dir, lib_path, vmcode_path, use_fast_math=use_fast_math
)
dev = tvm.device("cuda", 0)
return VirtualMachine(vm_exec, dev), dev, num_cutlass_partition
def verify_dense(
func, M, N, K, ref_target="cuda", sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False
):
if not has_cutlass():
return
mod = tvm.IRModule.from_expr(func)
typ = relay.transform.InferType()(mod)["main"].body.checked_type
out_dtype = typ.dtype
use_vm = any(isinstance(s, tvm.tir.Any) for s in typ.shape)
np_data = np.random.uniform(-1, 1, (M, K)).astype("float16")
np_weight = np.random.uniform(-1, 1, (N, K)).astype("float16")
np_bias = np.random.uniform(-1, 1, (N,)).astype(out_dtype)
params = {"weight": np_weight, "bias": np_bias}
if use_vm:
if ref_target == "cuda" and out_dtype == "float16":
# Uncomment "return" below to see the accuracy difference of static vs dynamic TVM native fp16 dense
# The static one can use a tensorcore schedule, but the dynamic one cannot
rt_mod, dev = get_ref_vm(tvm.IRModule.from_expr(get_dense(M, N, K)), params)
num_partition = 1
logging.warning(
"The reference fp16 dense with dynamic shape using fp16 accumulation has accuracy issues."
)
return
else:
rt_mod, dev, num_partition = profile_and_build_vm(mod, params, sm)
rt_mod_ref, dev = get_ref_vm(mod, params, target=ref_target)
x = tvm.nd.array(np_data, device=dev)
out = get_output_vm(rt_mod, ["data"], [x])
ref_out = get_output_vm(rt_mod_ref, ["data"], [x])
else:
rt_mod_ref, dev = get_ref_rt_mod(mod, params, target=ref_target)
rt_mod, dev, num_partition = profile_and_build(mod, params, sm)
x = tvm.nd.array(np_data, device=dev)
out = get_output(rt_mod, ["data"], [x])
ref_out = get_output(rt_mod_ref, ["data"], [x])
assert num_partition > 0
np.testing.assert_allclose(out, ref_out, atol=atol, rtol=rtol)
if run_benchmark:
print("CUTLASS:", rt_mod.benchmark(dev, number=1, repeat=600))
print("TVM with target %s:" % ref_target, rt_mod_ref.benchmark(dev, number=1, repeat=600))
def verify_batch_matmul(
func, batch, M, N, K, ref_target="cuda", sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False
):
if not has_cutlass():
return
mod = tvm.IRModule.from_expr(func)
typ = relay.transform.InferType()(mod)["main"].body.checked_type
use_vm = any(isinstance(s, tvm.tir.Any) for s in typ.shape)
x_np = np.random.uniform(-1, 1, (batch, M, K)).astype("float16")
y_np = np.random.uniform(-1, 1, (batch, N, K)).astype("float16")<|fim▁hole|> assert num_partition > 0
x = tvm.nd.array(x_np, device=dev)
y = tvm.nd.array(y_np, device=dev)
out = get_output_vm(rt_mod, ["x", "y"], [x, y])
ref_out = get_output_vm(rt_mod_ref, ["x", "y"], [x, y])
else:
rt_mod, dev, num_partition = profile_and_build(mod, {}, sm)
rt_mod_ref, dev = get_ref_rt_mod(mod, {})
assert num_partition > 0
x = tvm.nd.array(x_np, device=dev)
y = tvm.nd.array(y_np, device=dev)
out = get_output(rt_mod, ["x", "y"], [x, y])
ref_out = get_output(rt_mod_ref, ["x", "y"], [x, y])
np.testing.assert_allclose(out, ref_out, atol=atol, rtol=rtol)
if run_benchmark:
print("CUTLASS:", rt_mod.benchmark(dev, number=1, repeat=600))
print("TVM Tensorcore (no tuning):", rt_mod_ref.benchmark(dev, number=1, repeat=600))
M = 1820
N = 768
K = 768
def test_dense():
verify_dense(get_dense(M, N, K), M, N, K)
verify_dense(get_dense(M, N, K, out_dtype="float32"), M, N, K)
# Test align1 case
verify_dense(get_dense_bias(M, N + 1, K), M, N + 1, K)
def test_dense_bias():
verify_dense(get_dense_bias(M, N, K), M, N, K)
verify_dense(get_dense_bias(M, N, K, out_dtype="float32"), M, N, K)
def test_dense_bias_relu():
verify_dense(get_dense_bias_relu(M, N, K), M, N, K)
verify_dense(get_dense_bias_relu(M, N, K, out_dtype="float32"), M, N, K)
def test_dense_bias_gelu():
verify_dense(get_dense_bias_gelu(M, N, K), M, N, K, atol=1e-3, rtol=1e-3)
verify_dense(get_dense_bias_gelu(M, N, K, out_dtype="float32"), M, N, K, atol=1e-3, rtol=1e-3)
def test_dense_dynamic():
data_shape = (relay.Any(), K)
weight_shape = (relay.Any(), K)
if has_cublas():
# TVM native fp16 dense (without tensorcore), using fp16 accum, seems to have accuracy issues
# Use cublas as a reference
verify_dense(
get_dense_with_shape(data_shape, weight_shape),
M,
N,
K,
ref_target="cuda -libs=cublas",
)
verify_dense(
get_dense_with_shape(data_shape, weight_shape, out_dtype="float32"),
M,
N,
K,
atol=1e-4,
rtol=1e-4,
)
def test_batch_matmul():
batch = 8
verify_batch_matmul(get_batch_matmul(batch, M, N, K), batch, M, N, K)
verify_batch_matmul(get_batch_matmul(batch, M, N, K, out_dtype="float32"), batch, M, N, K)
if has_cublas():
# Test dynamic shape batch_matmul
# AutoTVM does not seem to support it
x_shape = (relay.Any(), relay.Any(), K)
y_shape = (relay.Any(), relay.Any(), K)
verify_batch_matmul(
get_batch_matmul_with_shape(x_shape, y_shape),
batch,
M,
N,
K,
ref_target="cuda -libs=cublas",
)
def convert_conv2d_layout(mod, desired_layouts):
with tvm.transform.PassContext(opt_level=3):
seq = tvm.transform.Sequential([relay.transform.ConvertLayout(desired_layouts)])
return seq(mod)
def verify_conv2d(
expr_nchw, # can be dynamic batch
expr_ref, # always static batch
d_shape,
w_shape,
sm=80,
atol=1e-5,
rtol=1e-5,
use_cudnn_ref=False,
run_benchmark=False,
use_fast_math=False,
):
if not has_cutlass():
return
mod_nchw = tvm.IRModule.from_expr(expr_nchw)
mod_ref = tvm.IRModule.from_expr(expr_ref)
typ = relay.transform.InferType()(mod_nchw)["main"].body.checked_type
out_dtype = typ.dtype
np_data = np.random.uniform(-1, 1, d_shape).astype("float16")
np_weight = np.random.uniform(-1, 1, w_shape).astype("float16")
np_bias = np.random.uniform(-1, 1, (w_shape[0],)).astype(out_dtype)
params = {"weight": np_weight, "bias": np_bias}
typ = relay.transform.InferType()(mod_nchw)["main"].body.checked_type
use_vm = any(isinstance(s, tvm.tir.Any) for s in typ.shape)
mod_weight_ohwi = convert_conv2d_layout(mod_nchw, {"nn.conv2d": ["NHWC", "OHWI"]})
if use_vm:
rt_mod, _, num_cutlass_partition = profile_and_build_vm(
mod_weight_ohwi, params, sm, use_fast_math=use_fast_math
)
out = get_output_vm(rt_mod, ["data"], [np_data])
else:
rt_mod, _, num_cutlass_partition = profile_and_build(
mod_weight_ohwi, params, sm, use_fast_math=use_fast_math
)
out = get_output(rt_mod, ["data"], [np_data])
assert num_cutlass_partition > 0
if use_cudnn_ref:
rt_mod_ref, dev = get_ref_rt_mod(
convert_conv2d_layout(mod_ref, {"nn.conv2d": ["NHWC", "OHWI"]}),
params,
target="cuda -libs=cudnn",
)
else:
rt_mod_ref, dev = get_ref_rt_mod(
convert_conv2d_layout(mod_ref, {"nn.conv2d": ["NHWC", "HWIO"]}),
params,
target="cuda",
)
ref_out = get_output(rt_mod_ref, ["data"], [np_data])
if run_benchmark:
print("CUTLASS:", rt_mod.benchmark(dev, number=1, repeat=600))
print("TVM Tensorcore (no tuning):", rt_mod_ref.benchmark(dev, number=1, repeat=600))
np.testing.assert_allclose(out, ref_out, atol=atol, rtol=rtol)
def test_conv2d():
padding = (1, 1)
for IC in [3, 16]:
d_shape = (16, IC, 32, 32)
w_shape = (32, IC, 3, 3)
mod_nchw = get_conv2d_nchw(d_shape, w_shape, padding)
verify_conv2d(
mod_nchw,
mod_nchw,
d_shape,
w_shape,
sm=80,
atol=1e-5,
rtol=1e-5,
use_cudnn_ref=(IC == 3), # The autotvm kernel has an accuracy issue with IC == 3 case
run_benchmark=False,
)
d_shape = (16, 16, 32, 32)
w_shape = (32, 16, 3, 3)
padding = (1, 1)
dyn_batch_shape = (relay.Any(),) + d_shape[1:]
mod_nchw = get_conv2d_nchw(d_shape, w_shape, padding)
mod_dyn = get_conv2d_nchw(dyn_batch_shape, w_shape, padding)
verify_conv2d(
mod_dyn, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False
)
def test_conv2d_fusion():
d_shape = (16, 16, 32, 32)
w_shape = (32, 16, 3, 3)
padding = (1, 1)
mod_nchw = get_conv2d_nchw_bias(d_shape, w_shape, padding)
verify_conv2d(
mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False
)
mod_nchw = get_conv2d_nchw_bias_relu(d_shape, w_shape, padding)
verify_conv2d(
mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False
)
mod_nchw = get_conv2d_nchw_bias_sigmoid(d_shape, w_shape, padding, out_dtype="float16")
verify_conv2d(
mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False
)
verify_conv2d(
mod_nchw,
mod_nchw,
d_shape,
w_shape,
sm=80,
atol=1e-3,
rtol=1e-3,
run_benchmark=False,
use_fast_math=True,
)
mod_nchw = get_conv2d_nchw_bias_sigmoid(d_shape, w_shape, padding, out_dtype="float32")
verify_conv2d(
mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False
)
mod_nchw = get_conv2d_nchw_bias_silu(d_shape, w_shape, padding, out_dtype="float32")
verify_conv2d(
mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False
)
mod_nchw = get_conv2d_nchw_bias_hardswish(d_shape, w_shape, padding, out_dtype="float16")
verify_conv2d(
mod_nchw, mod_nchw, d_shape, w_shape, sm=80, atol=1e-5, rtol=1e-5, run_benchmark=False
)
def test_conv2d_residual_block():
d_shape = (16, 16, 32, 32)
w_shape = (16, 16, 3, 3)
padding = (1, 1)
bias_add, residual_input = get_conv2d_nchw_bias_residual(d_shape, w_shape, padding)
for func, tol in [
(relay.nn.relu(bias_add + residual_input), 1e-5),
(relay.nn.relu(bias_add) + residual_input, 1e-5),
(relay.sigmoid(bias_add) * residual_input, 1e-5),
(relay.nn.relu(silu(bias_add) * residual_input), 1e-5),
# HardSwish requires higher tolerance since vectoring the residual block epilogue
# in cutlass.
# TODO(masahi): Invesitigate this issue
(relay.nn.relu(hardswish(bias_add) + residual_input), 1e-3),
]:
verify_conv2d(func, func, d_shape, w_shape, sm=80, atol=tol, rtol=tol, run_benchmark=False)
if __name__ == "__main__":
pytest.main([__file__])<|fim▁end|> |
if use_vm:
rt_mod, dev, num_partition = profile_and_build_vm(mod, {}, sm)
rt_mod_ref, dev = get_ref_vm(mod, {}, target=ref_target) |
<|file_name|>send_message.rs<|end_file_name|><|fim▁begin|>use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.<|fim▁hole|>#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[serde(skip_serializing_if = "Option::is_none")]
parse_mode: Option<ParseMode>,
#[serde(skip_serializing_if = "Not::not")]
disable_web_page_preview: bool,
#[serde(skip_serializing_if = "Not::not")]
disable_notification: bool,
#[serde(skip_serializing_if = "Option::is_none")]
reply_to_message_id: Option<MessageId>,
#[serde(skip_serializing_if = "Option::is_none")]
reply_markup: Option<ReplyMarkup>,
}
impl<'c, 's> Request for SendMessage<'s> {
type Type = JsonRequestType<Self>;
type Response = JsonIdResponse<MessageOrChannelPost>;
fn serialize(&self) -> Result<HttpRequest, Error> {
Self::Type::serialize(RequestUrl::method("sendMessage"), self)
}
}
impl<'s> SendMessage<'s> {
pub fn new<C, T>(chat: C, text: T) -> Self
where
C: ToChatRef,
T: Into<Cow<'s, str>>,
{
SendMessage {
chat_id: chat.to_chat_ref(),
text: text.into(),
parse_mode: None,
disable_web_page_preview: false,
disable_notification: false,
reply_to_message_id: None,
reply_markup: None,
}
}
pub fn parse_mode(&mut self, parse_mode: ParseMode) -> &mut Self {
self.parse_mode = Some(parse_mode);
self
}
pub fn disable_preview(&mut self) -> &mut Self {
self.disable_web_page_preview = true;
self
}
pub fn disable_notification(&mut self) -> &mut Self {
self.disable_notification = true;
self
}
pub fn reply_to<R>(&mut self, to: R) -> &mut Self
where
R: ToMessageId,
{
self.reply_to_message_id = Some(to.to_message_id());
self
}
pub fn reply_markup<R>(&mut self, reply_markup: R) -> &mut Self
where
R: Into<ReplyMarkup>,
{
self.reply_markup = Some(reply_markup.into());
self
}
}
/// Send text message.
pub trait CanSendMessage {
fn text<'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<C> CanSendMessage for C
where
C: ToChatRef,
{
fn text<'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
{
SendMessage::new(self, text)
}
}
/// Reply with text message.
pub trait CanReplySendMessage {
fn text_reply<'c, 's, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<M> CanReplySendMessage for M
where
M: ToMessageId + ToSourceChat,
{
fn text_reply<'c, 's, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
{
let mut rq = self.to_source_chat().text(text);
rq.reply_to(self.to_message_id());
rq
}
}<|fim▁end|> | |
<|file_name|>generate_new_native_tests.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
from shutil import copyfile
import glob
import os
sql = './sql'
expected = './expected'
NEW_FILES = ['native_features']
for file in NEW_FILES:
filelist = glob.glob(f"{sql}/*{file}.sql")
for path in filelist:
try:
os.remove(path)
except:
print("Error while deleting file : ", path)
filelist = glob.glob(f"{expected}/*{file}.out")
for path in filelist:
try:
os.remove(path)
except:
print("Error while deleting file : ", path)
files = {}
for filename in os.listdir(sql):
split_filename = filename.split("_", 1)
number = int(split_filename[0])
files[number] = split_filename[1]
max_file_num = max(files.keys())
def construct_filename(n, name):
return f"{str(n).zfill(2)}_{name}"
contents = """
SET client_min_messages = warning;
DO $$<|fim▁hole|>ELSE
CREATE EXTENSION pglogical;
END IF;
END$$;
CREATE EXTENSION pgl_ddl_deploy;
CREATE OR REPLACE FUNCTION pgl_ddl_deploy.override() RETURNS BOOLEAN AS $BODY$
BEGIN
RETURN TRUE;
END;
$BODY$
LANGUAGE plpgsql IMMUTABLE;
INSERT INTO pgl_ddl_deploy.queue (queued_at,role,pubnames,message_type,message)
VALUES (now(),current_role,'{mock}'::TEXT[],pgl_ddl_deploy.queue_ddl_message_type(),'CREATE TABLE nativerox(id int)');
INSERT INTO pgl_ddl_deploy.queue (queued_at,role,pubnames,message_type,message)
VALUES (now(),current_role,'{mock}'::TEXT[],pgl_ddl_deploy.queue_ddl_message_type(),'ALTER TABLE nativerox ADD COLUMN bar text;');
INSERT INTO pgl_ddl_deploy.queue (queued_at,role,pubnames,message_type,message)
VALUES (now(),current_role,'{mock}'::TEXT[],pgl_ddl_deploy.queue_ddl_message_type(),$$SELECT pgl_ddl_deploy.notify_subscription_refresh('mock', true);$$);
DO $$
DECLARE v_ct INT;
BEGIN
IF current_setting('server_version_num')::INT >= 100000 THEN
SELECT COUNT(1) INTO v_ct FROM information_schema.columns WHERE table_name = 'nativerox';
RAISE LOG 'v_ct: %', v_ct;
IF v_ct != 2 THEN
RAISE EXCEPTION 'Count does not match expected: v_ct: %', v_ct;
END IF;
SELECT COUNT(1) INTO v_ct FROM pgl_ddl_deploy.subscriber_logs;
IF v_ct != 1 THEN
RAISE EXCEPTION 'Count does not match expected: v_ct: %', v_ct;
END IF;
PERFORM pgl_ddl_deploy.retry_all_subscriber_logs();
SELECT (SELECT COUNT(1) FROM pgl_ddl_deploy.subscriber_logs WHERE NOT succeeded) +
(SELECT COUNT(1) FROM pgl_ddl_deploy.subscriber_logs WHERE error_message ~* 'No subscription to publication mock exists') INTO v_ct;
IF v_ct != 3 THEN
RAISE EXCEPTION 'Count does not match expected: v_ct: %', v_ct;
END IF;
ELSE
SELECT COUNT(1) INTO v_ct FROM pgl_ddl_deploy.subscriber_logs;
IF v_ct != 0 THEN
RAISE EXCEPTION 'Count does not match expected: v_ct: %', v_ct;
END IF;
END IF;
END$$;
"""
fname = construct_filename(max_file_num + 1, 'native_features')
with open(f"{sql}/{fname}.sql", "w") as newfile:
newfile.write(contents)
copyfile(f"{sql}/{fname}.sql", f"{expected}/{fname}.out")<|fim▁end|> | BEGIN
IF current_setting('server_version_num')::INT >= 100000 THEN
SET session_replication_role TO replica; |
<|file_name|>floating_k_statisctic.cpp<|end_file_name|><|fim▁begin|>#include <iostream>
#include <vector>
#include <iterator>
#include <queue>
#include <functional>
#include <algorithm>
using std::cin;
using std::cout;
using std::vector;
using std::swap;
using std::less;
using std::endl;
using std::cerr;
struct TNode
{
int key;
int index[2];
TNode()
{
index[0] = -1;
index[1] = -1;
}
explicit TNode(int _key)
{
key = _key;
index[0] = -1;
index[1] = -1;
}
bool operator>(const TNode& tn) const
{
return this->key > tn.key;
}
bool operator<(const TNode& tn) const
{
return this->key < tn.key;
}
bool inMinHeap()
{
return index[0] != -1;
}
bool inMaxHeap()
{
return index[1] != -1;
}
};
typedef TNode* tp;
TNode a;
template<class BDIT, int ind = 0>
class IndexGetter
{
public:
IndexGetter()
{}
int& operator()(BDIT it)
{<|fim▁hole|> int index = ind;
if (0 <= ind && ind <= 1) {
index = ind;
}
return it->index[index];
}
private:
};
TNode invalid;
template <class T
, class IndexGetter
, class Compare
= std::less <typename std::iterator_traits <T>::value_type> >
class IndexHeap
{
public:
IndexHeap()
{}
bool empty()
{
return heap.empty();
}
void remove(T it)
{
if (!empty()) {
int tind = ig(it);
if (tind == size() - 1) {
ig(heap.back()) = -1;
heap.pop_back();
return;
}
swp(tind, size() - 1);
ig(heap.back()) = -1;
heap.pop_back();
if (!empty()) {
update_heap(heap[tind]);
}
}
}
size_t size()
{
return heap.size();
}
T top()
{
if (!empty())
return heap[0];
return &invalid;
}
T pop()
{
if (!empty()) {
T ret = top();
remove(ret);
return ret;
}
return &invalid;
}
void insert(T elem)
{
if (elem == &invalid)
return;
if (ig(elem) != -1)
return;
ig(elem) = size();
heap.push_back(elem);
update_heap(elem);
}
void swp(int ftind, int sdind)
{
swap(ig(heap[ftind]), ig(heap[sdind]));
swap(heap[ftind], heap[sdind]);
}
void print()
{
std::cerr << "****************" << endl;
for (int i = 0; i < size(); ++i) {
std::cerr << "heap[" << i << "] : " << heap[i]->key << ", "
<< ig(heap[i]) << std::endl;
}
std::cerr << "****************" << endl << endl;
}
void update_heap(T it)
{
while (shiftUp(it)) {}
while (shiftDown(it)) {}
}
bool shiftUp(T it)
{
int tind, pind;
tind = ig(it);
pind = (tind - 1) / 2;
// cerr << tind << " : " << pind << endl;
if (comp(*(heap[tind]), *(heap[pind]))) {
swp(tind, pind);
return true;
}
return false;
}
bool shiftDown(T it)
{
int leftChild, rightChild, largestChild;
int index = ig(it);
leftChild = index * 2 + 1;
rightChild = index * 2 + 2;
largestChild = index;
if (leftChild < size()
&& comp(*(heap[leftChild]), *(heap[largestChild]))) {
largestChild = leftChild;
}
if (rightChild < size()
&& comp(*(heap[rightChild]), *(heap[largestChild]))) {
largestChild = rightChild;
}
if (largestChild != index) {
swp(index, largestChild);
return true;
}
return false;
}
private:
IndexGetter ig;
vector<T> heap;
Compare comp;
};
int main(int argc, char *argv[])
{
int elemNum, comNum, statNum;
invalid.key = -1;
vector<TNode> nodes;
IndexHeap<tp, IndexGetter<tp, 0>, std::less<TNode> > min_heap;
IndexHeap<tp, IndexGetter<tp, 1>, std::greater<TNode> > max_heap;
cin >> elemNum >> comNum >> statNum;
for (int i = 0; i < elemNum; ++i) {
int telem;
cin >> telem;
nodes.push_back(TNode(telem));
}
int left = 0, right = 0;
max_heap.insert(&nodes[0]);
for (int ind = 0; ind < comNum; ++ind) {
char com;
cin >> com;
if (com == 'R') {
++right;
min_heap.insert(&nodes[right]);
}
/*
* if (ind == 3) {
* cerr << "debug: " << endl;
* cerr << left << " " << right << endl;
* cerr << nodes[left].index[1] << endl;
* max_heap.print();
* }
*/
if (com == 'L') {
if (nodes[left].inMaxHeap()) {
max_heap.remove(&nodes[left]);
} else {
min_heap.remove(&nodes[left]);
}
++left;
}
// cerr << max_heap.size() << " : " << min_heap.size() << endl;
while (max_heap.size() < statNum && !min_heap.empty()) {
tp it = min_heap.pop();
// cerr << it->key << endl;
max_heap.insert(it);
}
while (!max_heap.empty()
&& !min_heap.empty()
&& *max_heap.top() > *min_heap.top()) {
min_heap.insert(max_heap.pop());
max_heap.insert(min_heap.pop());
}
if (max_heap.size() < statNum) {
cout << -1 << endl;
} else {
cout << max_heap.top()->key << endl;
}
}
return 0;
}<|fim▁end|> | |
<|file_name|>type.js<|end_file_name|><|fim▁begin|>declare var a: number;
var b: typeof a = "...";<|fim▁hole|>
type T = number;
var x:T = "...";
// what about recursive unions?<|fim▁end|> | var c: typeof a = "..."; |
<|file_name|>Quiz.py<|end_file_name|><|fim▁begin|>print("In Python, what do you call a 'box' used to store data?")
answer = input()
if answer == "variable":
print(" :) ")
else:
print(" :( ")
print("Thank you for playing!")
<|fim▁hole|>a - text
b - variable
c - a shoe box
''')
answer = input().lower()
if answer == "a":
print(" Nope - text is a type of data :( ")
elif answer == "b":
print(" Correct!! :) ")
elif answer == "c":
print(" Don't be silly! :( ")
else:
print(" You didn't choose a, b or c :( ")<|fim▁end|> | print('''
Q1 - In Python, what do you call a 'box' used to store data?
|
<|file_name|>module_class.ts<|end_file_name|><|fim▁begin|>export class Klass {
static x: number = 4;
constructor(public n: number) {}
<|fim▁hole|> return false;
}
}<|fim▁end|> | foo(): boolean { |
<|file_name|>GetRenderedTaskFormCmd.java<|end_file_name|><|fim▁begin|>/* 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.
*/
package org.flowable.engine.impl.cmd;
import java.io.Serializable;
import org.flowable.engine.common.api.FlowableException;
import org.flowable.engine.common.api.FlowableIllegalArgumentException;
import org.flowable.engine.common.api.FlowableObjectNotFoundException;
import org.flowable.engine.common.impl.interceptor.Command;
import org.flowable.engine.common.impl.interceptor.CommandContext;
import org.flowable.engine.form.TaskFormData;
import org.flowable.engine.impl.form.FormEngine;
import org.flowable.engine.impl.form.TaskFormHandler;
import org.flowable.engine.impl.persistence.entity.TaskEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.FormHandlerUtil;
import org.flowable.engine.task.Task;
/**
* @author Tom Baeyens
* @author Joram Barrez
*/
public class GetRenderedTaskFormCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String taskId;
protected String formEngineName;
public GetRenderedTaskFormCmd(String taskId, String formEngineName) {
this.taskId = taskId;
this.formEngineName = formEngineName;
}<|fim▁hole|> throw new FlowableIllegalArgumentException("Task id should not be null");
}
TaskEntity task = CommandContextUtil.getTaskEntityManager(commandContext).findById(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("Task '" + taskId + "' not found", Task.class);
}
TaskFormHandler taskFormHandler = FormHandlerUtil.getTaskFormHandlder(task);
if (taskFormHandler != null) {
FormEngine formEngine = CommandContextUtil.getProcessEngineConfiguration(commandContext).getFormEngines().get(formEngineName);
if (formEngine == null) {
throw new FlowableException("No formEngine '" + formEngineName + "' defined process engine configuration");
}
TaskFormData taskForm = taskFormHandler.createTaskForm(task);
return formEngine.renderTaskForm(taskForm);
}
return null;
}
}<|fim▁end|> |
public Object execute(CommandContext commandContext) {
if (taskId == null) { |
<|file_name|>SampleWSBareSEI.java<|end_file_name|><|fim▁begin|>/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as<|fim▁hole|> * This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.ws.jaxws.jbws1702;
import org.jboss.test.ws.jaxws.jbws1702.types.ResponseWrapperB;
import org.jboss.test.ws.jaxws.jbws1702.types.ResponseWrapperC;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
/**
* @author [email protected]
*/
@WebService
@SOAPBinding(
style = SOAPBinding.Style.DOCUMENT,
use = SOAPBinding.Use.LITERAL,
parameterStyle = SOAPBinding.ParameterStyle.BARE
)
public interface SampleWSBareSEI
{
@WebMethod(action="getClassCAsClassB")
ResponseWrapperB getClassCAsClassB();
@WebMethod(action="getClassC")
ResponseWrapperC getClassC();
}<|fim▁end|> | * published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
* |
<|file_name|>consv.rs<|end_file_name|><|fim▁begin|>/// This module contains the following sub-modules:
/// k
/// ks
/// ksl
/// This module contains functions that work under the assumption that lattice
/// momentum is conserved.
pub mod k {
use fnv::FnvHashMap;
use num_complex::Complex;
use blochfunc::{BlochFunc, BlochFuncSet};
use common::*;
use ops;
fn bloch_states<'a>(nx: Dim, ny: Dim, kx: K, ky: K) -> BlochFuncSet {
let n = nx * ny;
let mut sieve = vec![true; 2_usize.pow(n.raw_int())];
let mut bfuncs: Vec<BlochFunc> = Vec::new();
let phase = |i, j| {
let r = 1.;
let ang1 = 2. * PI * (i * kx.raw_int()) as f64 / nx.raw_int() as f64;
let ang2 = 2. * PI * (j * ky.raw_int()) as f64 / ny.raw_int() as f64;
Complex::from_polar(&r, &(ang1 + ang2))
};
for dec in 0..2_usize.pow(n.raw_int()) {
if sieve[dec] {
// if the corresponding entry of dec in "sieve" is not false,
// we find all translations of dec and put them in a BlochFunc
// then mark all corresponding entries in "sieve" as false.
// "decs" is a hashtable that holds vectors whose entries
// correspond to Bloch function constituent configurations which
// are mapped to single decimals that represent the leading states.
let mut decs: FnvHashMap<BinaryBasis, Complex<f64>> =
FnvHashMap::default();
// "new_dec" represents the configuration we are currently iterating
// over.
let mut new_dec = BinaryBasis(dec as u64);
for j in 0..ny.raw_int() {
for i in 0..nx.raw_int() {
sieve[new_dec.raw_int() as usize] = false;
let new_p = match decs.get(&new_dec) {
Some(&p) => p + phase(i, j),
None => phase(i, j)
};
decs.insert(new_dec, new_p);
new_dec = translate_x(new_dec, nx, ny);
}
new_dec = translate_y(new_dec, nx, ny);
}
let lead = BinaryBasis(dec as u64);
let norm = decs.values()
.into_iter()
.map(|&x| x.norm_sqr())
.sum::<f64>()
.sqrt();
if norm > 1e-8 {
let mut bfunc = BlochFunc { lead, decs, norm };
bfuncs.push(bfunc);
}
}
}
let mut table = BlochFuncSet::create(nx, ny, bfuncs);
table.sort();
table
}
pub fn h_ss_z(nx: Dim, ny: Dim, kx: K, ky: K, l: I)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky);
let sites = interacting_sites(nx, ny, l);
ops::ss_z(&sites, &bfuncs)
}
pub fn h_ss_xy(nx: Dim, ny: Dim, kx: K, ky: K, l: I)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky);
let sites = interacting_sites(nx, ny, l);
ops::ss_xy(&sites, &bfuncs)
}
pub fn h_ss_ppmm(nx: Dim, ny: Dim, kx: K, ky: K, l: I)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky);
let sites = interacting_sites(nx, ny, l);
ops::ss_ppmm(&sites, &bfuncs)
}
pub fn h_ss_pmz(nx: Dim, ny: Dim, kx: K, ky: K, l: I)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky);
let sites = interacting_sites(nx, ny, l);
ops::ss_pmz(&sites, &bfuncs)
}
pub fn h_sss_chi(nx: Dim, ny: Dim, kx: K, ky: K) -> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky);
let sites = triangular_vert_sites(nx, ny);
ops::sss_chi(&sites, &bfuncs)
}
pub fn ss_z(nx: Dim, ny: Dim, kx: K, ky: K, l: I) -> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky);
let sites = all_sites(nx, ny, l);
ops::ss_z(&sites, &bfuncs)
}
pub fn ss_xy(nx: Dim, ny: Dim, kx: K, ky: K, l: I)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky);
let sites = all_sites(nx, ny, l);
ops::ss_xy(&sites, &bfuncs)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bloch_states_test() {
let nx = Dim(4);
let ny = Dim(4);
let kx = K(1);
let ky = K(3);
let bfuncs = bloch_states(nx, ny, kx, ky);
assert_eq!(bfuncs.nonzero, 4080);
}
}
}
/// This module contains functions that work under the assumption that lattice
/// momentum and total Sz are conserved.
pub mod ks {
use fnv::FnvHashMap;
use num_complex::Complex;
use blochfunc::{BlochFunc, BlochFuncSet};
use common::*;
use ops;
fn bloch_states<'a>(nx: Dim, ny: Dim, kx: K, ky: K, nup: u32) -> BlochFuncSet {
let n = nx * ny;
let sz_basis_states = sz_basis(n, nup);
let mut szdec_to_ind: FnvHashMap<BinaryBasis, usize> = FnvHashMap::default();
let mut ind_to_szdec: FnvHashMap<usize, BinaryBasis> = FnvHashMap::default();
for (i, &bs) in sz_basis_states.iter().enumerate() {
ind_to_szdec.insert(i, bs);
szdec_to_ind.insert(bs, i);
}
let mut sieve = vec![true; sz_basis_states.len()];
let mut bfuncs: Vec<BlochFunc> = Vec::new();
let phase = |i, j| {
let r = 1.;
let ang1 = 2. * PI * (i * kx.raw_int()) as f64 / nx.raw_int() as f64;
let ang2 = 2. * PI * (j * ky.raw_int()) as f64 / ny.raw_int() as f64;
Complex::from_polar(&r, &(ang1 + ang2))
};
for ind in 0..sieve.len() {
if sieve[ind] {
// if the corresponding entry of dec in "sieve" is not false,
// we find all translations of dec and put them in a BlochFunc
// then mark all corresponding entries in "sieve" as false.
// "decs" is a hashtable that holds vectors whose entries<|fim▁hole|> FnvHashMap::default();
// "new_dec" represents the configuration we are currently iterating
// over.
let dec = *ind_to_szdec.get(&ind).unwrap();
let mut new_dec = dec;
let mut new_ind = ind;
for j in 0..ny.raw_int() {
for i in 0..nx.raw_int() {
sieve[new_ind as usize] = false;
let new_p = match decs.get(&new_dec) {
Some(&p) => p + phase(i, j),
None => phase(i, j)
};
decs.insert(new_dec, new_p);
new_dec = translate_x(new_dec, nx, ny);
new_ind = *szdec_to_ind.get(&new_dec).unwrap() as usize;
}
new_dec = translate_y(new_dec, nx, ny);
}
let lead = dec;
let norm = decs.values()
.into_iter()
.map(|&x| x.norm_sqr())
.sum::<f64>()
.sqrt();
if norm > 1e-8 {
let mut bfunc = BlochFunc { lead, decs, norm };
bfuncs.push(bfunc);
}
}
}
let mut table = BlochFuncSet::create(nx, ny, bfuncs);
table.sort();
table
}
pub fn h_ss_z(nx: Dim, ny: Dim, kx: K, ky: K, nup: u32, l: I)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky, nup);
let sites = interacting_sites(nx, ny, l);
ops::ss_z(&sites, &bfuncs)
}
pub fn h_ss_xy(nx: Dim, ny: Dim, kx: K, ky: K, nup: u32, l: I)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky, nup);
let sites = interacting_sites(nx, ny, l);
ops::ss_xy(&sites, &bfuncs)
}
pub fn h_sss_chi(nx: Dim, ny: Dim, kx: K, ky: K, nup: u32)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky, nup);
let sites = triangular_vert_sites(nx, ny);
ops::sss_chi(&sites, &bfuncs)
}
pub fn ss_z(nx: Dim, ny: Dim, kx: K, ky: K, nup: u32, l: I)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky, nup);
let sites = all_sites(nx, ny, l);
ops::ss_z(&sites, &bfuncs)
}
pub fn ss_xy(nx: Dim, ny: Dim, kx: K, ky: K, nup: u32, l: I)
-> CoordMatrix<CComplex<f64>> {
let bfuncs = bloch_states(nx, ny, kx, ky, nup);
let sites = all_sites(nx, ny, l);
ops::ss_xy(&sites, &bfuncs)
}
}<|fim▁end|> | // correspond to Bloch function constituent configurations which
// are mapped to single decimals that represent the leading states.
let mut decs: FnvHashMap<BinaryBasis, Complex<f64>> = |
<|file_name|>TableCellClassListTest.ts<|end_file_name|><|fim▁begin|>import { Assertions, Chain, GeneralSteps, Logger, Pipeline } from '@ephox/agar';<|fim▁hole|>import ModernTheme from 'tinymce/themes/modern/Theme';
UnitTest.asynctest('browser.tinymce.plugins.table.TableCellClassListTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
ModernTheme();
TablePlugin();
const tableHtml = '<table><tbody><tr><td>x</td></tr></tbody></table>';
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyApis = TinyApis(editor);
const tinyUi = TinyUi(editor);
Pipeline.async({}, [
Logger.t('no class input without setting', GeneralSteps.sequence([
tinyApis.sFocus,
tinyApis.sSetContent(tableHtml),
tinyApis.sSetSelection([0, 0, 0, 0, 0], 0, [0, 0, 0, 0, 0], 1),
tinyUi.sClickOnMenu('click table menu', 'span:contains("Table")'),
tinyUi.sClickOnUi('click table menu', 'div[role="menu"] span:contains("Cell")'),
tinyUi.sClickOnUi('click table menu', 'div[role="menu"] span:contains("Cell properties")'),
Chain.asStep({}, [
tinyUi.cWaitForPopup('wait for popup', 'div[aria-label="Cell properties"][role="dialog"]'),
Chain.op(function (x) {
Assertions.assertPresence(
'assert presence of col and row input',
{
'label:contains("Class")': 0
}, x);
})
]),
tinyUi.sClickOnUi('close popup', 'button > span:contains("Cancel")'),
tinyApis.sSetContent('')
])),
Logger.t('class input with setting', GeneralSteps.sequence([
tinyApis.sFocus,
tinyApis.sSetSetting('table_cell_class_list', [{ title: 'test', value: 'test' }]),
tinyApis.sSetContent(tableHtml),
tinyApis.sSetSelection([0, 0, 0, 0, 0], 0, [0, 0, 0, 0, 0], 1),
tinyUi.sClickOnMenu('click table menu', 'span:contains("Table")'),
tinyUi.sClickOnUi('click table menu', 'div[role="menu"] span:contains("Cell")'),
tinyUi.sClickOnUi('click table menu', 'div[role="menu"] span:contains("Cell properties")'),
tinyUi.sWaitForPopup('wait for popup', 'div[aria-label="Cell properties"][role="dialog"]'),
tinyUi.sClickOnUi('click class input', 'button > span:contains("test")'),
tinyUi.sClickOnUi('click class input', 'div[role="menuitem"] > span:contains("test")'),
tinyUi.sClickOnUi('close popup', 'button > span:contains("Ok")'),
tinyApis.sAssertContentPresence({ 'td.test': 1 })
]))
], onSuccess, onFailure);
}, {
plugins: 'table',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});<|fim▁end|> | import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import TablePlugin from 'tinymce/plugins/table/Plugin'; |
<|file_name|>teamqueue.py<|end_file_name|><|fim▁begin|>################################################################
# LiveQ - An interactive volunteering computing batch system
# Copyright (C) 2013 Ioannis Charalampidis
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
################################################################
import sys
import time
import logging
import jobmanager.io.agents as agents
import jobmanager.io.jobs as jobs
from jobmanager.config import Config
from peewee import fn
from liveq.models import Agent, AgentGroup, Jobs
# Setup logger
logger = logging.getLogger("teamqueue")
<|fim▁hole|> particular team
"""
pass<|fim▁end|> | def processTeamQueue():
"""
This should be called periodically to check and schedule jobs pending for the |
<|file_name|>align.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright © 2010 University of Zürich
# Author: Rico Sennrich <[email protected]>
# For licensing information, see LICENSE
from __future__ import division,print_function,unicode_literals
import sys
import time
import math
from operator import itemgetter
from bleualign.gale_church import align_texts
import bleualign.score as bleu
from bleualign.utils import evaluate, finalevaluation
import io
import platform
if sys.version_info >= (2,6) and platform.system() != "Windows":
import multiprocessing
multiprocessing_enabled = 1
else:
multiprocessing_enabled = 0
def collect_article(src,srctotarget,target,targettosrc,options):
EOF = False
while not EOF:
all_texts = []
all_translations = []
for text,translations in [(src,srctotarget),(target,targettosrc)]:
textlist = []
translist = [[] for i in translations]
for line in text:
if line.rstrip() == options['end_of_article_marker']:
for f in translations:
f.readline()
break
for i,f in enumerate(translations):
translist[i].append(f.readline().rstrip())
if options['factored']:
rawline = ' '.join(word.split('|')[0] for word in line.split())
textlist.append((rawline,line.rstrip()))
else:
textlist.append(line.rstrip())
else:
EOF = True
all_texts.append(textlist)
all_translations.append(translist)
sourcelist, targetlist = all_texts
translist1, translist2 = all_translations
yield sourcelist,targetlist,translist1,translist2
#takes a queue as argument and puts all articles to be aligned in it.
#best call this in a separate process because we limit the queue size for memory reasons
def tasks_producer(tasks,num_tasks,data,num_processes):
for i,task in enumerate(collect_article(*data)):
num_tasks.value += 1
tasks.put((i,task),True)
#poison pills
for i in range(num_processes):
tasks.put((None,None))
num_tasks.value -= 1 # only if this point is reached, process finishes when all tasks are done.
class Aligner:
default_options = {
#source and target files needed by Aligner
#they can be filenames, arrays of strings or io objects.
'srcfile':None, 'targetfile': None,
#the format of srcfile and targetfile
#False for normal text, True for 'text | other information', seprating by '|'
'factored': False,
#translations of srcfile and targetfile, not influenced by 'factored'
#they can be filenames, arrays of strings or io objects, too.
'srctotarget': [], 'targettosrc': [],
#run aligner without srctotarget and targettosrc
'no_translation_override':False,
#only consider target sentences for bleu-based alignment that are among top N alternatives for a given source sentence
'maxalternatives':3,
#bleu scoring algorithm works with 4-grams by default. We got better results when using 2-grams (since there are less 0 scores then)
'bleu_ngrams' : 2,
#BLEU is word-based by default, but character-level BLEU is more suitable for some languages, e.g. continuous script languages without space.
#it is a good idea to also increase bleu_ngrams when switching to character-level BLEU
'bleu_charlevel' : False,
#consider N to 1 (and 1 to N) alignment in gapfilling (complexity is size_of_gap*value^2, so don't turn this unnecessarily high)
#also, there are potential precision issues.
#set to 1 to disable bleu-based 1 to N alignments and let gale & church fill the gaps
'Nto1' : 2,
#do only gale-church, no bleualign
'galechurch': None,
#gapfillheuristics: what to do with sentences that aren't aligned one-to-one by the first BLEU pass, nor have a 1 to N alignment validated by BLEU?
#possible members are: bleu1to1, galechurch
#what they do is commented in the source code
'gapfillheuristics' : ["bleu1to1","galechurch"],
#defines string that identifies hard boundaries (articles, chapters etc.)
#string needs to be on a line of its own (see examples in eval directory)
#must be reliable (article i in the source text needs to correspond to article i in the target text)
'end_of_article_marker' : ".EOA",
#filtering out bad alignments by bleuscore
#filter has sentences or articles type
#filterthreshold means choosing the best X% of alignments (according to BLEU)
#bleuthreshold requires a sentence pair to achieve a certain BLEU score to be included in the output
#set filterlang True, whose when you want to filter alignemts which src is similar to target than translation
'filter': None, 'filterthreshold': 90, 'bleuthreshold': 0, 'filterlang': None,
#it will print unalignemt pair(zero to one or one to zero pair)
'printempty': False,
#setting output for four output filenames, it will add suffixes automatically
#or passing filenames or io object for them in respectly.
#if not passing anything or assigning None, they will use StringIO to save results.
'output': None,
'output-src': None, 'output-target': None,
'output-src-bad': None, 'output-target-bad': None,
#the best alignment of corpus for evaluation
'eval': None,
#defines amount of debugging output.
'verbosity': 1, 'log_to':sys.stdout,
#number of parallel processes
'num_processes': 1
}
def __init__(self,options):
self.src, self.target = None,None
self.srctotarget, self.targettosrc= [],[]
self.out1, self.out2, self.out_bad1, self.out_bad2 = None,None,None,None
self.sources_out,self.targets_out = [],[]
self.finalbleu = []
self.bleualign = []
self.close_src, self.close_target = False, False
self.close_srctotarget, self.close_targettosrc = [], []
self.close_out1, self.close_out2 = False, False
self.close_out_bad1, self.close_out_bad2 = False, False
self.options = self.default_options.copy()
self.options.update(options)
if not self.options['srcfile']:
raise ValueError('Source file not specified.')
if not self.options['targetfile']:
raise ValueError('Target file not specified.')
if not self.options['srctotarget'] and not self.options['targettosrc']\
and not self.options['no_translation_override']:
raise ValueError("ERROR: no translation available: BLEU scores can be computed between the source and target text, but this is not the intended usage of Bleualign and may result in poor performance! If you're *really* sure that this is what you want, set 'galechurch' for the options.")
self.src, self.close_src = \
self._inputObjectFromParameter(self.options['srcfile'])
self.target, self.close_target = \
self._inputObjectFromParameter(self.options['targetfile'])
for f in self.options['srctotarget']:
obj, close_obj = \
self._inputObjectFromParameter(f)
self.srctotarget.append(obj)
self.close_srctotarget.append(close_obj)
for f in self.options['targettosrc']:
obj, close_obj = \
self._inputObjectFromParameter(f)
self.targettosrc.append(obj)
self.close_targettosrc.append(close_obj)
self.out1,self.close_out1=self._outputObjectFromParameter(
self.options['output-src'], self.options['output'], '-s')
self.out2,self.close_out2=self._outputObjectFromParameter(
self.options['output-target'], self.options['output'], '-t')
if self.options['filter']:
self.out_bad1,self.close_out_bad1=self._outputObjectFromParameter(
self.options['output-src-bad'], self.options['output'], '-bad-s')
self.out_bad2,self.close_out_bad2=self._outputObjectFromParameter(
self.options['output-target-bad'], self.options['output'], '-bad-t')
# for passing by string array
def _stringArray2stringIo(self, stringArray):
return io.StringIO('\n'.join([line.rstrip() for line in stringArray]))
# parameter may be filename, IO object or string array
def _inputObjectFromParameter(self, parameter):
try:
inputObject = io.open(parameter, 'r', encoding='UTF-8')
close_object = True
except:
if isinstance(parameter, io.TextIOBase):
inputObject = parameter
else:
inputObject = self._stringArray2stringIo(parameter)
close_object = False
return inputObject, close_object
# parameter may be filename, IO object or string array
def _outputObjectFromParameter(self, parameter, filename, suffix):
close_object = False
if parameter:
try:
outputObject = io.open(parameter, 'w', encoding='UTF-8')
close_object = True
except:
outputObject = parameter
elif filename:
outputObject = io.open(filename + suffix, 'w', encoding='UTF-8')
else:
outputObject = io.StringIO()
return outputObject, close_object
#takes care of multiprocessing; calls process() function for each article
def mainloop(self):
results = {}
if multiprocessing_enabled and self.options['num_processes'] > 1:
tasks = multiprocessing.Queue(self.options['num_processes']+1)
manager = multiprocessing.Manager()
scores = manager.dict()
num_tasks = manager.Value('i',1)
scorers = [AlignMultiprocessed(tasks,self.options,scores,self.log) for i in range(self.options['num_processes'])]
for p in scorers:
p.start()
#this function produces the alignment tasks for the consumers in scorers
producer = multiprocessing.Process(target=tasks_producer,args=(tasks,num_tasks,(self.src,self.srctotarget,self.target,self.targettosrc,self.options),self.options['num_processes']))
producer.start()
i = 0
#get results from processed and call printout function
while i < num_tasks.value:
#wait till result #i is populated
while True:
try:
data,multialign,bleualign,scoredict = scores[i]
break
except:
time.sleep(0.1)
for p in scorers:
if p.exitcode == 1:
for p in scorers:
p.terminate()
producer.terminate()
raise RuntimeError("Multiprocessing error")
continue
(sourcelist,targetlist,translist1,translist2) = data
self.scoredict = scoredict
self.multialign = multialign
self.bleualign = bleualign
#normal case: translation from source to target exists
if translist1:
translist = translist1[0]
#no translation provided. we copy source sentences for further processing
else:
if self.options['factored']:
translist = [item[0] for item in sourcelist]
else:
translist = sourcelist
self.printout(sourcelist, translist, targetlist)
if self.options['eval']:
self.log('evaluation ' + str(i))
results[i] = evaluate(self.options,self.multialign,self.options['eval'][i],self.log)
del(scores[i])
i += 1
else:
for i,(sourcelist,targetlist,translist1,translist2) in enumerate(collect_article(self.src,self.srctotarget,self.target,self.targettosrc,self.options)):
self.log('reading in article ' + str(i) + ': ',1)
self.multialign = self.process(sourcelist,targetlist,translist1,translist2)
if translist1:
translist = translist1[0]
else:
if self.options['factored']:
translist = [item[0] for item in sourcelist]
else:
translist = sourcelist
self.printout(sourcelist, translist, targetlist)
if self.options['eval']:
self.log('evaluation ' + str(i))
results[i] = evaluate(self.options, self.multialign,self.options['eval'][i],self.log)
if self.out1:
self.out1.flush()
if self.out2:
self.out2.flush()
if self.options['eval']:
finalevaluation(results, self.log)
if self.options['filter']:
self.write_filtered()
self.close_file_streams()
return self.out1,self.out2
#results of alignment or good aligment if filtering
def results(self):
return self.out1,self.out2
#bad aligment for filtering. Otherwise, None
def results_bad(self):
return self.out_bad1,self.out_bad2
#Start different alignment runs depending on which and how many translations are sent to program; intersect results.
def process(self,sourcelist,targetlist,translist1,translist2):
multialign = []
phase1 = []
phase2 = []
#do nothing if last line in file is .EOA or file is empty.
if not targetlist or not sourcelist:
self.log('WARNING: article is empty. Skipping.',0)
return []
self.log('processing',1)
if self.options['factored']:
raw_sourcelist = [item[0] for item in sourcelist]
raw_targetlist = [item[0] for item in targetlist]
else:
raw_sourcelist = sourcelist
raw_targetlist = targetlist
for i,translist in enumerate(translist1):
self.log("computing alignment between srctotarget (file " + str(i) + ") and target text",1)
phase1.append(self.align(translist, raw_targetlist))
for i,translist in enumerate(translist2):
self.log("computing alignment between targettosrc (file " + str(i) + ") and source text",1)
phase2.append(self.align(translist, raw_sourcelist))
if not (translist1 or translist2):
if self.options['no_translation_override'] or self.options['galechurch']:
phase1 = [self.align(raw_sourcelist, raw_targetlist)]
else:
self.log("ERROR: no translation available", 1)
if multiprocessing_enabled and self.options['num_processes'] > 1:
sys.exit(1)
else:
raise RuntimeError("ERROR: no translation available")
if len(phase1) > 1:
self.log("intersecting all srctotarget alignments",1)
phase1 = sorted(set(phase1[0]).intersection(*[set(x) for x in phase1[1:]]))
elif phase1:
phase1 = phase1[0]
if len(phase2) > 1:
self.log("intersecting all targettosrc alignments",1)
phase2 = sorted(set(phase2[0]).intersection(*[set(x) for x in phase2[1:]]))
elif phase2:
phase2 = phase2[0]
if phase1 and phase2:
self.log("intersecting both directions",1)
phase3 = []
phase2mirror = [(j,k) for ((k,j),t) in phase2]
for pair,t in phase1:
if pair in phase2mirror:
phase3.append((pair,'INTERSECT: ' + t + ' - ' + phase2[phase2mirror.index(pair)][1]))
multialign = phase3
elif phase1:
multialign = phase1
elif phase2:
multialign = [((j,k),t) for ((k,j),t) in phase2]
return multialign
#Compute alignment for one article and one automatic translation.
def align(self, translist, targetlist):
if self.options["galechurch"]:
self.multialign,self.bleualign,self.scoredict = [],[],{}
translist = [item for item in enumerate(translist)]
targetlist = [item for item in enumerate(targetlist)]
churchaligns = self.gale_church(translist,targetlist)
for src,target in churchaligns:
self.addtoAlignments((src,target),'GALECHURCH')
return self.multialign
else:
self.log('Evaluating sentences with bleu',1)
self.scoredict = self.eval_sents(translist,targetlist)
self.log('finished',1)
self.log('searching for longest path of good alignments',1)
self.pathfinder(translist, targetlist)
self.log('finished',1)
self.log(time.asctime(),2)
self.log('filling gaps',1)
self.gapfinder(translist, targetlist)
self.log('finished',1)
self.log(time.asctime(),2)
return self.multialign
#use this if you want to implement your own similarity score
def eval_sents_dummy(self,translist,targetlist):
scoredict = {}
for testID,testSent in enumerate(translist):
scores = []
for refID,refSent in enumerate(targetlist):
score = 100-abs(len(testSent)-len(refSent)) #replace this with your own similarity score
if score > 0:
scores.append((score,refID,score))
scoredict[testID] = sorted(scores,key=itemgetter(0),reverse=True)[:self.options['maxalternatives']]
return scoredict
# given list of test sentences and list of reference sentences, calculate bleu scores
#if you want to replace bleu with your own similarity measure, use eval_sents_dummy
def eval_sents(self,translist,targetlist):
scoredict = {}
cooked_test = {}
cooked_test2 = {}
ngrams = self.options['bleu_ngrams']
charlevel = self.options['bleu_charlevel']
cooktarget_cache = {}
cooktarget = []
for idx, item in enumerate(targetlist):
if charlevel:
item = tuple(item)
if item in cooktarget_cache:
cooktarget.append((idx, cooktarget_cache[item]))
else:
cooked = (idx, bleu.cook_ref_set(item, ngrams))
cooktarget.append(cooked)
cooktarget_cache[item] = cooked[1]
for testID,testSent in enumerate(translist):
if charlevel:
testSent = tuple(testSent)
#copied over from bleu.py to minimize redundancy
test_normalized = bleu.normalize(testSent)
cooked_test["testlen"] = len(test_normalized)
cooked_test["guess"] = [max(len(test_normalized)-k+1,0) for k in range(1,self.options['bleu_ngrams']+1)]
counts = bleu.count_ngrams(test_normalized, self.options['bleu_ngrams'])
#separate by n-gram length. if we have no matching bigrams, we don't have to compare unigrams
ngrams_sorted = dict([(x,set()) for x in range(self.options['bleu_ngrams'])])
for ngram in counts:
ngrams_sorted[len(ngram)-1].add(ngram)
scorelist = []
scorelist_cache = {}
for (refID,(reflen, refmaxcounts, refset)) in cooktarget:
if refset in scorelist_cache:
if scorelist_cache[refset] is not None:
m, c = scorelist_cache[refset]
scorelist.append((m, refID, c))
continue
ngrams_filtered = ngrams_sorted[self.options['bleu_ngrams']-1].intersection(refset)
if ngrams_filtered:
cooked_test["reflen"] = reflen
cooked_test['correct'] = [0]*self.options['bleu_ngrams']
for ngram in ngrams_filtered:
cooked_test["correct"][self.options['bleu_ngrams']-1] += min(refmaxcounts[ngram], counts[ngram])
for order in range(self.options['bleu_ngrams']-1):
for ngram in ngrams_sorted[order].intersection(refset):
cooked_test["correct"][order] += min(refmaxcounts[ngram], counts[ngram])
#copied over from bleu.py to minimize redundancy
logbleu = 0.0
for k in range(self.options['bleu_ngrams']):
logbleu += math.log(cooked_test['correct'][k])-math.log(cooked_test['guess'][k])
logbleu /= self.options['bleu_ngrams']
logbleu += min(0,1-float(cooked_test['reflen'])/cooked_test['testlen'])
score = math.exp(logbleu)
if score > 0:
#calculate bleu score in reverse direction
cooked_test2["guess"] = [max(cooked_test['reflen']-k+1,0) for k in range(1,self.options['bleu_ngrams']+1)]
logbleu = 0.0
for k in range(self.options['bleu_ngrams']):
logbleu += math.log(cooked_test['correct'][k])-math.log(cooked_test2['guess'][k])
logbleu /= self.options['bleu_ngrams']
logbleu += min(0,1-float(cooked_test['testlen'])/cooked_test['reflen'])
score2 = math.exp(logbleu)
meanscore = (2*score*score2)/(score+score2)
scorelist.append((meanscore,refID,cooked_test['correct']))
scorelist_cache[refset] = (meanscore, cooked_test['correct'])
else:
scorelist_cache[refset] = None
else:
scorelist_cache[refset] = None
scoredict[testID] = sorted(scorelist,key=itemgetter(0),reverse=True)[:self.options['maxalternatives']]
return scoredict
#follow the backpointers in score matrix to extract best path of 1-to-1 alignments
def extract_best_path(self,pointers):
i = len(pointers)-1
j = len(pointers[0])-1
pointer = ''
best_path = []
while i >= 0 and j >= 0:
pointer = pointers[i][j]
if pointer == '^':
i -= 1
elif pointer == '<':
j -= 1
elif pointer == 'match':
best_path.append((i,j))
i -= 1
j -= 1
best_path.reverse()
return best_path
#dynamic programming search for best path of alignments (maximal score)
def pathfinder(self, translist, targetlist):
# add an extra row/column to the matrix and start filling it from 1,1 (to avoid exceptions for first row/column)
matrix = [[0 for column in range(len(targetlist)+1)] for row in range(len(translist)+1)]
pointers = [['' for column in range(len(targetlist))] for row in range(len(translist))]
for i in range(len(translist)):
alignments = dict([(target, score) for (score, target, correct) in self.scoredict[i]])
for j in range(len(targetlist)):
best_score = matrix[i][j+1]
best_pointer = '^'
score = matrix[i+1][j]
if score > best_score:
best_score = score
best_pointer = '<'
if j in alignments:
score = alignments[j] + matrix[i][j]
if score > best_score:
best_score = score
best_pointer = 'match'
matrix[i+1][j+1] = best_score
pointers[i][j] = best_pointer
self.bleualign = self.extract_best_path(pointers)
#find unaligned sentences and create work packets for gapfiller()
#gapfiller() takes two sentence pairs and all unaligned sentences in between as arguments; gapfinder() extracts these.
def gapfinder(self, translist, targetlist):
self.multialign = []
#find gaps: lastpair is considered pre-gap, pair is post-gap
lastpair = ((),())
src, target = None, None
for src,target in self.bleualign:
oldsrc, oldtarget = lastpair
#in first iteration, gap will start at 0
if not oldsrc:
oldsrc = (-1,)
if not oldtarget:
oldtarget = (-1,)
#identify gap sizes
sourcegap = list(range(oldsrc[-1]+1,src))
targetgap = list(range(oldtarget[-1]+1,target))
if targetgap or sourcegap:
lastpair = self.gapfiller(sourcegap, targetgap, lastpair, ((src,),(target,)), translist, targetlist)
else:
self.addtoAlignments(lastpair)
lastpair = ((src,),(target,))
#if self.bleualign is empty, gap will start at 0
if src is None:
src = -1
if target is None:
target = -1
#search for gap after last alignment pair
sourcegap = list(range(src+1, len(translist)))
targetgap = list(range(target+1, len(targetlist)))
if targetgap or sourcegap:
lastpair = self.gapfiller(sourcegap, targetgap, lastpair, ((),()), translist, targetlist)
self.addtoAlignments(lastpair)
#apply heuristics to align all sentences that remain unaligned after finding best path of 1-to-1 alignments
#heuristics include bleu-based 1-to-n alignment and length-based alignment
def gapfiller(self, sourcegap, targetgap, pregap, postgap, translist, targetlist):
evalsrc = []
evaltarget = []
#compile list of sentences in gap that will be considered for BLEU comparison
if self.options['Nto1'] > 1 or "bleu1to1" in self.options['gapfillheuristics']:
#concatenate all sentences in pregap alignment pair
tmpstr = ' '.join([translist[i] for i in pregap[0]])
evalsrc.append((pregap[0],tmpstr))
#concatenate all sentences in pregap alignment pair
tmpstr = ' '.join([targetlist[i] for i in pregap[1]])
evaltarget.append((pregap[1],tmpstr))
#search will be pruned to this window
if "bleu1to1" in self.options['gapfillheuristics']:
window = 10 + self.options['Nto1']
else:
window = self.options['Nto1']
for src in [j for i,j in enumerate(sourcegap) if (i < window or len(sourcegap)-i <= window)]:
Sent = translist[src]
evalsrc.append(((src,),Sent))
for target in [j for i,j in enumerate(targetgap) if (i < window or len(targetgap)-i <= window)]:
Sent = targetlist[target]
evaltarget.append(((target,),Sent))
#concatenate all sentences in postgap alignment pair
tmpstr = ' '.join([translist[i] for i in postgap[0]])
evalsrc.append((postgap[0],tmpstr))
#concatenate all sentences in postgap alignment pair
tmpstr = ' '.join([targetlist[i] for i in postgap[1]])
evaltarget.append((postgap[1],tmpstr))
nSrc = {}
for n in range(2,self.options['Nto1']+1):
nSrc[n] = self.createNSents(evalsrc,n)
for n in range(2,self.options['Nto1']+1):
evalsrc += nSrc[n]
nTar = {}
for n in range(2,self.options['Nto1']+1):
nTar[n] = self.createNSents(evaltarget,n)
for n in range(2,self.options['Nto1']+1):
evaltarget += nTar[n]
evalsrc_raw = [item[1] for item in evalsrc]
evaltarget_raw = [item[1] for item in evaltarget]
scoredict_raw = self.eval_sents(evalsrc_raw,evaltarget_raw)
scoredict = {}
for src,value in list(scoredict_raw.items()):
src = evalsrc[src][0]
if value:
newlist = []
for item in value:
score,target,score2 = item
target = evaltarget[target][0]
newlist.append((score,target,score2))
scoredict[src] = newlist
else:
scoredict[src] = []
while sourcegap or targetgap:
pregapsrc,pregaptarget = pregap
postgapsrc,postgaptarget = postgap
if sourcegap and self.options['Nto1'] > 1:
#try if concatenating source sentences together improves bleu score (beginning of gap)
if pregapsrc:
oldscore,oldtarget,oldcorrect = scoredict[pregapsrc][0]
combinedID = tuple(list(pregapsrc)+[sourcegap[0]])
if combinedID in scoredict:
newscore,newtarget,newcorrect = scoredict[combinedID][0]
if newscore > oldscore and newcorrect > oldcorrect and newtarget == pregaptarget:
#print('\nsource side: ' + str(combinedID) + ' better than ' + str(pregapsrc))
pregap = (combinedID,pregaptarget)
sourcegap.pop(0)
continue
#try if concatenating source sentences together improves bleu score (end of gap)
if postgapsrc:
oldscore,oldtarget,oldcorrect = scoredict[postgapsrc][0]
combinedID = tuple([sourcegap[-1]] + list(postgapsrc))
if combinedID in scoredict:
newscore,newtarget, newcorrect = scoredict[combinedID][0]
if newscore > oldscore and newcorrect > oldcorrect and newtarget == postgaptarget:
#print('\nsource side: ' + str(combinedID) + ' better than ' + str(postgapsrc))
postgap = (combinedID,postgaptarget)
sourcegap.pop()
continue
if targetgap and self.options['Nto1'] > 1:
#try if concatenating target sentences together improves bleu score (beginning of gap)
if pregapsrc:
newscore,newtarget,newcorrect = scoredict[pregapsrc][0]
if newtarget != pregaptarget and newtarget != postgaptarget:
#print('\ntarget side: ' + str(newtarget) + ' better than ' + str(pregaptarget))
pregap = (pregapsrc,newtarget)
for i in newtarget:
if i in targetgap:
del(targetgap[targetgap.index(i)])
continue
#try if concatenating target sentences together improves bleu score (end of gap)
if postgapsrc:
newscore,newtarget,newcorrect = scoredict[postgapsrc][0]
if newtarget != postgaptarget and newtarget != pregaptarget:
#print('\ntarget side: ' + str(newtarget) + ' better than ' + str(postgaptarget))
postgap = (postgapsrc,newtarget)
for i in newtarget:
if i in targetgap:
del(targetgap[targetgap.index(i)])
continue
#concatenation didn't help, and we still have possible one-to-one alignments
if sourcegap and targetgap:
#align first two sentences if BLEU validates this
if "bleu1to1" in self.options['gapfillheuristics']:
try:
besttarget = scoredict[(sourcegap[0],)][0][1]
except:
besttarget = 0
if besttarget == (targetgap[0],):
self.addtoAlignments(pregap)
#print('\none-to-one: ' + str((sourcegap[0],)) + ' to' + str((targetgap[0],)))
pregap = ((sourcegap[0],),besttarget)
del(sourcegap[0])
del(targetgap[0])
continue
#Alternative approach: use Gale & Church.
if "galechurch" in self.options['gapfillheuristics'] and (max(len(targetgap),len(sourcegap))<4 or max(len(targetgap),len(sourcegap))/min(len(targetgap),len(sourcegap)) < 2):
tempsrcgap = []
for src in sourcegap:
tempsrcgap.append((src,translist[src]))
temptargetgap = []
for target in targetgap:
temptargetgap.append((target,targetlist[target]))
churchaligns = self.gale_church(tempsrcgap,temptargetgap)
for src,target in churchaligns:
self.addtoAlignments((src,target),'GALECHURCH')
break
#no valid gapfiller left. break loop and ignore remaining gap
break
break
if not pregap in [i[0] for i in self.multialign]:
self.addtoAlignments(pregap)
return postgap
#Take list of (ID,Sentence) tuples for two language pairs and calculate Church & Gale alignment
#Then transform it into this program's alignment format
def gale_church(self,tempsrcgap,temptargetgap):
#get sentence lengths in characters
srclengths = [[len(i[1].strip()) for i in tempsrcgap]]
targetlengths = [[len(i[1].strip()) for i in temptargetgap]]
#call gale & church algorithm
pairs = sorted(list((align_texts(srclengths, targetlengths)[0])), key=itemgetter(0))
idict = {}
jdict = {}
newpairs = []
#store 1-to-n alignments in single pairs of tuples (instead of using multiple pairs of ints)
for i,j in pairs:
if i in idict and j in jdict:
done = 0
for iold1, jold1 in newpairs:
if done:
break
if i in iold1:
for iold2, jold2 in newpairs:
if done:
break
if j in jold2:
if not (iold1,jold1) == (iold2,jold2):
del(newpairs[newpairs.index((iold1,jold1))])
del(newpairs[newpairs.index((iold2,jold2))])
inew = tuple(sorted(list(iold1)+list(iold2)))
jnew = tuple(sorted(list(jold1)+list(jold2)))
newpairs.append((inew,jnew))
done = 1
break
elif i in idict:
for iold, jold in newpairs:
if i in iold:
jnew = tuple(sorted(list(jold)+[j]))
newpairs[newpairs.index((iold,jold))] = (iold,jnew)
jdict[j] = 0
break
elif j in jdict:
for iold, jold in newpairs:
if j in jold:
inew = tuple(sorted(list(iold)+[i]))
newpairs[newpairs.index((iold,jold))] = (inew,jold)
idict[i] = 0
break
else:
idict[i] = 0
jdict[j] = 0
newpairs.append(((i,),(j,)))
#Go from Church & Gale's numbering to our IDs
outpairs = []
for i,j in newpairs:
srcID = []
targetID = []
for src in i:
srcID.append(tempsrcgap[src][0])
for target in j:
targetID.append(temptargetgap[target][0])
#print('\nChurch & Gale: ' + str(tuple(srcID)) + ' to ' + str(tuple(targetID)))
outpairs.append((tuple(srcID),tuple(targetID)))
return outpairs
#get a list of (ID,Sentence) tuples and generate bi- or tri-sentence tuples
def createNSents(self,l,n=2):
out = []
for i in range(len(l)-n+1):
IDs = tuple([k for sublist in l[i:i+n] for k in sublist[0]])
Sents = " ".join([k[1] for k in l[i:i+n]])
out.append((IDs,Sents))
return out
def addtoAlignments(self,pair,aligntype=None):
if not (pair[0] and pair[1]):
return
if aligntype:
self.multialign.append((pair,aligntype))
else:
src,target = pair
if len(src) == 1 and len(target) == 1 and (src[0],target[0]) in self.bleualign:
self.multialign.append((pair,"BLEU"))
else:
self.multialign.append((pair,"GAPFILLER"))
def print_alignment_statistics(self, source_len, target_len):
multialignsrccount = sum([len(i[0][0]) for i in self.multialign])
multialigntargetcount = sum([len(i[0][1]) for i in self.multialign])
self.log("Results of BLEU 1-to-1 alignment",2)
if self.options['verbosity'] >= 2:
bleualignsrc = list(map(itemgetter(0),self.bleualign))
for sourceid in range(source_len):
if sourceid in bleualignsrc:
self.log('\033[92m' + str(sourceid) + ": "
+ str(self.bleualign[bleualignsrc.index(sourceid)][1]) + '\033[1;m')
else:
bestcand = self.scoredict.get(sourceid,[])
if bestcand:
bestcand = bestcand[0][1]
self.log('\033[1;31m'+str(sourceid) + ": unaligned. best cand "
+ str(bestcand)+'\033[1;m')
if source_len and target_len:
self.log("\n" + str(len(self.bleualign)) + ' out of ' + str(source_len) + ' source sentences aligned by BLEU ' + str(100*len(self.bleualign)/float(source_len)) + '%',2)
self.log("after gap filling, " + str(multialignsrccount) + ' out of '+ str(source_len) + ' source sentences aligned ' + str(100*multialignsrccount/float(source_len)) + '%',2)
self.log("after gap filling, " + str(multialigntargetcount) + ' out of '+ str(target_len) + ' target sentences aligned ' + str(100*multialigntargetcount/float(target_len)) + '%',2)
#print out some debugging info, and print output to file
def printout(self, sourcelist, translist, targetlist):
self.print_alignment_statistics(len(sourcelist), len(targetlist))
sources = []
translations = []
targets = []
sources_factored = []
targets_factored = []
if self.options['factored']:
sources_output = sources_factored
targets_output = targets_factored
else:
sources_output = sources
targets_output = targets
self.multialign = sorted(self.multialign,key=itemgetter(0))
sentscores = {}
lastsrc,lasttarget = 0,0
for j,(src,target) in enumerate([i[0] for i in self.multialign]):
self.log("alignment: {0} - {1}".format(",".join(map(str,src)), ",".join(map(str,target))),2)
if self.options['printempty']:
if src[0] != lastsrc + 1:
sources.extend([sourcelist[ID] for ID in range(lastsrc+1,src[0])])
targets.extend(['' for ID in range(lastsrc+1,src[0])])
translations.extend(['' for ID in range(lastsrc+1,src[0])])
if target[0] != lasttarget + 1:
sources.extend(['' for ID in range(lasttarget+1,target[0])])
targets.extend([targetlist[ID] for ID in range(lasttarget+1,target[0])])
translations.extend(['' for ID in range(lasttarget+1,target[0])])
lastsrc = src[-1]
lasttarget = target[-1]
translations.append(' '.join([translist[ID] for ID in src]))
if self.options['factored']:
sources.append(' '.join([sourcelist[ID][0] for ID in src]))
targets.append(' '.join([targetlist[ID][0] for ID in target]))
sources_factored.append(' '.join([sourcelist[ID][1] for ID in src]))
targets_factored.append(' '.join([targetlist[ID][1] for ID in target]))
else:
sources.append(' '.join([sourcelist[ID] for ID in src]))
targets.append(' '.join([targetlist[ID] for ID in target]))
if self.options['filter'] == 'sentences':
self.check_sentence_pair(j, sources[-1], translations[-1], targets[-1], sources_output[-1], targets_output[-1], sentscores)
if self.options['filter'] == 'sentences':
self.filter_sentence_pairs(sentscores, sources_output, targets_output)
if self.options['filter'] == 'articles':
self.filter_article_pairs(sources, translations, targets, sources_output, targets_output)
self.log("\nfinished with article",1)
self.log("\n====================\n",1)
if self.out1 and self.out2 and not self.options['filter']:
if self.options['factored']:
self.out1.write('\n'.join(sources_factored) + '\n')
self.out2.write('\n'.join(targets_factored) + '\n')
else:
self.out1.write('\n'.join(sources) + '\n')
self.out2.write('\n'.join(targets) + '\n')
#get BLEU score of sentence pair (for filtering)
def check_sentence_pair(self, j, src, trans, target, source_out, target_out, sentscores):
sentscore = self.score_article([trans],[target])
sentscore2 = self.score_article([src],[target])
if sentscore2 > sentscore and self.options['filterlang']:
self.out_bad1.write(source_out + '\n')
self.out_bad2.write(target_out + '\n')
else:
if sentscore > 0:
sentscorex = self.score_article([target],[trans])
newsentscore = (2*sentscore*sentscorex)/(sentscore+sentscorex)
else:
newsentscore = 0
sentscores[j]=newsentscore
# get BLEU score for article pair
def score_article(self,test,ref):
refs = [bleu.cook_refs([refSent],self.options['bleu_ngrams']) for refSent in ref]
testcook = []
for i,line in enumerate(test):
testcook.append(bleu.cook_test(line,refs[i],self.options['bleu_ngrams']))
score = bleu.score_cooked(testcook,self.options['bleu_ngrams'])
return score
# store BLEU score for each sentence pair (used for filtering at the very end)
def filter_sentence_pairs(self, sentscores, sources_output, targets_output):
before = len(self.sources_out)
for j,(src,target) in enumerate([i[0] for i in self.multialign]):
if j in sentscores: # false if sentence pair has been filtered out by language filter
confidence = sentscores[j]
self.finalbleu.append((confidence,sentscores.get(j),before,before+1))
before += 1
self.sources_out.append(sources_output[j])
self.targets_out.append(targets_output[j])
# store BLEU score for each article pair (used for filtering at the very end)
def filter_article_pairs(self, sources, translations, targets, sources_output, targets_output):
articlescore = self.score_article(translations,targets)
articlescore2 = self.score_article(sources,targets)
self.log('\nBLEU score for article: ' + str(articlescore) + ' / ' + str(articlescore2),1)
if articlescore2 > articlescore and self.options['filterlang']:
if self.options['factored']:
sources,targets = sources_factored,targets_factored
for i,line in enumerate(sources):
self.out_bad1.write(line + '\n')
self.out_bad2.write(targets[i] + '\n')
else:
articlescorex = self.score_article(targets,translations)
if articlescore > 0:
articlescore = (articlescore*articlescorex*2)/(articlescore+articlescorex)
before = len(self.sources_out)
after = before + len(self.multialign)
self.finalbleu.append((articlescore,articlescore2,before,after))
self.sources_out += sources_output
self.targets_out += targets_output
#filter bad sentence pairs / article pairs
def write_filtered(self):
self.finalbleu = sorted(self.finalbleu,key=itemgetter(0),reverse=True)
self.log(self.finalbleu,2)
totallength=0
totalscore=0
for (articlescore,articlescore2,before,after) in self.finalbleu:
length = after-before
totallength += length
totalscore += articlescore*length
if totallength != 0:
averagescore = totalscore/totallength
self.log("The average BLEU score is: " + str(averagescore),1)
goodlength = totallength*self.options['filterthreshold']/float(100)
totallength = 0
bad_percentiles = []
for i,(articlescore,articlescore2,before,after) in enumerate(self.finalbleu):
length = after-before
totallength += length
if totallength > goodlength:
bad_percentiles = self.finalbleu[i+1:]
self.log("\nDiscarding the following " + self.options['filter'] + " based on relative BLEU\n",2)
self.log(bad_percentiles,2)
if self.options['verbosity'] >= 3:
for score,score2,start,end in bad_percentiles:
for i in range(start,end):
self.log(score,3)<|fim▁hole|> self.log('-----------------',3)
break
stopwrite = set([i[2] for i in bad_percentiles])
resumewrite = set([i[3] for i in bad_percentiles])
stopped = 0
#absolute BLEU threshold
if self.options['bleuthreshold']:
bad_sentences = []
for i,(articlescore,articlescore2,before,after) in enumerate(self.finalbleu):
if articlescore < self.options['bleuthreshold']:
bad_sentences.append((articlescore,articlescore2,before,after))
stopwrite.add(before)
resumewrite.add(after)
self.log("\nDiscarding the following " + self.options['filter'] + " based on absolute BLEU\n",2)
self.log(bad_sentences,2)
if self.options['verbosity'] >= 3:
for score,score2,start,end in bad_sentences:
for i in range(start,end):
self.log(score,3)
self.log(self.sources_out[i],3)
self.log(self.targets_out[i],3)
self.log('-----------------',3)
if self.out1 and self.out2 and self.out_bad1 and self.out_bad2:
for i,line in enumerate(self.sources_out):
if i in resumewrite:
stopped = 0
if i in stopwrite:
stopped = 1
if stopped:
self.out_bad1.write(line + '\n')
self.out_bad2.write(self.targets_out[i] + '\n')
else:
self.out1.write(line + '\n')
self.out2.write(self.targets_out[i] + '\n')
#close all files opened by __init__
def close_file_streams(self):
if self.close_src:
self.src.close()
if self.close_target:
self.target.close()
if self.close_out1:
self.out1.close()
if self.close_out2:
self.out2.close()
if self.close_out_bad1:
self.out_bad1.close()
if self.close_out_bad2:
self.out_bad2.close()
for should_be_closed,output_stream\
in zip(self.close_srctotarget,self.srctotarget):
if should_be_closed:
output_stream.close()
for should_be_closed,output_stream\
in zip(self.close_targettosrc,self.targettosrc):
if should_be_closed:
output_stream.close()
def log(self, msg, level = 1, end='\n'):
if level <= self.options['verbosity']:
print(msg, end=end, file = self.options['log_to'])
#Allows parallelizing of alignment
if multiprocessing_enabled:
class AlignMultiprocessed(multiprocessing.Process,Aligner):
def __init__(self,tasks,options,scores,log):
multiprocessing.Process.__init__(self)
self.options = options
self.tasks = tasks
self.scores = scores
self.log = log
self.bleualign = []
self.scoredict = None
def run(self):
i,data = self.tasks.get()
while i != None:
self.log('reading in article ' + str(i) + ': ',1)
sourcelist,targetlist,translist1,translist2 = data
self.multialign = self.process(sourcelist,targetlist,translist1,translist2)
self.scores[i] = (data,self.multialign,self.bleualign,self.scoredict)
i,data = self.tasks.get()<|fim▁end|> | self.log(self.sources_out[i],3)
self.log(self.targets_out[i],3) |
<|file_name|>test_views.py<|end_file_name|><|fim▁begin|>import copy
import csv
import datetime
import json
import mock
import os
import re
import shutil
import tempfile
import urllib
import pyquery
from cStringIO import StringIO
from nose.tools import eq_, ok_, assert_raises
from nose.plugins.skip import SkipTest
from django.test.client import RequestFactory
from django.test.utils import override_settings
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.models import (
User,
AnonymousUser,
Group,
Permission
)
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.contrib.contenttypes.models import ContentType
from crashstats.base.tests.testbase import DjangoTestCase
from crashstats.crashstats import models
from crashstats.crashstats.management import PERMISSIONS
from .test_models import Response
SAMPLE_STATUS = {
"breakpad_revision": "1035",
"hits": [
{
"date_oldest_job_queued": "2012-09-28T20:39:33+00:00",
"date_recently_completed": "2012-09-28T20:40:00+00:00",
"processors_count": 1,
"avg_wait_sec": 16.407,
"waiting_job_count": 56,
"date_created": "2012-09-28T20:40:02+00:00",
"id": 410655,
"avg_process_sec": 0.914149
},
{
"date_oldest_job_queued": "2012-09-28T20:34:33+00:00",
"date_recently_completed": "2012-09-28T20:35:00+00:00",
"processors_count": 1,
"avg_wait_sec": 13.8293,
"waiting_job_count": 48,
"date_created": "2012-09-28T20:35:01+00:00",
"id": 410654,
"avg_process_sec": 1.24177
},
{
"date_oldest_job_queued": "2012-09-28T20:29:32+00:00",
"date_recently_completed": "2012-09-28T20:30:01+00:00",
"processors_count": 1,
"avg_wait_sec": 14.8803,
"waiting_job_count": 1,
"date_created": "2012-09-28T20:30:01+00:00",
"id": 410653,
"avg_process_sec": 1.19637
}
],
"total": 12,
"socorro_revision": "017d7b3f7042ce76bc80949ae55b41d1e915ab62",
"schema_revision": "schema_12345"
}
SAMPLE_META = """ {
"InstallTime": "1339289895",
"FramePoisonSize": "4096",
"Theme": "classic/1.0",
"Version": "5.0a1",
"Email": "%s",
"Vendor": "Mozilla",
"URL": "%s"
} """
SAMPLE_UNREDACTED = """ {
"client_crash_date": "2012-06-11T06:08:45",
"dump": "%s",
"signature": "FakeSignature1",
"user_comments": "%s",
"uptime": 14693,
"release_channel": "nightly",
"uuid": "11cb72f5-eb28-41e1-a8e4-849982120611",
"flash_version": "[blank]",
"hangid": null,
"distributor_version": null,
"truncated": true,
"process_type": null,
"id": 383569625,
"os_version": "10.6.8 10K549",
"version": "5.0a1",
"build": "20120609030536",
"ReleaseChannel": "nightly",
"addons_checked": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"last_crash": 371342,
"date_processed": "2012-06-11T06:08:44",
"cpu_name": "amd64",
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"address": "0x8",
"completeddatetime": "2012-06-11T06:08:57",
"success": true,
"json_dump": {
"status": "OK",
"sensitive": {
"exploitability": "high"
},
"threads": []
}
} """
BUG_STATUS = """ {
"hits": [{"id": "222222",
"signature": "FakeSignature1"},
{"id": "333333",
"signature": "FakeSignature1"},
{"id": "444444",
"signature": "Other FakeSignature"}
]
} """
SAMPLE_SIGNATURE_SUMMARY = {
"reports": {
"products": [
{
"version_string": "33.0a2",
"percentage": "57.542",
"report_count": 103,
"product_name": "Firefox"
},
],
"uptime": [
{
"category": "< 1 min",
"percentage": "29.126",
"report_count": 30
}
],
"architecture": [
{
"category": "x86",
"percentage": "100.000",
"report_count": 103
}
],
"flash_version": [
{
"category": "[blank]",
"percentage": "100.000",
"report_count": 103
}
],
"graphics": [
{
"report_count": 24,
"adapter_name": None,
"vendor_hex": "0x8086",
"percentage": "23.301",
"vendor_name": None,
"adapter_hex": "0x0166"
}
],
"distinct_install": [
{
"crashes": 103,
"version_string": "33.0a2",
"product_name": "Firefox",
"installations": 59
}
],
"devices": [
{
"cpu_abi": "XXX",
"manufacturer": "YYY",
"model": "ZZZ",
"version": "1.2.3",
"report_count": 52311,
"percentage": "48.440",
}
],
"os": [
{
"category": "Windows 8.1",
"percentage": "55.340",
"report_count": 57
}
],
"process_type": [
{
"category": "Browser",
"percentage": "100.000",
"report_count": 103
}
],
"exploitability": [
{
"low_count": 0,
"high_count": 0,
"null_count": 0,
"none_count": 4,
"report_date": "2014-08-12",
"medium_count": 0
}
]
}
}
class RobotsTestViews(DjangoTestCase):
@override_settings(ENGAGE_ROBOTS=True)
def test_robots_txt(self):
url = '/robots.txt'
response = self.client.get(url)
eq_(response.status_code, 200)
eq_(response['Content-Type'], 'text/plain')
ok_('Allow: /' in response.content)
@override_settings(ENGAGE_ROBOTS=False)
def test_robots_txt_disengage(self):
url = '/robots.txt'
response = self.client.get(url)
eq_(response.status_code, 200)
eq_(response['Content-Type'], 'text/plain')
ok_('Disallow: /' in response.content)
class FaviconTestViews(DjangoTestCase):
def test_favicon(self):
tmp_static_root = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp_static_root)
favicon_dir = os.path.join(tmp_static_root, 'img')
os.makedirs(favicon_dir)
favicon_path = os.path.join(favicon_dir, 'favicon.ico')
with open(favicon_path, 'wb') as icon:
icon.write('totally fake')
with self.settings(STATIC_ROOT=tmp_static_root):
response = self.client.get('/favicon.ico')
eq_(response.status_code, 200)
ok_('image/x-icon' in response['Content-Type'])
class BaseTestViews(DjangoTestCase):
@mock.patch('requests.get')
def setUp(self, rget):
super(BaseTestViews, self).setUp()
# checking settings.CACHES isn't as safe as `cache.__class__`
if 'LocMemCache' not in cache.__class__.__name__:
raise ImproperlyConfigured(
'The tests requires that you use LocMemCache when running'
)
# we do this here so that the current/versions thing
# is cached since that's going to be called later
# in every view more or less
def mocked_get(url, params, **options):
now = datetime.datetime.utcnow()
yesterday = now - datetime.timedelta(days=1)
if '/platforms/' in url:
return Response({
"hits": [
{
'code': 'win',
'name': 'Windows',
},
{
'code': 'mac',
'name': 'Mac OS X',
},
{
'code': 'lin',
'name': 'Linux',
}
],
"total": 6
})
if 'products/' in url:
return Response("""
{"products": [
"WaterWolf",
"NightTrain",
"SeaMonkey",
"LandCrab"
],
"hits": {
"WaterWolf": [
{"product": "WaterWolf",
"throttle": "100.00",
"end_date": "%(end_date)s",
"start_date": "2012-03-08",
"featured": true,
"version": "19.0",
"release": "Beta",
"id": 922},
{"product": "WaterWolf",
"throttle": "100.00",
"end_date": "%(end_date)s",
"start_date": "2012-03-08",
"featured": true,
"version": "18.0",
"release": "Stable",
"id": 920},
{"product": "WaterWolf",
"throttle": "100.00",
"end_date": "2012-03-09",
"start_date": "2012-03-08",
"featured": true,
"version": "19.1",
"release": "Nightly",
"id": 928},
{"product": "WaterWolf",
"throttle": "100.00",
"end_date": "%(end_date)s",
"start_date": "2012-03-08",
"featured": true,
"version": "20.0",
"release": "Nightly",
"id": 923}
],
"NightTrain":[
{"product": "NightTrain",
"throttle": "100.00",
"end_date": "%(end_date)s",
"start_date": "2012-03-08",
"featured": true,
"version": "18.0",
"release": "Aurora",
"id": 924},
{"product": "NightTrain",
"throttle": "100.00",
"end_date": "%(end_date)s",
"start_date": "2012-03-08",
"featured": true,
"version": "19.0",
"release": "Nightly",
"id": 925}
],
"SeaMonkey": [
{"product": "SeaMonkey",
"throttle": "99.00",
"end_date": "%(yesterday)s",
"start_date": "2012-03-08",
"featured": true,
"version": "9.5",
"release": "Alpha",
"id": 921},
{"product": "SeaMonkey",
"throttle": "99.00",
"end_date": "%(end_date)s",
"start_date": "2012-03-08",
"featured": true,
"version": "10.5",
"release": "nightly",
"id": 926}
],
"LandCrab": [
{"product": "LandCrab",
"throttle": "99.00",
"end_date": "%(end_date)s",
"start_date": "2012-03-08",
"featured": false,
"version": "1.5",
"release": "Release",
"id": 927}
]
},
"total": 4
}
""" % {'end_date': now.strftime('%Y-%m-%d'),
'yesterday': yesterday.strftime('%Y-%m-%d')})
if '/supersearch/fields/' in url:
from crashstats.supersearch.tests.test_views import (
SUPERSEARCH_FIELDS_MOCKED_RESULTS
)
results = copy.copy(SUPERSEARCH_FIELDS_MOCKED_RESULTS)
# to be realistic we want to introduce some dupes
# that have a different key but its `in_database_name`
# is one that is already in the hardcoded list (the
# baseline)
assert 'accessibility' not in results
results['accessibility'] = {
'name': 'accessibility',
'query_type': 'string',
'namespace': 'raw_crash',
'form_field_choices': None,
'permissions_needed': [],
'default_value': None,
'is_exposed': True,
'is_returned': True,
'is_mandatory': False,
'in_database_name': 'Accessibility',
}
return Response(results)
raise NotImplementedError(url)
rget.side_effect = mocked_get
# call these here so it gets patched for each test because
# it gets used so often
from crashstats.crashstats.models import CurrentVersions, Platforms
CurrentVersions().get()
Platforms().get()
from crashstats.supersearch.models import SuperSearchFields
SuperSearchFields().get()
def tearDown(self):
super(BaseTestViews, self).tearDown()
cache.clear()
def _login(self):
user = User.objects.create_user('test', '[email protected]', 'secret')
assert self.client.login(username='test', password='secret')
return user
def _logout(self):
self.client.logout()
def _add_permission(self, user, codename, group_name='Hackers'):
group = self._create_group_with_permission(codename)
user.groups.add(group)
def _create_group_with_permission(self, codename, group_name='Group'):
appname = 'crashstats'
ct, __ = ContentType.objects.get_or_create(
model='',
app_label=appname,
defaults={'name': appname}
)
permission, __ = Permission.objects.get_or_create(
codename=codename,
name=PERMISSIONS[codename],
content_type=ct
)
group, __ = Group.objects.get_or_create(
name=group_name,
)
group.permissions.add(permission)
return group
class TestGoogleAnalytics(BaseTestViews):
@override_settings(GOOGLE_ANALYTICS_ID='xyz123')
@override_settings(GOOGLE_ANALYTICS_DOMAIN='test.biz')
@mock.patch('requests.get')
def test_google_analytics(self, rget):
url = reverse('crashstats:home', args=('WaterWolf',))
def mocked_get(url, params, **options):
if 'products' in url:
return Response("""
{
"hits": [{
"is_featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "WaterWolf",
"build_type": "Nightly",
"version": "19.0",
"has_builds": true,
"start_date": "2012-09-25"
}],
"total": 1
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('xyz123' in response.content)
ok_('test.biz' in response.content)
class TestViews(BaseTestViews):
def test_contribute_json(self):
response = self.client.get('/contribute.json')
eq_(response.status_code, 200)
# should be valid JSON
ok_(json.loads(response.content))
eq_(response['Content-Type'], 'application/json')
@mock.patch('requests.get')
def test_handler500(self, rget):
root_urlconf = __import__(
settings.ROOT_URLCONF,
globals(),
locals(),
['urls'],
-1
)
# ...so that we can access the 'handler500' defined in there
par, end = root_urlconf.handler500.rsplit('.', 1)
# ...which is an importable reference to the real handler500 function
views = __import__(par, globals(), locals(), [end], -1)
# ...and finally we have the handler500 function at hand
handler500 = getattr(views, end)
# to make a mock call to the django view functions you need a request
fake_request = RequestFactory().request(**{'wsgi.input': None})
# Need a fake user for the persona bits on crashstats_base
fake_request.user = AnonymousUser()
# the reason for first causing an exception to be raised is because
# the handler500 function is only called by django when an exception
# has been raised which means sys.exc_info() is something.
try:
raise NameError('sloppy code')
except NameError:
# do this inside a frame that has a sys.exc_info()
response = handler500(fake_request)
eq_(response.status_code, 500)
ok_('Internal Server Error' in response.content)
ok_('id="products_select"' not in response.content)
def test_handler404(self):
url = reverse('crashstats:home', args=('Unknown',))
response = self.client.get(url)
eq_(response.status_code, 404)
ok_('Page not Found' in response.content)
ok_('id="products_select"' not in response.content)
def test_homepage_redirect(self):
response = self.client.get('/')
eq_(response.status_code, 302)
destination = reverse('crashstats:home',
args=[settings.DEFAULT_PRODUCT])
ok_(destination in response['Location'])
def test_homepage_products_redirect_without_versions(self):
url = reverse('crashstats:home', args=['WaterWolf'])
# some legacy URLs have this
url += '/versions/'
response = self.client.get(url)
redirect_code = settings.PERMANENT_LEGACY_REDIRECTS and 301 or 302
eq_(response.status_code, redirect_code)
destination = reverse('crashstats:home', args=['WaterWolf'])
ok_(destination in response['Location'])
def test_legacy_query_redirect(self):
response = self.client.get('/query/query?foo=bar')
redirect_code = settings.PERMANENT_LEGACY_REDIRECTS and 301 or 302
eq_(response.status_code, redirect_code)
ok_(reverse('crashstats:query') + '?foo=bar' in response['Location'])
@mock.patch('requests.get')
def test_buginfo(self, rget):
url = reverse('crashstats:buginfo')
def mocked_get(url, params, **options):
if 'bug?id=' in url:
return Response('{"bugs": [{"product": "allizom.org"}]}')
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url)
eq_(response.status_code, 400)
response = self.client.get(url, {'bug_ids': '123,456'})
eq_(response.status_code, 400)
response = self.client.get(url, {'include_fields': 'product'})
eq_(response.status_code, 400)
response = self.client.get(url, {'bug_ids': ' 123, 456 ',
'include_fields': ' product'})
eq_(response.status_code, 200)
struct = json.loads(response.content)
ok_(struct['bugs'])
eq_(struct['bugs'][0]['product'], 'allizom.org')
@mock.patch('requests.get')
def test_buginfo_with_caching(self, rget):
url = reverse('crashstats:buginfo')
def mocked_get(url, params, **options):
if 'bug?id=' in url:
return Response("""{"bugs": [
{"id": "987",
"product": "allizom.org",
"summary": "Summary 1"},
{"id": "654",
"product": "mozilla.org",
"summary": "Summary 2"}
]}""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {
'bug_ids': '987,654',
'include_fields': 'product,summary'
})
eq_(response.status_code, 200)
struct = json.loads(response.content)
eq_(struct['bugs'][0]['product'], 'allizom.org')
eq_(struct['bugs'][0]['summary'], 'Summary 1')
eq_(struct['bugs'][0]['id'], '987')
eq_(struct['bugs'][1]['product'], 'mozilla.org')
eq_(struct['bugs'][1]['summary'], 'Summary 2')
eq_(struct['bugs'][1]['id'], '654')
# expect to be able to find this in the cache now
cache_key = 'buginfo:987'
eq_(cache.get(cache_key), struct['bugs'][0])
@mock.patch('requests.get')
def test_home(self, rget):
url = reverse('crashstats:home', args=('WaterWolf',))
def mocked_get(url, params, **options):
if '/products' in url and 'versions' not in params:
return Response("""
{
"products": [
"WaterWolf"
],
"hits": {
"WaterWolf": [{
"featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "WaterWolf",
"release": "Nightly",
"version": "19.0",
"has_builds": true,
"start_date": "2012-09-25"
}]
},
"total": 1
}
""")
elif '/products' in url:
return Response("""
{
"hits": [{
"is_featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "WaterWolf",
"build_type": "Nightly",
"version": "19.0",
"has_builds": true,
"start_date": "2012-09-25"
}],
"total": 1
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url)
eq_(response.status_code, 200)
# Testing with unknown product
url = reverse('crashstats:home', args=('InternetExplorer',))
response = self.client.get(url)
eq_(response.status_code, 404)
# Testing with unknown version for product
url = reverse('crashstats:home', args=('WaterWolf', '99'))
response = self.client.get(url)
eq_(response.status_code, 404)
# Testing with valid version for product
url = reverse('crashstats:home', args=('WaterWolf', '19.0'))
response = self.client.get(url)
eq_(response.status_code, 200)
@mock.patch('requests.get')
def test_frontpage_json(self, rget):
url = reverse('crashstats:frontpage_json')
def mocked_get(url, params, **options):
if '/crashes/daily' in url:
return Response("""
{
"hits": {
"WaterWolf:19.0": {
"2012-10-08": {
"product": "WaterWolf",
"adu": 30000,
"crash_hadu": 71.099999999999994,
"version": "19.0",
"report_count": 2133,
"date": "2012-10-08"
},
"2012-10-02": {
"product": "WaterWolf",
"adu": 30000,
"crash_hadu": 77.299999999999997,
"version": "19.0",
"report_count": 2319,
"date": "2012-10-02"
}
}
}
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {'product': 'WaterWolf'})
eq_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
ok_(struct['product_versions'])
eq_(struct['count'], 1)
@mock.patch('requests.get')
def test_frontpage_json_bad_request(self, rget):
url = reverse('crashstats:frontpage_json')
def mocked_get(url, params, **options):
assert '/crashes/daily' in url, url
if 'product' in params and params['product'] == 'WaterWolf':
return Response("""
{
"hits": {
"WaterWolf:19.0": {
"2012-10-08": {
"product": "WaterWolf",
"adu": 30000,
"crash_hadu": 71.099999999999994,
"version": "19.0",
"report_count": 2133,
"date": "2012-10-08"
},
"2012-10-02": {
"product": "WaterWolf",
"adu": 30000,
"crash_hadu": 77.299999999999997,
"version": "19.0",
"report_count": 2319,
"date": "2012-10-02"
}
}
}
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {'product': 'Neverheardof'})
eq_(response.status_code, 400)
response = self.client.get(url, {'versions': '999.1'})
eq_(response.status_code, 400)
response = self.client.get(url, {
'product': 'WaterWolf',
'versions': '99.9' # mismatch
})
eq_(response.status_code, 400)
response = self.client.get(url, {
'product': 'WaterWolf',
'versions': '19.0'
})
eq_(response.status_code, 200)
response = self.client.get(url, {
'product': 'WaterWolf',
'duration': 'xxx'
})
eq_(response.status_code, 400)
response = self.client.get(url, {
'product': 'WaterWolf',
'duration': '-100'
})
eq_(response.status_code, 400)
response = self.client.get(url, {
'product': 'WaterWolf',
'duration': '10'
})
eq_(response.status_code, 200)
response = self.client.get(url, {
'product': 'WaterWolf',
'date_range_type': 'junk'
})
eq_(response.status_code, 400)
response = self.client.get(url, {
'product': 'WaterWolf',
'date_range_type': 'build'
})
eq_(response.status_code, 200)
response = self.client.get(url, {
'product': 'WaterWolf',
'date_range_type': 'report'
})
eq_(response.status_code, 200)
@mock.patch('requests.get')
def test_frontpage_json_no_data_for_version(self, rget):
url = reverse('crashstats:frontpage_json')
def mocked_get(url, params, **options):
assert '/crashes/daily' in url, url
if 'product' in params and params['product'] == 'WaterWolf':
return Response("""
{
"hits": {}
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {
'product': 'WaterWolf',
'versions': '20.0'
})
eq_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
# Even though there was no data, the product_versions
# property should still exist and be populated.
eq_(struct['count'], 0)
ok_(struct['product_versions'])
selected_product = struct['product_versions'][0]
eq_(selected_product['product'], 'WaterWolf')
eq_(selected_product['version'], '20.0')
@mock.patch('requests.get')
def test_products_list(self, rget):
url = reverse('crashstats:products_list')
def mocked_get(url, params, **options):
if '/products' in url:
return Response("""
{
"products": [
"WaterWolf",
"Fennec"
],
"hits": [
{
"sort": "1",
"default_version": "15.0.1",
"release_name": "firefox",
"rapid_release_version": "5.0",
"product_name": "WaterWolf"
},
{
"sort": "3",
"default_version": "10.0.6esr",
"release_name": "mobile",
"rapid_release_version": "5.0",
"product_name": "Fennec"
}],
"total": "2"
}
""")
rget.side_effect = mocked_get
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
@mock.patch('requests.get')
def test_gccrashes(self, rget):
url = reverse('crashstats:gccrashes', args=('WaterWolf',))
unknown_product_url = reverse('crashstats:gccrashes',
args=('NotKnown',))
invalid_version_url = reverse('crashstats:gccrashes',
args=('WaterWolf', '99'))
def mocked_get(**options):
if '/products' in options['url']:
return Response("""
{
"products": ["WaterWolf"],
"hits": [
{
"product": "WaterWolf",
"version": "20.0",
"release": "Nightly"
}
],
"total": "1"
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('Total Volume of GC Crashes for WaterWolf 19.1'
in response.content)
response = self.client.get(invalid_version_url)
eq_(response.status_code, 200)
doc = pyquery.PyQuery(response.content)
eq_(doc('.django-form-error li b')[0].text, 'Version:')
response = self.client.get(unknown_product_url)
eq_(response.status_code, 404)
@mock.patch('requests.get')
def test_gccrashes_json(self, rget):
url = reverse('crashstats:gccrashes_json')
def mocked_get(url, params, **options):
if '/gccrashes' in url:
return Response("""
{
"hits": [
[
"20140203000001",
366
]
],
"total": 1
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {
'product': 'WaterWolf',
'version': '20.0',
'start_date': '2014-01-27',
'end_date': '2014-02-04'
})
ok_(response.status_code, 200)
ok_('application/json' in response['content-type'])
@mock.patch('requests.get')
def test_gccrashes_json_bad_request(self, rget):
url = reverse('crashstats:gccrashes_json')
def mocked_get(url, **options):
if 'gccrashes/' in url:
return Response("""
{
"hits": [
[
"20140203000001",
366
]
],
"total": 1
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {
'product': 'WaterWolf',
'version': '20.0',
'start_date': 'XXXXXX', # not even close
'end_date': '2014-02-04'
})
ok_(response.status_code, 400)
response = self.client.get(url, {
'product': 'WaterWolf',
'version': '20.0',
'start_date': '2014-02-33', # crazy date
'end_date': '2014-02-04'
})
ok_(response.status_code, 400)
# same but on the end_date
response = self.client.get(url, {
'product': 'WaterWolf',
'version': '20.0',
'start_date': '2014-02-13',
'end_date': '2014-02-44' # crazy date
})
ok_(response.status_code, 400)
# start_date > end_date
response = self.client.get(url, {
'product': 'WaterWolf',
'version': '20.0',
'start_date': '2014-02-02',
'end_date': '2014-01-01' # crazy date
})
ok_(response.status_code, 400)
def test_crash_trends(self):
url = reverse('crashstats:crash_trends', args=('WaterWolf',))
no_nightly_url = reverse('crashstats:crash_trends', args=('LandCrab',))
inconsistent_case_url = reverse('crashstats:crash_trends',
args=('SeaMonkey',))
unkown_product_url = reverse('crashstats:crash_trends',
args=('NotKnown',))
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('Nightly Crash Trends For WaterWolf' in response.content)
response = self.client.get(unkown_product_url)
eq_(response.status_code, 404)
# This used to cause a 500 because there is no Nightly associated
# with this product, should 200 now.
response = self.client.get(no_nightly_url)
eq_(response.status_code, 200)
ok_('Nightly Crash Trends For LandCrab' in response.content)
# This used to cause a 500 because of inconsistent case for
# release names in the DB, causing some releases to be returned
# as 'nightly' instead of 'Nightly'. This should now return 200.
response = self.client.get(inconsistent_case_url)
eq_(response.status_code, 200)
ok_('Nightly Crash Trends For SeaMonkey' in response.content)
@mock.patch('requests.get')
def test_get_nightlies_for_product_json(self, rget):
url = reverse('crashstats:get_nightlies_for_product_json')
def mocked_get(**options):
if '/products' in options['url']:
return Response("""
{
"hits": [
{
"sort": "1",
"default_version": "5.0a1",
"release_name": "waterwolf",
"rapid_release_version": "5.0",
"product_name": "WaterWolf"
}],
"total": "1"
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {'product': 'WaterWolf'})
ok_('application/json' in response['content-type'])
eq_(response.status_code, 200)
ok_(response.content, ['20.0'])
response = self.client.get(url, {'product': 'NightTrain'})
eq_(response.status_code, 200)
ok_(response.content, ['18.0', '19.0'])
response = self.client.get(url, {'product': 'Unknown'})
ok_(response.content, [])
@mock.patch('requests.get')
def test_crashtrends_json(self, rget):
url = reverse('crashstats:crashtrends_json')
def mocked_get(url, params, **options):
ok_('start_date' in params)
eq_('2012-10-01', params['start_date'])
ok_('end_date' in params)
eq_('2012-10-10', params['end_date'])
if '/crashtrends' in url:
return Response("""
{
"crashtrends": [{
"build_date": "2012-10-10",
"version_string": "5.0a1",
"product_version_id": 1,
"days_out": 6,
"report_count": 144,
"report_date": "2012-10-04",
"product_name": "WaterWolf"
},
{
"build_date": "2012-10-06",
"version_string": "5.0a1",
"product_version_id": 1,
"days_out": 2,
"report_count": 162,
"report_date": "2012-10-08",
"product_name": "WaterWolf"
},
{
"build_date": "2012-09-29",
"version_string": "5.0a1",
"product_version_id": 1,
"days_out": 5,
"report_count": 144,
"report_date": "2012-10-04",
"product_name": "WaterWolf"
}]
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {
'product': 'WaterWolf',
'version': '20.0',
'start_date': '2012-10-01',
'end_date': '2012-10-10'
})
ok_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
eq_(struct['total'], 2)
# Test with product that does not have a nightly
response = self.client.get(url, {
'product': 'LandCrab',
'version': '9.5',
'start_date': '2012-10-01',
'end_date': '2012-10-10'
})
ok_(response.status_code, 400)
ok_('text/html' in response['content-type'])
ok_(
'LandCrab is not one of the available choices'
in response.content
)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_topcrasher_ranks_bybug(self, rget, rpost):
url = reverse('crashstats:topcrasher_ranks_bybug')
def mocked_post(**options):
assert '/bugs' in options['url'], options['url']
return Response("""
{"hits": [{"id": "123456789", "signature": "FakeSignature 1"},
{"id": "123456789", "signature": "FakeSignature 3"}]}
""")
def mocked_get(url, params, **options):
signature_summary_data = copy.deepcopy(SAMPLE_SIGNATURE_SUMMARY)
if '/signaturesummary' in url:
signature_summary_data['reports']['products'] = [
{
"version_string": "18.0",
"percentage": "48.440",
"report_count": 52311,
"product_name": "WaterWolf",
},
{
"version_string": "18.0",
"percentage": "48.440",
"report_count": 52311,
"product_name": "NightTrain",
},
{
"version_string": "13.0b4",
"percentage": "9.244",
"report_count": 9983,
"product_name": "WaterWolf",
}
]
return Response(signature_summary_data)
if '/crashes/signatures' in url:
return Response(u"""
{"crashes": [
{
"count": 188,
"mac_count": 66,
"content_count": 0,
"first_report": "2012-06-21",
"startup_percent": 0.0,
"currentRank": 0,
"previousRank": 1,
"first_report_exact": "2012-06-21T21:28:08",
"versions":
"2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1",
"percentOfTotal": 0.24258064516128999,
"win_count": 56,
"changeInPercentOfTotal": 0.011139597126354983,
"linux_count": 66,
"hang_count": 0,
"signature": "FakeSignature 1",
"versions_count": 8,
"changeInRank": 1,
"plugin_count": 0,
"previousPercentOfTotal": 0.23144104803493501,
"is_gc_count": 10
},
{
"count": 188,
"mac_count": 66,
"content_count": 0,
"first_report": "2012-06-21",
"startup_percent": 0.0,
"currentRank": 0,
"previousRank": 1,
"first_report_exact": "2012-06-21T21:28:08",
"versions":
"2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1",
"percentOfTotal": 0.24258064516128999,
"win_count": 56,
"changeInPercentOfTotal": 0.011139597126354983,
"linux_count": 66,
"hang_count": 0,
"signature": "FakeSignature 2",
"versions_count": 8,
"changeInRank": 1,
"plugin_count": 0,
"previousPercentOfTotal": 0.23144104803493501,
"is_gc_count": 10
}
],
"totalPercentage": 0,
"start_date": "2012-05-10",
"end_date": "2012-05-24",
"totalNumberOfCrashes": 2}
""")
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
response = self.client.get(url, {'bug_number': '123456789'})
ok_('FakeSignature 1' in response.content)
ok_('FakeSignature 2' not in response.content)
ok_('FakeSignature 3' in response.content)
report_list_url = reverse('crashstats:report_list')
report_list_url1 = (
'%s?signature=%s' % (
report_list_url,
urllib.quote_plus('FakeSignature 1')
)
)
ok_(report_list_url1 in response.content)
report_list_url3 = (
'%s?signature=%s' % (
report_list_url,
urllib.quote_plus('FakeSignature 3')
)
)
ok_(report_list_url3 in response.content)
# ensure that multiple products appear
doc = pyquery.PyQuery(response.content)
eq_(doc('td[class=product]')[0].text, 'WaterWolf')
eq_(doc('td[class=product]')[1].text, 'NightTrain')
eq_(response.status_code, 200)
# we also have a signature with no active product+version
ok_('Not found in active topcrash lists' in response.content)
response = self.client.get(url, {'bug_number': '123bad'})
eq_(response.status_code, 400)
response = self.client.get(url, {'bug_number': '1234564654564646'})
eq_(response.status_code, 400)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_topcrasher(self, rget, rpost):
# first without a version
no_version_url = reverse('crashstats:topcrasher',
args=('WaterWolf',))
url = reverse('crashstats:topcrasher',
args=('WaterWolf', '19.0'))
has_builds_url = reverse('crashstats:topcrasher',
args=('WaterWolf', '19.0', 'build'))
reports_count_default = reverse('crashstats:topcrasher',
args=('WaterWolf', '19.0'))
reports_count_100 = reverse('crashstats:topcrasher',
args=('WaterWolf', '19.0', None, None,
None, '100'))
response = self.client.get(no_version_url)
ok_(url in response['Location'])
def mocked_post(**options):
assert '/bugs/' in options['url'], options['url']
return Response("""{
"hits": [
{"id": 123456789,
"signature": "Something"},
{"id": 22222,
"signature": "FakeSignature1 \u7684 Japanese"},
{"id": 33333,
"signature": "FakeSignature1 \u7684 Japanese"}
]
}
""")
def mocked_get(url, params, **options):
if '/crashes/signatures' in url:
return Response(u"""
{"crashes": [
{
"count": 188,
"mac_count": 66,
"content_count": 0,
"first_report": "2012-06-21",
"startup_percent": 0.0,
"currentRank": 0,
"previousRank": 1,
"first_report_exact": "2012-06-21T21:28:08",
"versions":
"2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1",
"percentOfTotal": 0.24258064516128999,
"win_count": 56,
"changeInPercentOfTotal": 0.011139597126354983,
"linux_count": 66,
"hang_count": 0,
"signature": "FakeSignature1 \u7684 Japanese",
"versions_count": 8,
"changeInRank": 1,
"plugin_count": 0,
"previousPercentOfTotal": 0.23144104803493501,
"is_gc_count": 10
}
],
"totalPercentage": 0,
"start_date": "2012-05-10",
"end_date": "2012-05-24",
"totalNumberOfCrashes": 0}
""")
if '/products' in url:
return Response("""
{
"hits": [
{
"is_featured": true,
"throttle": 1.0,
"end_date": "string",
"start_date": "integer",
"build_type": "string",
"product": "WaterWolf",
"version": "19.0",
"has_builds": true
}],
"total": "1"
}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('By Crash Date' in response.content)
response = self.client.get(has_builds_url)
eq_(response.status_code, 200)
ok_('By Build Date' in response.content)
response = self.client.get(reports_count_default)
eq_(response.status_code, 200)
doc = pyquery.PyQuery(response.content)
selected_count = doc('.tc-result-count a[class="selected"]')
eq_(selected_count.text(), '50')
# there's actually only one such TD
bug_ids = [x.text for x in doc('td.bug_ids_more > a')]
# higher bug number first
eq_(bug_ids, ['33333', '22222'])
response = self.client.get(reports_count_100)
eq_(response.status_code, 200)
doc = pyquery.PyQuery(response.content)
selected_count = doc('.tc-result-count a[class="selected"]')
eq_(selected_count.text(), '100')
# also, render the CSV
response = self.client.get(url, {'format': 'csv'})
eq_(response.status_code, 200)
ok_('text/csv' in response['Content-Type'])
# know your fixtures :)
ok_('WaterWolf' in response['Content-Disposition'])
ok_('19.0' in response['Content-Disposition'])
# we should be able unpack it
reader = csv.reader(StringIO(response.content))
line1, line2 = reader
eq_(line1[0], 'Rank')
try:
eq_(int(line2[0]), 1)
except Exception:
raise SkipTest
# bytestring when exported as CSV with UTF-8 encoding
eq_(line2[4], 'FakeSignature1 \xe7\x9a\x84 Japanese')
def test_topcrasher_with_invalid_version(self):
# 0.1 is not a valid release version
url = reverse('crashstats:topcrasher',
args=('WaterWolf', '0.1'))
response = self.client.get(url)
eq_(response.status_code, 404)
def test_topcrasher_with_product_sans_release(self):
# SnowLion is not a product at all
url = reverse('crashstats:topcrasher',
args=('SnowLion', '0.1'))
response = self.client.get(url)
eq_(response.status_code, 404)
# SeaMonkey is a product but has no active releases
url = reverse('crashstats:topcrasher',
args=('SeaMonkey', '9.5'))
response = self.client.get(url)
eq_(response.status_code, 404)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_topcrasher_without_any_signatures(self, rget, rpost):
# first without a version
no_version_url = reverse('crashstats:topcrasher',
args=('WaterWolf',))
url = reverse('crashstats:topcrasher',
args=('WaterWolf', '19.0'))
has_builds_url = reverse('crashstats:topcrasher',
args=('WaterWolf', '19.0', 'build'))
response = self.client.get(no_version_url)
ok_(url in response['Location'])
def mocked_post(**options):
assert '/bugs' in options['url'], options['url']
return Response("""
{"hits": [{"id": "123456789",
"signature": "Something"}]}
""")
def mocked_get(url, params, **options):
if '/crashes/signatures' in url:
return Response(u"""
{"crashes": [],
"totalPercentage": 0,
"start_date": "2012-05-10",
"end_date": "2012-05-24",
"totalNumberOfCrashes": 0}
""")
if '/products' in url:
return Response("""
{
"hits": [
{
"is_featured": true,
"throttle": 1.0,
"end_date": "string",
"start_date": "integer",
"build_type": "string",
"product": "WaterWolf",
"version": "19.0",
"has_builds": true
}],
"total": "1"
}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('By Crash Date' in response.content)
response = self.client.get(has_builds_url)
eq_(response.status_code, 200)
ok_('By Build Date' in response.content)
# also, render the CSV
response = self.client.get(url, {'format': 'csv'})
eq_(response.status_code, 200)
ok_('text/csv' in response['Content-Type'])
# know your fixtures :)
ok_('WaterWolf' in response['Content-Disposition'])
ok_('19.0' in response['Content-Disposition'])
#
# no signatures, the CSV is empty apart from the header
eq_(len(response.content.splitlines()), 1)
reader = csv.reader(StringIO(response.content))
line1, = reader
eq_(line1[0], 'Rank')
def test_topcrasher_without_versions_redirect(self):
response = self.client.get('/topcrasher/products/WaterWolf/versions/')
redirect_code = settings.PERMANENT_LEGACY_REDIRECTS and 301 or 302
eq_(response.status_code, redirect_code)
actual_url = reverse('crashstats:topcrasher',
kwargs={'product': 'WaterWolf'})
ok_(response['location'].endswith(actual_url))
@mock.patch('requests.get')
def test_exploitable_crashes_without_product(self, rget):
url = reverse('crashstats:exploitable_crashes_legacy')
user = self._login()
group = self._create_group_with_permission('view_exploitability')
user.groups.add(group)
assert user.has_perm('crashstats.view_exploitability')
response = self.client.get(url)
eq_(response.status_code, 301)
correct_url = reverse(
'crashstats:exploitable_crashes',
args=(settings.DEFAULT_PRODUCT,)
)
ok_(response['location'].endswith(correct_url))
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_exploitable_crashes(self, rget, rpost):
url = reverse(
'crashstats:exploitable_crashes',
args=(settings.DEFAULT_PRODUCT,)
)
def mocked_post(url, **options):
assert '/bugs' in url, url
return Response({
"hits": [
{"id": "111111111", "signature": "FakeSignature 1"},
{"id": "222222222", "signature": "FakeSignature 3"},
{"id": "101010101", "signature": "FakeSignature"}
]
})
rpost.side_effect = mocked_post
def mocked_get(url, params, **options):
assert '/crashes/exploitability' in url
ok_('product' in params)
eq_('WaterWolf', params['product'])
return Response("""
{
"hits": [
{
"signature": "FakeSignature",
"report_date": "2013-06-06",
"high_count": 4,
"medium_count": 3,
"low_count": 2,
"none_count": 1,
"product_name": "%s",
"version_string": "2.0"
}
],
"total": 1
}
""" % (settings.DEFAULT_PRODUCT,))
rget.side_effect = mocked_get
response = self.client.get(url)
ok_(settings.LOGIN_URL in response['Location'] + '?next=%s' % url)
ok_(response.status_code, 302)
user = self._login()
response = self.client.get(url)
eq_(response.status_code, 302)
ok_(settings.LOGIN_URL in response['Location'] + '?next=%s' % url)
group = self._create_group_with_permission('view_exploitability')
user.groups.add(group)
assert user.has_perm('crashstats.view_exploitability')
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('FakeSignature' in response.content)
# only this bug ID should be shown
ok_('101010101' in response.content)
# not these bug IDs
ok_('222222222' not in response.content)
ok_('111111111' not in response.content)
# if you try to mess with the paginator it should just load page 1
response = self.client.get(url, {'page': 'meow'})
ok_(response.status_code, 200)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_exploitable_crashes_by_product_and_version(self, rget, rpost):
url = reverse(
'crashstats:exploitable_crashes',
args=(settings.DEFAULT_PRODUCT, '19.0')
)
def mocked_post(url, **options):
assert '/bugs' in url, url
return Response({
"hits": [
{"id": "111111111", "signature": "FakeSignature 1"},
{"id": "222222222", "signature": "FakeSignature 3"},
{"id": "101010101", "signature": "FakeSignature"}
]
})
rpost.side_effect = mocked_post
def mocked_get(url, params, **options):
assert '/crashes/exploitability' in url
ok_('product' in params)
eq_('WaterWolf', params['product'])
ok_('version' in params)
eq_('19.0', params['version'])
return Response("""
{
"hits": [
{
"signature": "FakeSignature",
"report_date": "2013-06-06",
"high_count": 4,
"medium_count": 3,
"low_count": 2,
"none_count": 1,
"product_name": "%s",
"version_string": "123.0"
}
],
"total": 1
}
""" % (settings.DEFAULT_PRODUCT,))
rget.side_effect = mocked_get
user = self._login()
group = self._create_group_with_permission('view_exploitability')
user.groups.add(group)
assert user.has_perm('crashstats.view_exploitability')
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('FakeSignature' in response.content)
@mock.patch('requests.get')
def test_exploitable_crashes_by_unknown_version(self, rget):
url = reverse(
'crashstats:exploitable_crashes',
args=(settings.DEFAULT_PRODUCT, '999.0')
)
user = self._login()
group = self._create_group_with_permission('view_exploitability')
user.groups.add(group)
assert user.has_perm('crashstats.view_exploitability')
response = self.client.get(url)
eq_(response.status_code, 404)
@mock.patch('requests.get')
def test_daily(self, rget):
url = reverse('crashstats:daily')
def mocked_get(url, params, **options):
if '/products' in url:
return Response("""
{
"products": [
"WaterWolf",
"NightTrain"
],
"hits": {
"WaterWolf": [{
"featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "WaterWolf",
"release": "Nightly",
"version": "19.0",
"has_builds": true,
"start_date": "2012-09-25"
}],
"NightTrain": [{
"featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "NightTrain",
"release": "Nightly",
"version": "18.0",
"has_builds": true,
"start_date": "2012-09-25"
}]
},
"total": 2
}
""")
if '/crashes' in url:
# This list needs to match the versions as done in the common
# fixtures set up in setUp() above.
return Response("""
{
"hits": {
"WaterWolf:20.0": {
"2012-09-23": {
"adu": 80388,
"crash_hadu": 12.279,
"date": "2012-08-23",
"product": "WaterWolf",
"report_count": 9871,
"throttle": 0.1,
"version": "20.0"
}
},
"WaterWolf:19.0": {
"2012-08-23": {
"adu": 80388,
"crash_hadu": 12.279,
"date": "2012-08-23",
"product": "WaterWolf",
"report_count": 9871,
"throttle": 0.1,
"version": "19.0"
}
},
"WaterWolf:18.0": {
"2012-08-13": {
"adu": 80388,
"crash_hadu": 12.279,
"date": "2012-08-23",
"product": "WaterWolf",
"report_count": 9871,
"throttle": 0.1,
"version": "18.0"
}
}
}
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {
'p': 'WaterWolf',
'v': ['20.0', '19.0']
})
eq_(response.status_code, 200)
# XXX any basic tests with can do on response.content?
ok_('18.0' in response.content.split('id="version3"')[1].
split("</select>")[0])
ok_('18.0' in response.content.split('id="version2"')[1].
split("</select>")[0])
ok_('18.0' in response.content.split('id="version1"')[1].
split("</select>")[0])
ok_('18.0' in response.content.split('id="version0"')[1].
split("</select>")[0])
# check that the CSV version is working too
response = self.client.get(url, {
'p': 'WaterWolf',
'v': ['20.0', '19.0'],
'format': 'csv'
})
eq_(response.status_code, 200)
eq_(response['Content-Type'], 'text/csv')
# also, I should be able to read it
reader = csv.reader(response)
# because response is an iterator that will return a blank line first
# we skip till the next time
rows = list(reader)[1:]
ok_(rows)
head_row = rows[0]
eq_(head_row[0], 'Date')
eq_(
head_row[1:],
[
'WaterWolf 20.0 Crashes',
'WaterWolf 20.0 ADI',
'WaterWolf 20.0 Throttle',
'WaterWolf 20.0 Ratio',
'WaterWolf 19.0 Crashes',
'WaterWolf 19.0 ADI',
'WaterWolf 19.0 Throttle',
'WaterWolf 19.0 Ratio'
]
)
first_row = rows[1]
eq_(first_row[0], '2012-09-23')
# Test dates don't cause problems
response = self.client.get(url, {
'p': 'WaterWolf',
'v': ['20.0', '19.0'],
'date_start': '2010-01-01'
})
eq_(response.status_code, 200)
@mock.patch('crashstats.crashstats.models.Platforms')
@mock.patch('requests.get')
def test_daily_by_os(self, rget, platforms_get):
url = reverse('crashstats:daily')
def mocked_get(url, params, **options):
if '/products' in url:
return Response("""
{
"products": [
"WaterWolf",
"NightTrain"
],
"hits": {
"WaterWolf": [{
"featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "WaterWolf",
"release": "Nightly",
"version": "19.0",
"has_builds": true,
"start_date": "2012-09-25"
}],
"NightTrain": [{
"featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "NightTrain",
"release": "Nightly",
"version": "18.0",
"has_builds": true,
"start_date": "2012-09-25"
}]
},
"total": 2
}
""")
if '/crashes' in url:
ok_('separated_by' in params)
eq_('os', params['separated_by'])
ok_('os' in params)
eq_(['Windows', 'Amiga'], params['os'])
# This list needs to match the versions as done in the common
# fixtures set up in setUp() above.
return Response("""
{
"hits": {
"WaterWolf:20.0:win": {
"2012-09-23": {
"os": "Windows",
"adu": 80388,
"crash_hadu": 12.279,
"date": "2012-08-23",
"product": "WaterWolf",
"report_count": 9871,
"throttle": 0.1,
"version": "20.0"
}
},
"WaterWolf:20.0:ami": {
"2012-09-23": {
"os": "Amiga",
"adu": 7377,
"crash_hadu": 12.279,
"date": "2012-08-23",
"product": "WaterWolf",
"report_count": 871,
"throttle": 0.1,
"version": "20.0"
}
}
}
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_platforms_get():
return [
{'code': 'win', 'name': 'Windows', 'display': True},
{'code': 'ami', 'name': 'Amiga', 'display': True},
{'code': 'win', 'name': 'Windows95'}, # not displayed
]
platforms_get().get.side_effect = mocked_platforms_get
response = self.client.get(url, {
'p': 'WaterWolf',
'v': '20.0',
'form_selection': 'by_os'
})
eq_(response.status_code, 200)
# XXX any basic tests with can do on response.content?
# check that the CSV version is working too
response = self.client.get(url, {
'p': 'WaterWolf',
'v': '20.0',
'format': 'csv',
'form_selection': 'by_os'
})
eq_(response.status_code, 200)
eq_(response['Content-Type'], 'text/csv')
# also, we should be able to read it
reader = csv.reader(response)
# because response is an iterator that will return a blank line first
# we skip till the next time
rows = list(reader)[1:]
head_row = rows[0]
first_row = rows[1]
eq_(head_row[0], 'Date')
eq_(
head_row[1:],
[
'WaterWolf 20.0 on Windows Crashes',
'WaterWolf 20.0 on Windows ADI',
'WaterWolf 20.0 on Windows Throttle',
'WaterWolf 20.0 on Windows Ratio',
'WaterWolf 20.0 on Amiga Crashes',
'WaterWolf 20.0 on Amiga ADI',
'WaterWolf 20.0 on Amiga Throttle',
'WaterWolf 20.0 on Amiga Ratio'
]
)
eq_(first_row[0], '2012-09-23')
def test_daily_legacy_redirect(self):
url = reverse('crashstats:daily')
response = self.client.get(url + '?p=WaterWolf&v[]=Something')
eq_(response.status_code, 301)
ok_('p=WaterWolf' in response['Location'].split('?')[1])
ok_('v=Something' in response['Location'].split('?')[1])
response = self.client.get(
url + '?p=WaterWolf&os[]=Something&os[]=Else'
)
eq_(response.status_code, 301)
ok_('p=WaterWolf' in response['Location'].split('?')[1])
ok_('os=Something' in response['Location'].split('?')[1])
ok_('os=Else' in response['Location'].split('?')[1])
@mock.patch('requests.get')
def test_daily_with_bad_input(self, rget):
url = reverse('crashstats:daily')
def mocked_get(url, params, **options):
if '/products' in url:
return Response("""
{
"products": [
"WaterWolf",
"NightTrain"
],
"hits": {
"WaterWolf": [{
"featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "WaterWolf",
"release": "Nightly",
"version": "19.0",
"has_builds": true,
"start_date": "2012-09-25"
}],
"NightTrain": [{
"featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "NightTrain",
"release": "Nightly",
"version": "18.0",
"has_builds": true,
"start_date": "2012-09-25"
}]
},
"total": 2
}
""")
if '/crashes' in url:
# This list needs to match the versions as done in the common
# fixtures set up in setUp() above.
return Response("""
{
"hits": {}
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url, {
'p': 'WaterWolf',
'date_start': u' \x00'
})
eq_(response.status_code, 400)
response = self.client.get(url, {
'p': 'WaterWolf',
'date_range_type': 'any old crap'
})
eq_(response.status_code, 400)
response = self.client.get(url, {
'p': 'WaterWolf',
'hang_type': 'any old crap'
})
eq_(response.status_code, 400)
response = self.client.get(url, {
'p': 'WaterWolf',
'format': 'csv',
})
eq_(response.status_code, 200)
eq_(response['Content-Type'], 'text/csv')
# last sanity check
response = self.client.get(url, {
'p': 'WaterWolf',
})
eq_(response.status_code, 200)
def test_quick_search(self):
url = reverse('crashstats:quick_search')
# Test with no parameter.
response = self.client.get(url)
eq_(response.status_code, 302)
target = reverse('supersearch.search')
ok_(response['location'].endswith(target))
# Test with a signature.
response = self.client.get(
url,
{'query': 'moz'}
)
eq_(response.status_code, 302)
target = reverse('supersearch.search') + '?signature=%7Emoz'
ok_(response['location'].endswith(target))
# Test with a crash_id.
crash_id = '1234abcd-ef56-7890-ab12-abcdef130802'
response = self.client.get(
url,
{'query': crash_id}
)
eq_(response.status_code, 302)
target = reverse(
'crashstats:report_index',
kwargs=dict(crash_id=crash_id)
)
ok_(response['location'].endswith(target))
# Test a simple search containing a crash id and spaces
crash_id = ' 1234abcd-ef56-7890-ab12-abcdef130802 '
response = self.client.get(
url,
{'query': crash_id}
)
eq_(response.status_code, 302)
ok_(response['location'].endswith(target))
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_query(self, rget, rpost):
def mocked_post(**options):
assert '/bugs' in options['url'], options['url']
return Response("""
{"hits": [
{
"id": "123456",
"signature": "nsASDOMWindowEnumerator::GetNext()"
}
],
"total": 1
}
""")
def mocked_get(url, params, **options):
assert '/search/signatures' in url
if 'products' in params and 'WaterWolf' in params['products']:
return Response("""{
"hits": [
{
"count": 586,
"signature": "nsASDOMWindowEnumerator::GetNext()",
"numcontent": 0,
"is_windows": 586,
"is_linux": 0,
"numplugin": 56,
"is_mac": 0,
"numhang": 0
},
{
"count": 13,
"signature": "mySignatureIsCool",
"numcontent": 0,
"is_windows": 10,
"is_linux": 2,
"numplugin": 0,
"is_mac": 1,
"numhang": 0
},
{
"count": 2,
"signature": "mineIsCoolerThanYours",
"numcontent": 0,
"is_windows": 0,
"is_linux": 0,
"numplugin": 0,
"is_mac": 2,
"numhang": 2
},
{
"count": 2,
"signature": null,
"numcontent": 0,
"is_windows": 0,
"is_linux": 0,
"numplugin": 0,
"is_mac": 2,
"numhang": 2
}
],
"total": 4
} """)
elif 'products' in params and 'NightTrain' in params['products']:
return Response('{"hits": [], "total": 0}')
elif 'products' in params and 'SeaMonkey' in params['products']:
ok_('plugin_search_mode' in params)
eq_(params['plugin_search_mode'], 'is_exactly')
return Response("""
{"hits": [
{
"count": 586,
"signature": "nsASDOMWindowEnumerator::GetNext()",
"numcontent": 0,
"is_windows": 586,
"is_linux": 0,
"numplugin": 533,
"is_mac": 0,
"numhang": 0,
"pluginname": "superAddOn",
"pluginfilename": "addon.dll",
"pluginversion": "1.2.3"
}],
"total": 1
}
""")
else:
return Response("""
{"hits": [
{
"count": 586,
"signature": "nsASDOMWindowEnumerator::GetNext()",
"numcontent": 0,
"is_windows": 586,
"is_linux": 0,
"numplugin": 0,
"is_mac": 0,
"numhang": 0
}],
"total": 1
}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
url = reverse('crashstats:query')
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('<h2>Query Results</h2>' not in response.content)
ok_('table id="signatureList"' not in response.content)
# Verify that the passed product is selected in search form
response = self.client.get(url, {'product': 'NightTrain'})
eq_(response.status_code, 200)
ok_('<h2>Query Results</h2>' not in response.content)
ok_('table id="signatureList"' not in response.content)
ok_('value="NightTrain" selected' in response.content)
# Verify that the passed version is selected in nav
response = self.client.get(url, {
'product': 'NightTrain',
'version': 'NightTrain:18.0'
})
eq_(response.status_code, 200)
ok_('<h2>Query Results</h2>' not in response.content)
ok_('table id="signatureList"' not in response.content)
# Because versions in the search form only gets set on DOM ready,
# we here ensure that the version was passed and set by checking
# that the correct version is selected in the versions drop-down.
ok_('option value="18.0" selected' in response.content)
response = self.client.get(url, {
'product': 'WaterWolf',
'date': '2012-01-01'
})
eq_(response.status_code, 200)
ok_('<h2>Query Results</h2>' in response.content)
ok_('table id="signatureList"' in response.content)
ok_('nsASDOMWindowEnumerator::GetNext()' in response.content)
ok_('mySignatureIsCool' in response.content)
ok_('mineIsCoolerThanYours' in response.content)
ok_('(null signature)' in response.content)
# Test that the default value for query_type is 'contains'
ok_('<option value="contains" selected' in response.content)
# Test with empty results
response = self.client.get(url, {
'product': 'NightTrain',
'date': '2012-01-01'
})
eq_(response.status_code, 200)
ok_('<h2>Query Results</h2>' in response.content)
ok_('The maximum query date' not in response.content)
ok_('table id="signatureList"' not in response.content)
ok_('Results within' in response.content)
ok_('No results were found' in response.content)
response = self.client.get(url, {'query': 'nsASDOMWindowEnumerator'})
eq_(response.status_code, 200)
ok_('<h2>Query Results</h2>' in response.content)
ok_('table id="signatureList"' in response.content)
ok_('nsASDOMWindowEnumerator::GetNext()' in response.content)
ok_('123456' in response.content)
# Test that the signature parameter is used as default value
response = self.client.get(url, {'signature': 'myFunctionIsCool'})
eq_(response.status_code, 200)
ok_('<h2>Query Results</h2>' not in response.content)
ok_('table id="signatures-list"' not in response.content)
ok_('value="myFunctionIsCool"' in response.content)
# Test that null bytes break the page cleanly
response = self.client.get(url, {'date': u' \x00'})
eq_(response.status_code, 400)
ok_('<h2>Query Results</h2>' not in response.content)
ok_('Enter a valid date/time' in response.content)
# Test that do_query forces the query
response = self.client.get(url, {
'do_query': 1,
'product': 'WaterWolf'
})
eq_(response.status_code, 200)
ok_('<h2>Query Results</h2>' in response.content)
ok_('table id="signatureList"' in response.content)
ok_('nsASDOMWindowEnumerator::GetNext()' in response.content)
# Test that old query types are changed
# Test that plugin data is displayed
response = self.client.get(url, {
'do_query': 1,
'product': 'SeaMonkey',
'plugin_query_type': 'exact',
'process_type': 'plugin',
})
eq_(response.status_code, 200)
ok_('<h2>Query Results</h2>' in response.content)
ok_('table id="signatureList"' in response.content)
ok_('nsASDOMWindowEnumerator::GetNext()' in response.content)
ok_('Plugin Filename' in response.content)
ok_('Plugin Name/Ver' in response.content)
ok_('addon.dll' in response.content)
ok_('superAddOn 1.2.3' in response.content)
# Test 'all' is an accepted value for report_type and hang_type
response = self.client.get(url, {
'do_query': 1,
'product': 'WaterWolf',
'hang_type': 'all',
'process_type': 'all',
})
eq_(response.status_code, 200)
ok_('table id="signatureList"' in response.content)
ok_('value="any" checked' in response.content)
# Test defaut date
expected = datetime.datetime.utcnow()
response = self.client.get(url)
eq_(response.status_code, 200)
ok_(expected.strftime('%m/%d/%Y %H:00:00') in response.content)
# Test passed date
response = self.client.get(url, {
'date': '11/27/2031 10:10:10'
})
eq_(response.status_code, 200)
ok_('11/27/2031 10:10:10' in response.content)
# Test value of build ids
response = self.client.get(url, {
'build_id': '12345'
})
eq_(response.status_code, 200)
ok_('value="12345"' in response.content)
response = self.client.get(url, {
'build_id': '12345,54321'
})
eq_(response.status_code, 200)
ok_('value="12345, 54321"' in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_query_range(self, rget, rpost):
def mocked_post(**options):
return Response('{"hits": [], "total": 0}')
def mocked_get(url, params, **options):
assert '/search/signatures' in url
response = ','.join('''
{
"count": %(x)s,
"signature": "sig%(x)s",
"numcontent": 0,
"is_windows": %(x)s,
"is_linux": 0,
"numplugin": 0,
"is_mac": 0,
"numhang": 0
}
''' % {'x': x} for x in range(150))
return Response('{"hits": [%s], "total": 150}' % response)
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
url = reverse('crashstats:query')
# Test an out-of-range date range
response = self.client.get(url, {
'query': 'js::',
'range_unit': 'weeks',
'range_value': 9
})
eq_(response.status_code, 200)
ok_('The maximum query date' in response.content)
ok_('Admins may log in' in response.content)
ok_('name="range_value" value="%s"' % settings.QUERY_RANGE_DEFAULT_DAYS
in response.content)
ok_('value="days" selected' in response.content)
# Test an out-of-range date range for a logged in user
user = self._login()
group = self._create_group_with_permission('run_long_queries')
user.groups.add(group)
response = self.client.get(url, {
'query': 'js::',
'range_unit': 'weeks',
'range_value': 9
})
eq_(response.status_code, 200)
# we're logged in, that works now
ok_('The maximum query date' not in response.content)
# ... but this doesn't
response = self.client.get(url, {
'query': 'js::',
'range_unit': 'weeks',
'range_value': 30
})
eq_(response.status_code, 200)
ok_('The maximum query date' in response.content)
# an admin won't see that message
ok_('Admins may log in' not in response.content)
ok_('name="range_value" value="%s"' % settings.QUERY_RANGE_DEFAULT_DAYS
in response.content)
ok_('value="days" selected' in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_query_pagination(self, rget, rpost):
def mocked_post(**options):
return Response('{"hits": [], "total": 0}')
def mocked_get(url, params, **options):
assert '/search/signatures' in url
response = ','.join('''
{
"count": %(x)s,
"signature": "sig%(x)s",
"numcontent": 0,
"is_windows": %(x)s,
"is_linux": 0,
"numplugin": 0,
"is_mac": 0,
"numhang": 0
}
''' % {'x': x} for x in range(150))
return Response('{"hits": [%s], "total": 150}' % response)
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
url = reverse('crashstats:query')
response = self.client.get(url, {'do_query': 1})
eq_(response.status_code, 200)
next_page_url = '%s?do_query=1&page=2' % url
ok_(next_page_url in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_query_summary(self, rget, rpost):
def mocked_post(**options):
return Response('{"hits": [], "total": 0}')
def mocked_get(url, params, **options):
return Response('{"hits": [], "total": 0}')
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
url = reverse('crashstats:query')
response = self.client.get(url, {
'query': 'test',
'query_type': 'contains'
})
eq_(response.status_code, 200)
ok_('Results within' in response.content)
ok_("crash signature contains 'test'" in response.content)
ok_('the crashing process was of any type' in response.content)
response = self.client.get(url, {
'query': 'test',
'query_type': 'is_exactly',
'build_id': '1234567890',
'product': ['WaterWolf', 'NightTrain'],
'version': ['WaterWolf:18.0'],
'platform': ['mac'],
'process_type': 'plugin',
'plugin_query_type': 'starts_with',
'plugin_query_field': 'filename',
'plugin_query': 'lib'
})
eq_(response.status_code, 200)
ok_('Results within' in response.content)
ok_("crash signature is exactly 'test'" in response.content)
ok_('product is one of WaterWolf, NightTrain' in response.content)
ok_('version is one of WaterWolf:18.0' in response.content)
ok_('platform is one of Mac OS X' in response.content)
ok_('for build 1234567890' in response.content)
ok_('the crashing process was a plugin' in response.content)
ok_('and its filename starts with lib' in response.content)
@override_settings(SEARCH_MIDDLEWARE_IMPL='elasticsearch')
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_query_force_impl_settings(self, rget, rpost):
def mocked_post(**options):
return Response('{"hits": [], "total": 0}')
def mocked_get(url, params, **options):
ok_('_force_api_impl' in params)
eq_('elasticsearch', params['_force_api_impl'])
return Response('{"hits": [], "total": 0}')
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
url = reverse('crashstats:query')
response = self.client.get(url, {
'do_query': 1,
})
eq_(response.status_code, 200)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_query_force_impl_url(self, rget, rpost):
def mocked_post(**options):
return Response('{"hits": [], "total": 0}')
def mocked_get(url, params, **options):
ok_('_force_api_impl' in params)
eq_('postgres', params['_force_api_impl'])
return Response('{"hits": [], "total": 0}')
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
url = reverse('crashstats:query')
response = self.client.get(url, {
'do_query': 1,
'_force_api_impl': 'postgres'
})
eq_(response.status_code, 200)
@override_settings(SEARCH_MIDDLEWARE_IMPL='mongodb')
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_query_force_impl_url_over_settings(self, rget, rpost):
def mocked_post(**options):
return Response('{"hits": [], "total": 0}')
def mocked_get(url, params, **options):
ok_('_force_api_impl' in params)
eq_('mysql', params['_force_api_impl'])
return Response('{"hits": [], "total": 0}')
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
url = reverse('crashstats:query')
response = self.client.get(url, {
'do_query': 1,
'_force_api_impl': 'mysql'
})
eq_(response.status_code, 200)
@mock.patch('requests.get')
def test_plot_signature(self, rget):
def mocked_get(url, params, **options):
if '/crashes/signature_history' in url:
return Response("""
{
"hits": [],
"total": 0
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
# missing signature
url = reverse('crashstats:plot_signature',
args=('WaterWolf', '19.0',
'2011-12-01', '2011-12-02', ''))
response = self.client.get(url)
eq_(response.status_code, 400)
# invalid start date
url = reverse('crashstats:plot_signature',
args=('WaterWolf', '19.0',
'2012-02-33', '2012-12-01',
'Read::Bytes'))
response = self.client.get(url)
eq_(response.status_code, 400)
# invalid end date
url = reverse('crashstats:plot_signature',
args=('WaterWolf', '19.0',
'2012-02-28', '2012-13-01',
'Read::Bytes'))
response = self.client.get(url)
eq_(response.status_code, 400)
# valid dates
url = reverse('crashstats:plot_signature',
args=('WaterWolf', '19.0',
'2011-12-01', '2011-12-02',
'Read::Bytes'))
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
ok_(struct['signature'])
@mock.patch('requests.get')
def test_explosive_view_without_explosives(self, rget):
url = reverse('crashstats:explosive')
def mocked_get(url, params, **options):
if '/suspicious' in url:
return Response("""
{"hits": [], "total": 0}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
resp = self.client.get(url)
eq_(resp.status_code, 200)
assert 'No explosive crashes found' in resp.content
@mock.patch('requests.get')
def test_explosive_view_with_explosives(self, rget):
url = reverse('crashstats:explosive')
def mocked_get(url, params, **options):
if '/suspicious' in url:
return Response("""
{"hits": [
{"date": "2013-09-01",
"signatures": ["signature1", "signature2"]
}
], "total": 1}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
resp = self.client.get(url)
eq_(resp.status_code, 200)
assert 'is explosive' in resp.content
@mock.patch('requests.get')
def test_explosive_data(self, rget):
url = reverse('crashstats:explosive_data',
args=('signature', '2013-03-05'))
def mocked_get(url, params, **options):
if '/crashes/count_by_day' in url:
return Response("""{
"hits": {
"2013-02-26": 100,
"2013-02-27": 100,
"2013-02-28": 100,
"2013-03-01": 100,
"2013-03-02": 100,
"2013-03-03": 100,
"2013-03-04": 100,
"2013-03-05": 100,
"2013-03-06": 100,
"2013-03-07": 100,
"2013-03-08": 100
}
}""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(url)
eq_(response.status_code, 200)
resp = json.loads(response.content)
ok_('counts' in resp)
# returns 11 days of data since we are after it.
# the first day is 7 days prior, the last is 3 days after.
eq_(len(resp['counts']), 11)
eq_(resp['counts'][0][0], '2013-02-26')
eq_(resp['counts'][0][1], 100)
eq_(resp['counts'][-1][0], '2013-03-08')
eq_(resp['counts'][-1][1], 100)
@mock.patch('requests.get')
def test_explosive_data_today(self, rget):
now = datetime.datetime.utcnow()
start = now - datetime.timedelta(10)
now = now.strftime('%Y-%m-%d')
start = start.strftime('%Y-%m-%d')
url = reverse('crashstats:explosive_data', args=('signature', now))
def mocked_get(url, params, **options):
if '/crashes/count_by_day' in url:
dates = []
current = datetime.datetime.strptime(start, "%Y-%m-%d")
end = datetime.datetime.strptime(now, "%Y-%m-%d")
while current <= end:
dates.append(current.strftime("%Y-%m-%d"))
current += datetime.timedelta(1)
return Response("""{
"hits": {
"%s": 100,
"%s": 100,
"%s": 100,
"%s": 100,
"%s": 100,
"%s": 100,
"%s": 100,
"%s": 100,
"%s": 100,
"%s": 100,
"%s": 100
}
}""" % tuple(dates))
rget.side_effect = mocked_get
response = self.client.get(url)
eq_(response.status_code, 200)
resp = json.loads(response.content)
eq_(resp['counts'][0][0], start)
eq_(resp['counts'][0][1], 100)
eq_(resp['counts'][-1][0], now)
eq_(resp['counts'][-1][1], 100)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_topchangers(self, rget, rpost):
url = reverse('crashstats:topchangers',
args=('WaterWolf', '19.0'))
bad_url = reverse('crashstats:topchangers',
args=('SeaMonkey', '19.0'))
bad_url2 = reverse('crashstats:topchangers',
args=('WaterWolf', '19.999'))
url_wo_version = reverse('crashstats:topchangers',
args=('WaterWolf',))
def mocked_post(**options):
assert 'by=signatures' in options['url'], options['url']
return Response("""
{"bug_associations": [{"bug_id": "123456789",
"signature": "Something"}]}
""")
def mocked_get(url, params, **options):
if '/crashes/signatures' in url:
return Response("""
{"crashes": [
{
"count": 188,
"mac_count": 66,
"content_count": 0,
"first_report": "2012-06-21",
"startup_percent": 0.0,
"currentRank": 0,
"previousRank": 1,
"first_report_exact": "2012-06-21T21:28:08",
"versions":
"2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1",
"percentOfTotal": 0.24258064516128999,
"win_count": 56,
"changeInPercentOfTotal": 0.011139597126354983,
"linux_count": 66,
"hang_count": 0,
"signature": "FakeSignature1",
"versions_count": 8,
"changeInRank": 0,
"plugin_count": 0,
"previousPercentOfTotal": 0.23144104803493501,
"is_gc_count": 10
}
],
"totalPercentage": 0,
"start_date": "2012-05-10",
"end_date": "2012-05-24",
"totalNumberOfCrashes": 0}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
response = self.client.get(url_wo_version)
eq_(response.status_code, 200)
# invalid version for the product name
response = self.client.get(bad_url)
eq_(response.status_code, 404)
# invalid version for the product name
response = self.client.get(bad_url2)
eq_(response.status_code, 404)
response = self.client.get(url)
eq_(response.status_code, 200)
def test_topchangers_without_versions_redirect(self):
response = self.client.get('/topchangers/products/WaterWolf/versions/')
redirect_code = settings.PERMANENT_LEGACY_REDIRECTS and 301 or 302
eq_(response.status_code, redirect_code)
actual_url = reverse('crashstats:topchangers',
kwargs={'product': 'WaterWolf'})
ok_(response['location'].endswith(actual_url))
@mock.patch('requests.get')
def test_signature_summary(self, rget):
def mocked_get(url, params, **options):
if '/signaturesummary' in url:
assert params['report_types']
return Response({
"reports": {
"products": [
{
"version_string": "33.0a2",
"percentage": "57.542",
"report_count": 103,
"product_name": "Firefox"
},
],
"uptime": [
{
"category": "< 1 min",
"percentage": "29.126",
"report_count": 30
}
],
"architecture": [
{
"category": "x86",
"percentage": "100.000",
"report_count": 103
}
],
"flash_version": [
{
"category": "[blank]",
"percentage": "100.000",
"report_count": 103
}
],
"graphics": [
{
"report_count": 24,
"adapter_name": None,
"vendor_hex": "0x8086",
"percentage": "23.301",
"vendor_name": None,
"adapter_hex": "0x0166"
}
],
"distinct_install": [
{
"crashes": 103,
"version_string": "33.0a2",
"product_name": "Firefox",
"installations": 59
}
],
"devices": [
{
"cpu_abi": "XXX",
"manufacturer": "YYY",
"model": "ZZZ",
"version": "1.2.3",
"report_count": 52311,
"percentage": "48.440",
}
],
"os": [
{
"category": "Windows 8.1",
"percentage": "55.340",
"report_count": 57
}
],
"process_type": [
{
"category": "Browser",
"percentage": "100.000",
"report_count": 103
}
],
"exploitability": [
{
"low_count": 0,
"high_count": 0,
"null_count": 0,
"none_count": 4,
"report_date": "2014-08-12",
"medium_count": 0
}
]
}
})
raise NotImplementedError(url)
url = reverse('crashstats:signature_summary')
rget.side_effect = mocked_get
# first try without the necessary parameters
response = self.client.get(url)
eq_(response.status_code, 400)
response = self.client.get(url, {
'range_value': '1',
'signature': 'sig',
'version': 'WaterWolf:19.0'
})
eq_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
ok_(struct['architectures'])
ok_(struct['flashVersions'])
ok_(struct['percentageByOs'])
ok_(struct['processTypes'])
ok_(struct['productVersions'])
ok_(struct['uptimeRange'])
ok_(struct['distinctInstall'])
ok_(struct['devices'])
ok_(struct['graphics'])
ok_(not struct['canViewExploitability'])
ok_('exploitabilityScore' not in struct)
# percentages are turned into string as they're fed straight into
# a mustache template.
# for example,
eq_(struct['uptimeRange'][0]['percentage'], '29.13')
user = self._login()
group = self._create_group_with_permission('view_exploitability')
user.groups.add(group)
response = self.client.get(url, {'range_value': '1',
'signature': 'sig',
'version': 'WaterWolf:19.0'})
eq_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
ok_(struct['canViewExploitability'])
ok_(struct['exploitabilityScore'])
@mock.patch('requests.get')
def test_signature_summary_flash_exploitability(self, rget):
def mocked_get(url, params, **options):
signature_summary_data = copy.deepcopy(SAMPLE_SIGNATURE_SUMMARY)
if '/signaturesummary' in url:
if 'sig1' in params['signature']:
signature_summary_data['reports']['flash_version'] = [
{
"category": "11.9.900.117",
"percentage": "50.794",
"report_count": 320
},
{
"category": "11.9.900.152",
"percentage": "45.397",
"report_count": 286
},
{
"category": "11.7.700.224",
"percentage": "1.429",
"report_count": 9
}
]
elif 'sig2' in params['signature']:
signature_summary_data['reports']['flash_version'] = [
{
"category": "11.9.900.117",
"percentage": "50.794",
"report_count": 320
},
{
"category": "[blank]",
"percentage": "45.397",
"report_count": 286
},
{
"category": "11.7.700.224",
"percentage": "1.429",
"report_count": 9
}
]
return Response(signature_summary_data)
raise NotImplementedError(url)
url = reverse('crashstats:signature_summary')
rget.side_effect = mocked_get
user = self._login()
group = self._create_group_with_permission('view_flash_exploitability')
user.groups.add(group)
response = self.client.get(url, {
'range_value': '1',
'signature': 'sig1',
'version': 'WaterWolf:19.0'
})
eq_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
ok_(struct['canViewExploitability'])
ok_(struct['exploitabilityScore'])
response = self.client.get(url, {'range_value': '1',
'signature': 'sig2', # different
'version': 'WaterWolf:19.0'})
eq_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
ok_(not struct['canViewExploitability'])
ok_('exploitabilityScore' not in struct)
@mock.patch('requests.get')
def test_status(self, rget):
def mocked_get(url, **options):
assert '/server_status' in url, url
return Response(SAMPLE_STATUS)
rget.side_effect = mocked_get
url = reverse('crashstats:status')
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('schema_12345' in response.content)
ok_('017d7b3f7042ce76bc80949ae55b41d1e915ab62' in response.content)
ok_('1035' in response.content)
ok_('Sep 28 2012 20:30:01' in response.content)
@mock.patch('requests.get')
def test_status_revision(self, rget):
def mocked_get(url, **options):
assert '/server_status' in url, url
return Response(SAMPLE_STATUS)
rget.side_effect = mocked_get
url = reverse('crashstats:status_revision')
response = self.client.get(url)
eq_(response.status_code, 200)
eq_(response.content, '017d7b3f7042ce76bc80949ae55b41d1e915ab62')
ok_('text/plain' in response['content-type'])
def test_login_required(self):
url = reverse(
'crashstats:exploitable_crashes',
args=(settings.DEFAULT_PRODUCT,)
)
response = self.client.get(url)
eq_(response.status_code, 302)
ok_(settings.LOGIN_URL in response['Location'] + '?next=%s' % url)
@mock.patch('requests.get')
def test_status_json(self, rget):
def mocked_get(**options):
assert '/server_status' in options['url'], options['url']
return Response(SAMPLE_STATUS)
rget.side_effect = mocked_get
url = reverse('crashstats:status_json')
response = self.client.get(url)
eq_(response.status_code, 200)
ok_(response.content.strip().startswith('{'))
ok_('017d7b3f7042ce76bc80949ae55b41d1e915ab62' in response.content)
ok_('1035' in response.content)
ok_('2012-09-28T20:30:01+00:00' in response.content)
ok_('application/json' in response['Content-Type'])
eq_('*', response['Access-Control-Allow-Origin'])
def test_crontabber_state(self):
url = reverse('crashstats:crontabber_state')
response = self.client.get(url)
eq_(response.status_code, 200)
@mock.patch('requests.get')
def test_your_crashes(self, rget):
url = reverse('crashstats:your_crashes')
def mocked_get(url, params, **options):
assert '/supersearch/' in url
if '/supersearch/fields/' in url:
return Response({
'email': {
'name': 'email',
'query_type': 'string',
'namespace': 'processed_crash',
'form_field_choices': None,
'permissions_needed': ['crashstats.view_pii'],
'default_value': None,
'is_exposed': True,
'is_returned': True,
'is_mandatory': False,
}
})
assert 'email' in params
assert params['email'] == ['[email protected]']
return Response({
'hits': [
{
'uuid': '1234abcd-ef56-7890-ab12-abcdef130801',
'date': '2000-01-01T00:00:00'
},
{
'uuid': '1234abcd-ef56-7890-ab12-abcdef130802',
'date': '2000-01-02T00:00:00'
}
],
'total': 2
})
rget.side_effect = mocked_get
# A user needs to be signed in to see this page.
response = self.client.get(url)
eq_(response.status_code, 302)
self.assertRedirects(
response,
reverse('crashstats:login') + '?next=%s' % url
)
self._login()
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('1234abcd-ef56-7890-ab12-abcdef130801' in response.content)
ok_('1234abcd-ef56-7890-ab12-abcdef130802' in response.content)
ok_('[email protected]' in response.content)
@mock.patch('requests.get')
def test_your_crashes_no_data(self, rget):
url = reverse('crashstats:your_crashes')
def mocked_get(url, params, **options):
assert '/supersearch/' in url
if '/supersearch/fields/' in url:
return Response({
'email': {
'name': 'email',
'query_type': 'string',
'namespace': 'processed_crash',
'form_field_choices': None,
'permissions_needed': ['crashstats.view_pii'],
'default_value': None,
'is_exposed': True,
'is_returned': True,
'is_mandatory': False,
}
})
assert 'email' in params
assert params['email'] == ['[email protected]']
return Response({
'hits': [],
'total': 0
})
rget.side_effect = mocked_get
self._login()
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('[email protected]' in response.content)
ok_('no crash report' in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index(self, rget, rpost):
# using \\n because it goes into the JSON string
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
comment0 = "This is a comment\\nOn multiple lines"
comment0 += "\\[email protected]"
comment0 += "\\nwww.p0rn.com"
email0 = "[email protected]"
url0 = "someaddress.com"
def mocked_get(url, params, **options):
if '/crash_data' in url:
assert 'datatype' in params
if params['datatype'] == 'meta':
return Response(SAMPLE_META % (email0, url0))
if params['datatype'] == 'unredacted':
return Response(SAMPLE_UNREDACTED % (
dump,
comment0
))
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response(BUG_STATUS)
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120611'])
response = self.client.get(url)
eq_(response.status_code, 200)
# which bug IDs appear is important and the order matters too
ok_(
-1 ==
response.content.find('444444') <
response.content.find('333333') <
response.content.find('222222')
)
ok_('FakeSignature1' in response.content)
ok_('11cb72f5-eb28-41e1-a8e4-849982120611' in response.content)
comment_transformed = (
comment0
.replace('\\n', '<br>')
.replace('[email protected]', '(email removed)')
.replace('www.p0rn.com', '(URL removed)')
)
ok_(comment_transformed in response.content)
# but the email should have been scrubbed
ok_('[email protected]' not in response.content)
ok_(email0 not in response.content)
ok_(url0 not in response.content)
ok_(
'You need to be signed in to be able to download raw dumps.'
in response.content
)
# Should not be able to see sensitive key from stackwalker JSON
ok_('"sensitive"' not in response.content)
ok_('"exploitability"' not in response.content)
# the email address will appear if we log in
user = self._login()
group = self._create_group_with_permission('view_pii')
user.groups.add(group)
assert user.has_perm('crashstats.view_pii')
response = self.client.get(url)
ok_('[email protected]' in response.content)
ok_(email0 in response.content)
ok_(url0 in response.content)
ok_('"sensitive"' in response.content)
ok_('"exploitability"' in response.content)
eq_(response.status_code, 200)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_with_additional_raw_dump_links(self, rget, rpost):
# using \\n because it goes into the JSON string
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
def mocked_get(url, params, **options):
if '/crash_data' in url:
assert 'datatype' in params
if params['datatype'] == 'meta':
return Response({
"InstallTime": "1339289895",
"FramePoisonSize": "4096",
"Theme": "classic/1.0",
"Version": "5.0a1",
"Email": "[email protected]",
"Vendor": "Mozilla",
"URL": "farmville.com",
"additional_minidumps": "foo, bar,",
})
if params['datatype'] == 'unredacted':
return Response({
"client_crash_date": "2012-06-11T06:08:45",
"dump": dump,
"signature": "FakeSignature1",
"user_comments": None,
"uptime": 14693,
"release_channel": "nightly",
"uuid": "11cb72f5-eb28-41e1-a8e4-849982120611",
"flash_version": "[blank]",
"hangid": None,
"distributor_version": None,
"truncated": True,
"process_type": None,
"id": 383569625,
"os_version": "10.6.8 10K549",
"version": "5.0a1",
"build": "20120609030536",
"ReleaseChannel": "nightly",
"addons_checked": None,
"product": "WaterWolf",
"os_name": "Mac OS X",
"last_crash": 371342,
"date_processed": "2012-06-11T06:08:44",
"cpu_name": "amd64",
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"address": "0x8",
"completeddatetime": "2012-06-11T06:08:57",
"success": True,
"exploitability": "Unknown Exploitability"
})
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response(BUG_STATUS)
raise NotImplementedError(url)
rpost.side_effect = mocked_post
crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611'
url = reverse('crashstats:report_index', args=(crash_id,))
response = self.client.get(url)
eq_(response.status_code, 200)
# first of all, expect these basic URLs
raw_json_url = reverse('crashstats:raw_data', args=(crash_id, 'json'))
raw_dmp_url = reverse('crashstats:raw_data', args=(crash_id, 'dmp'))
# not quite yet
ok_(raw_json_url not in response.content)
ok_(raw_dmp_url not in response.content)
user = self._login()
response = self.client.get(url)
eq_(response.status_code, 200)
# still they don't appear
ok_(raw_json_url not in response.content)
ok_(raw_dmp_url not in response.content)
group = self._create_group_with_permission('view_rawdump')
user.groups.add(group)
response = self.client.get(url)
eq_(response.status_code, 200)
# finally they appear
ok_(raw_json_url in response.content)
ok_(raw_dmp_url in response.content)
# also, check that the other links are there
foo_dmp_url = reverse(
'crashstats:raw_data_named',
args=(crash_id, 'upload_file_minidump_foo', 'dmp')
)
ok_(foo_dmp_url in response.content)
bar_dmp_url = reverse(
'crashstats:raw_data_named',
args=(crash_id, 'upload_file_minidump_bar', 'dmp')
)
ok_(bar_dmp_url in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_fennecandroid_report(self, rget, rpost):
# using \\n because it goes into the JSON string
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
comment0 = "This is a comment\\nOn multiple lines"
comment0 += "\\[email protected]"
comment0 += "\\nwww.p0rn.com"
email0 = "[email protected]"
url0 = "someaddress.com"
def mocked_get(url, params, **options):
if '/crash_data' in url:
assert 'datatype' in params
if params['datatype'] == 'meta':
return Response(SAMPLE_META % (email0, url0))
if params['datatype'] == 'unredacted':
raw_crash_json = SAMPLE_UNREDACTED % (
dump,
comment0
)
raw_crash_json = json.loads(raw_crash_json)
raw_crash_json['product'] = 'WinterSun'
return Response(raw_crash_json)
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response(BUG_STATUS)
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120611'])
bug_product_map = {
'WinterSun': 'Winter Is Coming'
}
with self.settings(BUG_PRODUCT_MAP=bug_product_map):
response = self.client.get(url)
eq_(response.status_code, 200)
doc = pyquery.PyQuery(response.content)
link = doc('#bugzilla a[target="_blank"]').eq(0)
eq_(link.text(), 'Winter Is Coming')
ok_('product=Winter+Is+Coming' in link.attr('href'))
# also, the "More Reports" link should have WinterSun in it
link = doc('a.sig-overview').eq(0)
ok_('product=WinterSun' in link.attr('href'))
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_odd_product_and_version(self, rget, rpost):
"""If the processed JSON references an unfamiliar product and
version it should not use that to make links in the nav to
reports for that unfamiliar product and version."""
# using \\n because it goes into the JSON string
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
comment0 = "This is a comment\\nOn multiple lines"
comment0 += "\\[email protected]"
comment0 += "\\nwww.p0rn.com"
email0 = "[email protected]"
url0 = "someaddress.com"
def mocked_get(url, params, **options):
if '/crash_data' in url:
assert 'datatype' in params
if params['datatype'] == 'meta':
return Response(SAMPLE_META % (email0, url0))
if params['datatype'] == 'unredacted':
processed_json = SAMPLE_UNREDACTED % (dump, comment0)
assert '"WaterWolf"' in processed_json
assert '"5.0a1"' in processed_json
processed_json = processed_json.replace(
'"WaterWolf"', '"SummerWolf"'
)
processed_json = processed_json.replace(
'"5.0a1"', '"99.9"'
)
return Response(processed_json)
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response(BUG_STATUS)
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120611'])
response = self.client.get(url)
eq_(response.status_code, 200)
# the title should have the "SummerWolf 99.9" in it
doc = pyquery.PyQuery(response.content)
title = doc('title').text()
ok_('SummerWolf' in title)
ok_('99.9' in title)
# there shouldn't be any links to reports for the product
# mentioned in the processed JSON
bad_url = reverse('crashstats:home', args=('SummerWolf',))
ok_(bad_url not in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_correlations_failed(self, rget, rpost):
# using \\n because it goes into the JSON string
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
comment0 = "This is a comment"
email0 = "[email protected]"
url0 = "someaddress.com"
def mocked_get(url, params, **options):
if '/crash_data' in url:
assert 'datatype' in params
if params['datatype'] == 'meta':
return Response(SAMPLE_META % (email0, url0))
if params['datatype'] == 'unredacted':
return Response(SAMPLE_UNREDACTED % (
dump,
comment0
))
if 'correlations/signatures' in url:
raise models.BadStatusCodeError(500)
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response(BUG_STATUS)
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120611'])
response = self.client.get(url)
eq_(response.status_code, 200)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_no_dump(self, rget, rpost):
dump = ""
comment0 = "This is a comment"
email0 = "[email protected]"
url0 = "someaddress.com"
def mocked_get(url, params, **options):
if '/crash_data' in url:
assert 'datatype' in params
if params['datatype'] == 'meta':
return Response(SAMPLE_META % (email0, url0))
if params['datatype'] == 'unredacted':
data = json.loads(
SAMPLE_UNREDACTED % (dump, comment0)
)
del data['dump']
del data['json_dump']
return Response(data)
if 'correlations/signatures' in url:
raise models.BadStatusCodeError(500)
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response(BUG_STATUS)
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120611'])
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('No dump available' in response.content)
def test_report_index_invalid_crash_id(self):
# last 6 digits indicate 30th Feb 2012 which doesn't exist
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120230'])
response = self.client.get(url)
eq_(response.status_code, 400)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_pending_today(self, rget, rpost):
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
raise models.BadStatusCodeError(404)
rget.side_effect = mocked_get
today = datetime.datetime.utcnow().strftime('%y%m%d')
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982%s' % today])
response = self.client.get(url)
ok_('pendingStatus' in response.content)
eq_(response.status_code, 200)
yesterday = datetime.datetime.utcnow() - datetime.timedelta(days=1)
yesterday = yesterday.strftime('%y%m%d')
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982%s' % yesterday])
response = self.client.get(url)
ok_('Crash Not Found' in response.content)
eq_(response.status_code, 200)
url = reverse('crashstats:report_index',
args=['blablabla'])
response = self.client.get(url)
eq_(response.status_code, 400)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_with_hangid_in_raw_data(self, rget, rpost):
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
comment0 = "This is a comment"
email0 = "[email protected]"
url0 = "someaddress.com"
email1 = "[email protected]"
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'meta'
):
return Response("""
{
"InstallTime": "1339289895",
"FramePoisonSize": "4096",
"Theme": "classic/1.0",
"Version": "5.0a1",
"Email": "%s",
"Vendor": "Mozilla",
"URL": "%s",
"HangID": "123456789"
}
""" % (email0, url0))
if '/crashes/paireduuid' in url:
return Response("""
{
"hits": [{
"uuid": "e8820616-1462-49b6-9784-e99a32120201"
}],
"total": 1
}
""")
if 'crashes/comments' in url:
return Response("""
{
"hits": [
{
"user_comments": "%s",
"date_processed": "2012-08-21T11:17:28-07:00",
"email": "%s",
"uuid": "469bde48-0e8f-3586-d486-b98810120830"
}
],
"total": 1
}
""" % (comment0, email1))
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
return Response("""
{
"client_crash_date": "2012-06-11T06:08:45",
"dump": "%s",
"signature": "FakeSignature1",
"user_comments": null,
"uptime": 14693,
"release_channel": "nightly",
"uuid": "11cb72f5-eb28-41e1-a8e4-849982120611",
"flash_version": "[blank]",
"hangid": null,
"distributor_version": null,
"truncated": true,
"process_type": null,
"id": 383569625,
"os_version": "10.6.8 10K549",
"version": "5.0a1",
"build": "20120609030536",
"ReleaseChannel": "nightly",
"addons_checked": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"last_crash": 371342,
"date_processed": "2012-06-11T06:08:44",
"cpu_name": "amd64",
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"address": "0x8",
"completeddatetime": "2012-06-11T06:08:57",
"success": true,
"exploitability": "Unknown Exploitability"
}
""" % dump)
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response("""
{"hits": [{"id": "123456789",
"signature": "Something"}]}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120611'])
response = self.client.get(url)
ok_('Hang Minidump' in response.content)
# the HangID in the fixture above
ok_('123456789' in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_with_invalid_InstallTime(self, rget, rpost):
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
comment0 = "This is a comment"
email0 = "[email protected]"
url0 = "someaddress.com"
email1 = "[email protected]"
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'meta'
):
return Response("""
{
"InstallTime": "Not a number",
"FramePoisonSize": "4096",
"Theme": "classic/1.0",
"Version": "5.0a1",
"Email": "%s",
"Vendor": "Mozilla",
"URL": "%s",
"HangID": "123456789"
}
""" % (email0, url0))
if '/crashes/paireduuid' in url:
return Response("""
{
"hits": [{
"uuid": "e8820616-1462-49b6-9784-e99a32120201"
}],
"total": 1
}
""")
if 'crashes/comments' in url:
return Response("""
{
"hits": [
{
"user_comments": "%s",
"date_processed": "2012-08-21T11:17:28-07:00",
"email": "%s",
"uuid": "469bde48-0e8f-3586-d486-b98810120830"
}
],
"total": 1
}
""" % (comment0, email1))
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
return Response("""
{
"client_crash_date": "2012-06-11T06:08:45",
"dump": "%s",
"signature": "FakeSignature1",
"user_comments": null,
"uptime": 14693,
"release_channel": "nightly",
"uuid": "11cb72f5-eb28-41e1-a8e4-849982120611",
"flash_version": "[blank]",
"hangid": null,
"distributor_version": null,
"truncated": true,
"process_type": null,
"id": 383569625,
"os_version": "10.6.8 10K549",
"version": "5.0a1",
"build": "20120609030536",
"ReleaseChannel": "nightly",
"addons_checked": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"last_crash": 371342,
"date_processed": "2012-06-11T06:08:44",
"cpu_name": "amd64",
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"address": "0x8",
"completeddatetime": "2012-06-11T06:08:57",
"success": true,
"exploitability": "Unknown Exploitability"
}
""" % dump)
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response("""
{"hits": [{"id": "123456789",
"signature": "Something"}]}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120611'])
response = self.client.get(url)
ok_('<th>Install Time</th>' not in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_with_invalid_parsed_dump(self, rget, rpost):
json_dump = {
u'crash_info': {
u'address': u'0x88',
u'type': u'EXCEPTION_ACCESS_VIOLATION_READ'
},
u'main_module': 0,
u'modules': [
{
u'base_addr': u'0x980000',
u'debug_file': u'FlashPlayerPlugin.pdb',
u'debug_id': u'5F3C0D3034CA49FE9B94FC97EBF590A81',
u'end_addr': u'0xb4d000',
u'filename': u'FlashPlayerPlugin_13_0_0_214.exe',
u'version': u'13.0.0.214'},
],
u'sensitive': {u'exploitability': u'none'},
u'status': u'OK',
u'system_info': {
u'cpu_arch': u'x86',
u'cpu_count': 8,
u'cpu_info': u'GenuineIntel family 6 model 26 stepping 4',
u'os': u'Windows NT',
u'os_ver': u'6.0.6002 Service Pack 2'
},
u'thread_count': 1,
u'threads': [{u'frame_count': 0, u'frames': []}]
}
comment0 = "This is a comment"
email0 = "[email protected]"
url0 = "someaddress.com"
email1 = "[email protected]"
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'meta'
):
return Response("""
{
"InstallTime": "Not a number",
"FramePoisonSize": "4096",
"Theme": "classic/1.0",
"Version": "5.0a1",
"Email": "%s",
"Vendor": "Mozilla",
"URL": "%s",
"HangID": "123456789"
}
""" % (email0, url0))
if '/crashes/paireduuid' in url:
return Response("""
{
"hits": [{
"uuid": "e8820616-1462-49b6-9784-e99a32120201"
}],
"total": 1
}
""")
if 'crashes/comments' in url:
return Response("""
{
"hits": [
{
"user_comments": "%s",
"date_processed": "2012-08-21T11:17:28-07:00",
"email": "%s",
"uuid": "469bde48-0e8f-3586-d486-b98810120830"
}
],
"total": 1
}
""" % (comment0, email1))
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
return Response("""
{
"client_crash_date": "2012-06-11T06:08:45",
"json_dump": %s,
"signature": "FakeSignature1",
"user_comments": null,
"uptime": 14693,
"release_channel": "nightly",
"uuid": "11cb72f5-eb28-41e1-a8e4-849982120611",
"flash_version": "[blank]",
"hangid": null,
"distributor_version": null,
"truncated": true,
"process_type": null,
"id": 383569625,
"os_version": "10.6.8 10K549",
"version": "5.0a1",
"build": "20120609030536",
"ReleaseChannel": "nightly",
"addons_checked": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"last_crash": 371342,
"date_processed": "2012-06-11T06:08:44",
"cpu_name": "amd64",
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"address": "0x8",
"completeddatetime": "2012-06-11T06:08:57",
"success": true,
"exploitability": "Unknown Exploitability"
}
""" % json.dumps(json_dump))
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response("""
{"hits": [{"id": "123456789",
"signature": "Something"}]}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120611'])
response = self.client.get(url)
ok_('<th>Install Time</th>' not in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_with_sparse_json_dump(self, rget, rpost):
json_dump = {u'status': u'ERROR_NO_MINIDUMP_HEADER', u'sensitive': {}}
comment0 = "This is a comment"
email0 = "[email protected]"
url0 = "someaddress.com"
email1 = "[email protected]"
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'meta'
):
return Response("""
{
"InstallTime": "Not a number",
"FramePoisonSize": "4096",
"Theme": "classic/1.0",
"Version": "5.0a1",
"Email": "%s",
"Vendor": "Mozilla",
"URL": "%s",
"HangID": "123456789"
}
""" % (email0, url0))
if '/crashes/paireduuid' in url:
return Response("""
{
"hits": [{
"uuid": "e8820616-1462-49b6-9784-e99a32120201"
}],
"total": 1
}
""")
if 'crashes/comments' in url:
return Response("""
{
"hits": [
{
"user_comments": "%s",
"date_processed": "2012-08-21T11:17:28-07:00",
"email": "%s",
"uuid": "469bde48-0e8f-3586-d486-b98810120830"
}
],
"total": 1
}
""" % (comment0, email1))
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
return Response("""
{
"client_crash_date": "2012-06-11T06:08:45",
"json_dump": %s,
"signature": "FakeSignature1",
"user_comments": null,
"uptime": 14693,
"release_channel": "nightly",
"uuid": "11cb72f5-eb28-41e1-a8e4-849982120611",
"flash_version": "[blank]",
"hangid": null,
"distributor_version": null,
"truncated": true,
"process_type": null,
"id": 383569625,
"os_version": "10.6.8 10K549",
"version": "5.0a1",
"build": "20120609030536",
"ReleaseChannel": "nightly",
"addons_checked": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"last_crash": 371342,
"date_processed": "2012-06-11T06:08:44",
"cpu_name": "amd64",
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"address": "0x8",
"completeddatetime": "2012-06-11T06:08:57",
"success": true,
"exploitability": "Unknown Exploitability"
}
""" % json.dumps(json_dump))
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response("""
{"hits": [{"id": "123456789",
"signature": "Something"}]}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=['11cb72f5-eb28-41e1-a8e4-849982120611'])
response = self.client.get(url)
eq_(response.status_code, 200)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_with_crash_exploitability(self, rget, rpost):
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
comment0 = "This is a comment"
email0 = "[email protected]"
url0 = "someaddress.com"
email1 = "[email protected]"
crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611'
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'meta'
):
return Response("""
{
"InstallTime": "Not a number",
"FramePoisonSize": "4096",
"Theme": "classic/1.0",
"Version": "5.0a1",
"Email": "%s",
"Vendor": "Mozilla",
"URL": "%s",
"HangID": "123456789"
}
""" % (email0, url0))
if '/crashes/paireduuid' in url:
return Response("""
{
"hits": [{
"uuid": "e8820616-1462-49b6-9784-e99a32120201"
}],
"total": 1
}
""")
if '/crashes/comments' in url:
return Response("""
{
"hits": [
{
"user_comments": "%s",
"date_processed": "2012-08-21T11:17:28-07:00",
"email": "%s",
"uuid": "469bde48-0e8f-3586-d486-b98810120830"
}
],
"total": 1
}
""" % (comment0, email1))
if '/correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
return Response("""
{
"client_crash_date": "2012-06-11T06:08:45",
"dump": "%s",
"signature": "FakeSignature1",
"user_comments": null,
"uptime": 14693,
"release_channel": "nightly",
"uuid": "11cb72f5-eb28-41e1-a8e4-849982120611",
"flash_version": "[blank]",
"hangid": null,
"distributor_version": null,
"truncated": true,
"process_type": null,
"id": 383569625,
"os_version": "10.6.8 10K549",
"version": "5.0a1",
"build": "20120609030536",
"ReleaseChannel": "nightly",
"addons_checked": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"last_crash": 371342,
"date_processed": "2012-06-11T06:08:44",
"cpu_name": "amd64",
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"address": "0x8",
"completeddatetime": "2012-06-11T06:08:57",
"success": true,
"exploitability": "Unknown Exploitability"
}
""" % dump)
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response("""
{"hits": [{"id": "123456789",
"signature": "Something"}]}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index', args=[crash_id])
response = self.client.get(url)
ok_('Exploitability</th>' not in response.content)
# you must be signed in to see exploitability
user = self._login()
group = self._create_group_with_permission('view_exploitability')
user.groups.add(group)
response = self.client.get(url)
ok_('Exploitability</th>' in response.content)
ok_('Unknown Exploitability' in response.content)
@mock.patch('requests.get')
def test_report_index_processed_crash_not_found(self, rget):
crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611'
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
raise models.BadStatusCodeError(404)
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_index',
args=[crash_id])
response = self.client.get(url)
eq_(response.status_code, 200)
ok_("Crash Not Found" in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_raw_crash_not_found(self, rget, rpost):
crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611'
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
def mocked_get(url, params, **options):
assert '/crash_data/' in url
assert 'datatype' in params
if params['datatype'] == 'unredacted':
return Response("""
{
"client_crash_date": "2012-06-11T06:08:45",
"dump": "%s",
"signature": "FakeSignature1",
"user_comments": null,
"uptime": 14693,
"release_channel": "nightly",
"uuid": "11cb72f5-eb28-41e1-a8e4-849982120611",
"flash_version": "[blank]",
"hangid": null,
"distributor_version": null,
"truncated": true,
"process_type": null,
"id": 383569625,
"os_version": "10.6.8 10K549",
"version": "5.0a1",
"build": "20120609030536",
"ReleaseChannel": "nightly",
"addons_checked": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"last_crash": 371342,
"date_processed": "2012-06-11T06:08:44",
"cpu_name": "amd64",
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"address": "0x8",
"completeddatetime": "2012-06-11T06:08:57",
"success": true,
"exploitability": "Unknown Exploitability"
}
""" % dump)
elif params['datatype'] == 'meta': # raw crash json!
raise models.BadStatusCodeError(404)
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response("""
{"hits": [{"id": "123456789",
"signature": "Something"}]}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_index',
args=[crash_id])
response = self.client.get(url)
eq_(response.status_code, 200)
ok_("Crash Not Found" in response.content)
@mock.patch('requests.get')
def test_report_index_pending(self, rget):
crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611'
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
raise models.BadStatusCodeError(408)
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_index',
args=[crash_id])
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('Fetching this archived report' in response.content)
@mock.patch('requests.get')
def test_report_index_too_old(self, rget):
crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611'
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
raise models.BadStatusCodeError(410)
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_index',
args=[crash_id])
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('This archived report has expired' in response.content)
@mock.patch('requests.get')
def test_report_index_other_error(self, rget):
crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611'
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
return Response('Scary Error', status_code=500)
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_index',
args=[crash_id])
assert_raises(
models.BadStatusCodeError,
self.client.get,
url
)
# Let's also check that we get the response in the exception
# message.
try:
self.client.get(url)
assert False # shouldn't get here
except models.BadStatusCodeError as exception:
ok_('Scary Error' in str(exception))
# and it should include the URL it used
mware_url = models.UnredactedCrash.base_url + '/crash_data/'
ok_(mware_url in str(exception))
@mock.patch('requests.get')
def test_report_pending_json(self, rget):
crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611'
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
raise models.BadStatusCodeError(408)
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_pending',
args=[crash_id])
response = self.client.get(url)
expected = {
'status': 'error',
'status_message': ('The report for %s'
' is not available yet.' % crash_id),
'url_redirect': ''
}
eq_(response.status_code, 200)
eq_(expected, json.loads(response.content))
def test_report_index_and_pending_missing_crash_id(self):
url = reverse('crashstats:report_index', args=[''])
response = self.client.get(url)
eq_(response.status_code, 404)
url = reverse('crashstats:report_pending', args=[''])
response = self.client.get(url)
eq_(response.status_code, 404)
def test_report_list(self):
url = reverse('crashstats:report_list')
response = self.client.get(url)
eq_(response.status_code, 400)
response = self.client.get(url, {
'signature': 'sig',
'range_value': 'xxx'
})
eq_(response.status_code, 400)
response = self.client.get(url, {'signature': 'sig'})
eq_(response.status_code, 200)
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
ok_('Crash Reports for sig' in response.content)
def test_report_list_all_link(self):
url = reverse('crashstats:report_list')
sig = 'js::jit::EnterBaselineMethod(JSContext*, js::RunState&)'
response = self.client.get(url, {
'product': 'WaterWolf',
'signature': sig
})
eq_(response.status_code, 200)
doc = pyquery.PyQuery(response.content)
for link in doc('a'):
if link.text and 'View ALL' in link.text:
ok_(urllib.quote_plus(sig) in link.attrib['href'])
def test_report_list_columns_offered(self):
url = reverse('crashstats:report_list')
response = self.client.get(url, {'signature': 'sig'})
eq_(response.status_code, 200)
# The "user_comments" field is a choice
ok_('<option value="user_comments">' in response.content)
# The "URL" field is not a choice
ok_('<option value="URL">' not in response.content)
# also, all fields in models.RawCrash.API_WHITELIST should
# be there
for field in models.RawCrash.API_WHITELIST:
html = '<option value="%s">' % field
ok_(html in response.content)
# but it's different if you're logged in
user = self._login()
group = self._create_group_with_permission('view_pii')
user.groups.add(group)
response = self.client.get(url, {'signature': 'sig'})
eq_(response.status_code, 200)
ok_('<option value="user_comments">' in response.content)
ok_('<option value="URL">' in response.content)
# and a column from the Raw Crash
ok_('<option value="Accessibility">' in response.content)
# and it's only supposed to appear once
eq_(response.content.count('<option value="Accessibility">'), 1)
@mock.patch('requests.get')
def test_report_list_partial_correlations(self, rget):
def mocked_get(url, params, **options):
if 'report/list' in url:
return Response("""
{
"hits": [
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Linux",
"uuid": "441017f4-e006-4eea-8451-dc20e0120905",
"cpu_info": "...",
"url": "http://example.com/116",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"release_channel": "Release",
"process_type": "browser",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120901000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
},
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"uuid": "e491c551-be0d-b0fb-c69e-107380120905",
"cpu_info": "...",
"url": "http://example.com/60053",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"release_channel": "Release",
"process_type": "content",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120822000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
}
],
"total": 2
}
""")
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Linux",
"uuid": "441017f4-e006-4eea-8451-dc20e0120905",
"cpu_info": "...",
"url": "http://example.com/116",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"release_channel": "Release",
"process_type": "browser",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120901000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
},
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"uuid": "e491c551-be0d-b0fb-c69e-107380120905",
"cpu_info": "...",
"url": "http://example.com/60053",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"release_channel": "Release",
"process_type": "content",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120822000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
}
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('correlations',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
# relevant data is put into 'data' attributes
ok_('data-correlation_version="5.0a1"' in response.content)
ok_('data-correlation_os="Mac OS X"' in response.content)
@mock.patch('requests.get')
def test_report_list_partial_correlations_no_data(self, rget):
def mocked_get(url, params, **options):
if 'report/list' in url:
return Response("""
{
"hits": [],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('correlations',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
# relevant data is put into 'data' attributes
ok_('data-correlation_version=""' in response.content)
ok_('data-correlation_os=""' in response.content)
@mock.patch('requests.get')
def test_report_list_partial_sigurls(self, rget):
really_long_url = (
'http://thisistheworldsfivehundredthirtyfifthslong'
'esturk.com/that/contains/a/path/and/?a=query&'
)
assert len(really_long_url) > 80
def mocked_get(url, params, **options):
# no specific product was specified, then it should be all products
ok_('products' in params)
ok_(settings.DEFAULT_PRODUCT not in params['products'])
ok_('ALL' in params['products'])
if '/signatureurls' in url:
return Response("""{
"hits": [
{"url": "http://farm.ville", "crash_count":123},
{"url": "%s", "crash_count": 1}
],
"total": 2
}
""" % (really_long_url))
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('sigurls',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
ok_('Must be signed in to see signature URLs' in response.content)
ok_('http://farm.ville' not in response.content)
user = self._login()
group = self._create_group_with_permission('view_pii')
user.groups.add(group)
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
# <a href="HERE" title="HERE">HERE</a>
eq_(response.content.count('http://farm.ville'), 3)
# because the label is truncated
# <a href="HERE" title="HERE">HE...</a>
eq_(response.content.count(really_long_url), 2)
@mock.patch('requests.get')
def test_report_list_partial_sigurls_specific_product(self, rget):
really_long_url = (
'http://thisistheworldsfivehundredthirtyfifthslong'
'esturk.com/that/contains/a/path/and/?a=query&'
)
assert len(really_long_url) > 80
def mocked_get(url, params, **options):
# 'NightTrain' was specifically requested
ok_('products' in params)
ok_('NightTrain' in params['products'])
if '/signatureurls' in url:
return Response("""{
"hits": [
{"url": "http://farm.ville", "crash_count":123},
{"url": "%s", "crash_count": 1}
],
"total": 2
}
""" % (really_long_url))
raise NotImplementedError(url)
rget.side_effect = mocked_get
user = self._login()
group = self._create_group_with_permission('view_pii')
user.groups.add(group)
url = reverse('crashstats:report_list_partial', args=('sigurls',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3,
'product': 'NightTrain'
})
eq_(response.status_code, 200)
eq_(response.content.count('http://farm.ville'), 3)
@mock.patch('requests.get')
def test_report_list_partial_comments(self, rget):
def mocked_get(url, params, **options):
if '/crashes/comments' in url:
return Response("""
{
"hits": [
{
"user_comments": "I LOVE CHEESE [email protected]",
"date_processed": "2012-08-21T11:17:28-07:00",
"email": "[email protected]",
"uuid": "469bde48-0e8f-3586-d486-b98810120830"
}
],
"total": 1
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('comments',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
ok_('I LOVE CHEESE' in response.content)
ok_('email removed' in response.content)
ok_('[email protected]' not in response.content)
ok_('[email protected]' not in response.content)
user = self._login()
group = self._create_group_with_permission('view_pii')
user.groups.add(group)
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
ok_('I LOVE CHEESE' in response.content)
ok_('email removed' not in response.content)
ok_('[email protected]' in response.content)
ok_('[email protected]' in response.content)
@mock.patch('requests.get')
def test_report_list_partial_comments_paginated(self, rget):
called_with_params = []
def mocked_get(url, params, **options):
if '/crashes/comments' in url:
called_with_params.append(params)
if params.get('result_offset'):
return Response({
"hits": [{
"user_comments": "I LOVE HAM",
"date_processed": "2012-08-21T11:17:28-07:00",
"email": "[email protected]",
"uuid": "469bde48-0e8f-3586-d486-b98810120830"
}],
"total": 2
})
else:
return Response({
"hits": [{
"user_comments": "I LOVE CHEESE",
"date_processed": "2011-08-21T11:17:28-07:00",
"email": "[email protected]",
"uuid": "469bde48-0e8f-3586-d486-b98810120829"
}],
"total": 2
})
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('comments',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
ok_('I LOVE CHEESE' in response.content)
ok_('I LOVE HAM' not in response.content)
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3,
'page': 2,
})
eq_(response.status_code, 200)
ok_('I LOVE HAM' in response.content)
ok_('I LOVE CHEESE' not in response.content)
eq_(len(called_with_params), 2)
@mock.patch('requests.get')
def test_report_list_partial_reports(self, rget):
def mocked_get(url, params, **options):
if 'report/list' in url:
return Response("""
{
"hits": [
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Linux",
"uuid": "441017f4-e006-4eea-8451-dc20e0120905",
"cpu_info": "...",
"url": "http://example.com/116",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "browser",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120901000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
},
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"uuid": "e491c551-be0d-b0fb-c69e-107380120905",
"cpu_info": "...",
"url": "http://example.com/60053",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "content",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120822000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
}
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('reports',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
ok_('0xdeadbeef' in response.content)
@mock.patch('requests.get')
def test_report_list_partial_reports_with_sorting(self, rget):
mock_calls = []
def mocked_get(url, params, **options):
mock_calls.append(params)
if 'report/list' in url:
return Response("""
{
"hits": [
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Linux",
"uuid": "441017f4-e006-4eea-8451-dc20e0120905",
"cpu_info": "...",
"url": "http://example.com/116",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "browser",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120901000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
},
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"uuid": "e491c551-be0d-b0fb-c69e-107380120905",
"cpu_info": "...",
"url": "http://example.com/60053",
"last_crash": 1234,
"date_processed": "2012-09-05T22:19:59+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "content",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120822000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
}
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('reports',))
data = {
'signature': 'FakeSignature2',
'range_value': 3
}
response = self.client.get(url, data)
eq_(response.status_code, 200)
assert len(mock_calls) == 1
eq_(mock_calls[-1]['sort'], 'date_processed')
ok_('reverse' not in mock_calls[-1])
response = self.client.get(url, dict(
data,
sort='build'
))
eq_(response.status_code, 200)
assert len(mock_calls) == 2
eq_(mock_calls[-1]['sort'], 'build')
ok_('reverse' not in mock_calls[-1])
response = self.client.get(url, dict(
data,
sort='build',
reverse='True'
))
eq_(response.status_code, 200)
assert len(mock_calls) == 3
eq_(mock_calls[-1]['sort'], 'build')
eq_(mock_calls[-1]['reverse'], True)
@mock.patch('requests.get')
def test_report_list_partial_reports_columns_override(self, rget):
def mocked_get(url, params, **options):
if 'report/list' in url:
return Response("""
{
"hits": [
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Linux",
"uuid": "441017f4-e006-4eea-8451-dc20e0120905",
"cpu_info": "...",
"url": "http://example.com/116",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "browser",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120901000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
},
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"uuid": "e491c551-be0d-b0fb-c69e-107380120905",
"cpu_info": "...",
"url": "http://example.com/60053",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "content",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120822000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
}
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('reports',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3,
'c': ['crap', 'date_processed', 'reason', 'os_and_version']
})
eq_(response.status_code, 200)
# 'reason' in _columns
ok_('reason7' in response.content)
# 'address' not in _columns
ok_('0xdeadbeef' not in response.content)
# 'cpu_name' not in _columns
ok_('x86' not in response.content)
# 'os_and_version' not in _columns
ok_('Mac OS X' in response.content)
@mock.patch('requests.get')
def test_report_list_partial_reports_with_rawcrash(self, rget):
def mocked_get(url, params, **options):
if 'report/list' in url:
return Response("""
{
"hits": [
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Linux",
"uuid": "441017f4-e006-4eea-8451-dc20e0120905",
"cpu_info": "...",
"url": "http://example.com/116",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "browser",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120901000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null,
"raw_crash": {
"Winsock_LSP": "Peter",
"SecondsSinceLastCrash": "Bengtsson"
}
},
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"uuid": "e491c551-be0d-b0fb-c69e-107380120905",
"cpu_info": "...",
"url": "http://example.com/60053",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "content",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120822000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null,
"raw_crash": null
}
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('reports',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3,
'c': ['date_processed', 'Winsock_LSP', 'SecondsSinceLastCrash']
})
eq_(response.status_code, 200)
ok_('Peter' in response.content)
ok_('Bengtsson' in response.content)
# and also the table headers should be there
ok_('Winsock_LSP*' in response.content)
ok_('SecondsSinceLastCrash*' in response.content)
@mock.patch('requests.get')
def test_report_list_partial_reports_page_2(self, rget):
uuids = []
_date = datetime.datetime.now()
for i in range(300):
uuids.append(
'441017f4-e006-4eea-8451-dc20e' +
_date.strftime('%Y%m%d')
)
_date += datetime.timedelta(days=1)
def mocked_get(url, params, **options):
if 'report/list' in url:
result_number = int(params['result_number'])
try:
result_offset = int(params['result_offset'])
except KeyError:
result_offset = 0
first = {
"user_comments": None,
"product": "WaterWolf",
"os_name": "Linux",
"uuid": "441017f4-e006-4eea-8451-dc20e0120905",
"cpu_info": "...",
"url": "http://example.com/116",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "browser",
"hangid": None,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120901000007",
"install_age": 1234,
"signature": "FakeSignature",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": None
}
hits = []
for i in range(result_offset, result_offset + result_number):
try:
item = dict(first, uuid=uuids[i])
hits.append(item)
except IndexError:
break
return Response(json.dumps({
"hits": hits,
"total": len(uuids)
}))
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('reports',))
response = self.client.get(url, {
'signature': 'sig',
})
eq_(response.status_code, 200)
ok_(uuids[0] in response.content)
ok_(uuids[-1] not in response.content)
# expect there to be a link with `page=2` in there
report_list_url = reverse('crashstats:report_list')
report_list_url += '?signature=sig'
ok_(report_list_url + '&page=2' in response.content)
# we'll need a copy of this for later
response_first = response
response = self.client.get(url, {
'signature': 'sig',
'page': 2
})
eq_(response.status_code, 200)
ok_(uuids[0] not in response.content)
ok_(uuids[-1] in response.content)
# try to be a smartass
response_zero = self.client.get(url, {
'signature': 'sig',
'page': 0
})
eq_(response.status_code, 200)
# because with page < 1 you get page=1
tbody_zero = response_zero.content.split('<tbody')[1]
tbody_first = response_first.content.split('<tbody')[1]
eq_(hash(tbody_zero), hash(tbody_first))
response = self.client.get(url, {
'signature': 'sig',
'page': 'xx'
})
eq_(response.status_code, 400)
@mock.patch('requests.get')
def test_report_list_partial_reports_non_defaults(self, rget):
def mocked_get(url, params, **options):
if 'report/list' in url:
return Response("""
{
"hits": [
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Linux",
"uuid": "441017f4-e006-4eea-8451-dc20e0120905",
"cpu_info": "...",
"url": "http://example.com/116",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "browser",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120901000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
},
{
"user_comments": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"uuid": "e491c551-be0d-b0fb-c69e-107380120905",
"cpu_info": "...",
"url": "http://example.com/60053",
"last_crash": 1234,
"date_processed": "2012-09-05T21:18:58+00:00",
"cpu_name": "x86",
"uptime": 1234,
"process_type": "content",
"hangid": null,
"reason": "reason7",
"version": "5.0a1",
"os_version": "1.2.3.4",
"build": "20120822000007",
"install_age": 1234,
"signature": "FakeSignature2",
"install_time": "2012-09-05T20:58:24+00:00",
"address": "0xdeadbeef",
"duplicate_of": null
}
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('reports',))
data = {
'signature': 'sig',
'range_unit': settings.RANGE_UNITS[-1],
'process_type': settings.PROCESS_TYPES[-1],
'range_value': 48,
'plugin_field': settings.PLUGIN_FIELDS[-1],
'hang_type': settings.HANG_TYPES[-1],
'plugin_query_type': settings.QUERY_TYPES[-1],
'product': 'NightTrain',
}
response = self.client.get(url, data)
eq_(response.status_code, 200)
def test_report_list_partial_reports_invalid_range_value(self):
url = reverse('crashstats:report_list_partial', args=('reports',))
data = {
'signature': 'sig',
'range_unit': 'days',
'process_type': settings.PROCESS_TYPES[-1],
'range_value': 48,
'plugin_field': settings.PLUGIN_FIELDS[-1],
'hang_type': settings.HANG_TYPES[-1],
'plugin_query_type': settings.QUERY_TYPES[-1],
'product': 'NightTrain',
}
response = self.client.get(url, data)
eq_(response.status_code, 400)
response = self.client.get(url, dict(data, range_unit='weeks'))
eq_(response.status_code, 400)
response = self.client.get(url, dict(
data,
range_unit='hours',
range_value=24 * 48
))
eq_(response.status_code, 400)
@mock.patch('requests.post')
def test_report_list_partial_bugzilla(self, rpost):
def mocked_post(url, **options):
if '/bugs/' in url:
return Response({
"hits": [
{"id": 111111,
"signature": "Something"},
{"id": 123456789,
"signature": "Something"}
]
})
raise NotImplementedError(url)
rpost.side_effect = mocked_post
url = reverse('crashstats:report_list_partial', args=('bugzilla',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
# not the right signature so it's part of "Related Crash Signatures"
ok_(
response.content.find('Related Crash Signatures') <
response.content.find('123456789')
)
response = self.client.get(url, {
'signature': 'Something',
'range_value': 3
})
eq_(response.status_code, 200)
# now the right signature
ok_('123456789' in response.content)
ok_('111111' in response.content)
# because bug id 123456789 is > than 111111 we expect that order
# in the rendered output
ok_(
response.content.find('123456789') <
response.content.find('111111') <
response.content.find('Related Crash Signatures')
)
@mock.patch('requests.get')
def test_report_list_partial_table(self, rget):
def mocked_get(url, params, **options):
if '/crashes/frequency' in url:
# these fixtures make sure we stress the possibility that
# the build_date might be invalid or simply just null.
return Response("""
{
"hits": [
{
"count": 1050,
"build_date": "20130806030203",
"count_mac": 0,
"frequency_windows": 1.0,
"count_windows": 1050,
"frequency": 1.0,
"count_linux": 0,
"total": 1050,
"frequency_linux": 0.0,
"frequency_mac": 0.0
},
{
"count": 1150,
"build_date": "notadate",
"count_mac": 0,
"frequency_windows": 1.0,
"count_windows": 1150,
"frequency": 1.0,
"count_linux": 0,
"total": 1150,
"frequency_linux": 0.0,
"frequency_mac": 0.0
},
{
"count": 1250,
"build_date": null,
"count_mac": 0,
"frequency_windows": 1.0,
"count_windows": 1250,
"frequency": 1.0,
"count_linux": 0,
"total": 1250,
"frequency_linux": 0.0,
"frequency_mac": 0.0
}
]
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('table',))
response = self.client.get(url, {
'signature': 'sig',
'range_value': 3
})
eq_(response.status_code, 200)
ok_('1050 - 100.0%' in response.content)
ok_('1150 - 100.0%' in response.content)
ok_('1250 - 100.0%' in response.content)
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_report_index_redirect_by_prefix(self, rget, rpost):
dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod|1"
comment0 = "This is a comment"
email0 = "[email protected]"
url0 = "someaddress.com"
email1 = "[email protected]"
def mocked_get(url, params, **options):
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'meta'
):
return Response("""
{
"InstallTime": "1339289895",
"FramePoisonSize": "4096",
"Theme": "classic/1.0",
"Version": "5.0a1",
"Email": "%s",
"Vendor": "Mozilla",
"URL": "%s"
}
""" % (email0, url0))
if 'crashes/comments' in url:
return Response("""
{
"hits": [
{
"user_comments": "%s",
"date_processed": "2012-08-21T11:17:28-07:00",
"email": "%s",
"uuid": "469bde48-0e8f-3586-d486-b98810120830"
}
],
"total": 1
}
""" % (comment0, email1))
if (
'/crash_data' in url and
'datatype' in params and
params['datatype'] == 'unredacted'
):
return Response("""
{
"client_crash_date": "2012-06-11T06:08:45",
"dump": "%s",
"signature": "FakeSignature1",
"user_comments": null,
"uptime": 14693,
"release_channel": "nightly",
"uuid": "11cb72f5-eb28-41e1-a8e4-849982120611",
"flash_version": "[blank]",
"hangid": null,
"distributor_version": null,
"truncated": true,
"process_type": null,
"id": 383569625,
"os_version": "10.6.8 10K549",
"version": "5.0a1",
"build": "20120609030536",
"ReleaseChannel": "nightly",
"addons_checked": null,
"product": "WaterWolf",
"os_name": "Mac OS X",
"last_crash": 371342,
"date_processed": "2012-06-11T06:08:44",
"cpu_name": "amd64",
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"address": "0x8",
"completeddatetime": "2012-06-11T06:08:57",
"success": true,
"exploitability": "Unknown Exploitability"
}
""" % dump)
if 'correlations/signatures' in url:
return Response("""
{
"hits": [
"FakeSignature1",
"FakeSignature2"
],
"total": 2
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
def mocked_post(url, **options):
if '/bugs/' in url:
return Response("""
{"hits": [{"id": "123456789",
"signature": "Something"}]}
""")
raise NotImplementedError(url)
rpost.side_effect = mocked_post
base_crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611'
crash_id = settings.CRASH_ID_PREFIX + base_crash_id
assert len(crash_id) > 36
url = reverse('crashstats:report_index', args=[crash_id])
response = self.client.get(url)
correct_url = reverse('crashstats:report_index', args=[base_crash_id])
self.assertRedirects(response, correct_url)
@mock.patch('requests.get')
def test_report_list_with_no_data(self, rget):
def mocked_get(url, params, **options):
if 'report/list' in url:
return Response("""
{
"hits": [],
"total": 0
}
""")
raise NotImplementedError(url)
rget.side_effect = mocked_get
url = reverse('crashstats:report_list_partial', args=('reports',))
response = self.client.get(url, {'signature': 'sig'})
eq_(response.status_code, 200)
# it sucks to depend on the output like this but it'll do for now since
# it's quite a rare occurance.
ok_('</html>' not in response.content) # it's a partial
ok_('no reports in the time period specified' in response.content)
@mock.patch('requests.get')
def test_raw_data(self, rget):
def mocked_get(url, params, **options):
assert '/crash_data' in url
if 'datatype' in params and params['datatype'] == 'raw':
return Response("""
bla bla bla
""".strip())
else:
# default is datatype/meta
return Response("""
{"foo": "bar",
"stuff": 123}
""")
rget.side_effect = mocked_get
crash_id = '176bcd6c-c2ec-4b0c-9d5f-dadea2120531'
json_url = reverse('crashstats:raw_data', args=(crash_id, 'json'))
response = self.client.get(json_url)
self.assertRedirects(
response,
reverse('crashstats:login') + '?next=%s' % json_url
)
eq_(response.status_code, 302)
user = self._login()
group = self._create_group_with_permission('view_rawdump')
user.groups.add(group)
assert user.has_perm('crashstats.view_rawdump')
response = self.client.get(json_url)
eq_(response.status_code, 200)
eq_(response['Content-Type'], 'application/json')
eq_(json.loads(response.content),
{"foo": "bar", "stuff": 123})
dump_url = reverse('crashstats:raw_data', args=(crash_id, 'dmp'))
response = self.client.get(dump_url)
eq_(response.status_code, 200)
eq_(response['Content-Type'], 'application/octet-stream')
ok_('bla bla bla' in response.content, response.content)
# dump files are cached.
# check the mock function and expect no change
def different_mocked_get(url, **options):
if '/crash_data' in url and 'datatype=raw' in url:
return Response("""
SOMETHING DIFFERENT
""".strip())
raise NotImplementedError(url)
rget.side_effect = different_mocked_get
response = self.client.get(dump_url)
eq_(response.status_code, 200)
ok_('bla bla bla' in response.content) # still. good.
@mock.patch('requests.post')
@mock.patch('requests.get')
def test_remembered_date_range_type(self, rget, rpost):
# if you visit the home page, the default date_range_type will be
# 'report' but if you switch to 'build' it'll remember that
def mocked_get(url, params, **options):
if '/products' in url and 'versions' not in params:
return Response("""
{
"products": [
"WaterWolf"
],
"hits": {
"WaterWolf": [{
"featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "WaterWolf",
"release": "Nightly",
"version": "19.0",
"has_builds": true,
"start_date": "2012-09-25"
}]
},
"total": 1
}
""")
elif '/products' in url:
return Response("""
{
"hits": [{
"is_featured": true,
"throttle": 100.0,
"end_date": "2012-11-27",
"product": "WaterWolf",
"build_type": "Nightly",
"version": "19.0",
"has_builds": true,
"start_date": "2012-09-25"
}],
"total": 1
}
""")
if '/crashes/daily' in url:
return Response("""
{
"hits": {
"WaterWolf:19.0": {
"2012-10-08": {
"product": "WaterWolf",
"adu": 30000,
"crash_hadu": 71.099999999999994,
"version": "19.0",
"report_count": 2133,
"date": "2012-10-08"
},
"2012-10-02": {
"product": "WaterWolf",
"adu": 30000,
"crash_hadu": 77.299999999999997,
"version": "19.0",
"report_count": 2319,
"date": "2012-10-02"
}
}
}
}
""")
if '/crashes/signatures' in url:
return Response("""
{"crashes": [
{
"count": 188,
"mac_count": 66,
"content_count": 0,
"first_report": "2012-06-21",
"startup_percent": 0.0,
"currentRank": 0,
"previousRank": 1,
"first_report_exact": "2012-06-21T21:28:08",
"versions":
"2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1",
"percentOfTotal": 0.24258064516128999,
"win_count": 56,
"changeInPercentOfTotal": 0.011139597126354983,
"linux_count": 66,
"hang_count": 0,
"signature": "FakeSignature1",
"versions_count": 8,
"changeInRank": 0,
"plugin_count": 0,
"previousPercentOfTotal": 0.23144104803493501,
"is_gc_count": 10
}
],
"totalPercentage": 0,
"start_date": "2012-05-10",
"end_date": "2012-05-24",
"totalNumberOfCrashes": 0}
""")
raise NotImplementedError(url)
def mocked_post(**options):
assert '/bugs/' in options['url'], options['url']
return Response("""
{"hits": [{"id": "123456789",
"signature": "Something"}]}
""")
rpost.side_effect = mocked_post
rget.side_effect = mocked_get
url = reverse('crashstats:home', args=('WaterWolf',))
response = self.client.get(url)
eq_(response.status_code, 200)
regex = re.compile('(<a\s+href="\?date_range_type=(\w+)[^>]+)')
for tag, value in regex.findall(response.content):
if value == 'report':
ok_('selected' in tag)
else:
ok_('selected' not in tag)
# now, like the home page does, fire of an AJAX request to frontpage
# for 'build' instead
frontpage_json_url = reverse('crashstats:frontpage_json')
frontpage_reponse = self.client.get(frontpage_json_url, {
'product': 'WaterWolf',
'date_range_type': 'build'
})
eq_(frontpage_reponse.status_code, 200)
# load the home page again, and it should be on build date instead
response = self.client.get(url)
eq_(response.status_code, 200)
for tag, value in regex.findall(response.content):
if value == 'build':
ok_('selected' in tag)
else:
ok_('selected' not in tag)
# open topcrashers with 'report'
topcrasher_report_url = reverse(
'crashstats:topcrasher',
kwargs={
'product': 'WaterWolf',
'versions': '19.0',
'date_range_type': 'report'
}
)
response = self.client.get(topcrasher_report_url)
eq_(response.status_code, 200)
# now, go back to the home page, and 'report' should be the new default
response = self.client.get(url)
eq_(response.status_code, 200)
for tag, value in regex.findall(response.content):
if value == 'report':
ok_('selected' in tag)
else:
ok_('selected' not in tag)
# open topcrashers with 'build'
topcrasher_report_url = reverse(
'crashstats:topcrasher',
kwargs={
'product': 'WaterWolf',
'versions': '19.0',
'date_range_type': 'build'
}
)
response = self.client.get(topcrasher_report_url)
eq_(response.status_code, 200)
# now, go back to the home page, and 'report' should be the new default
response = self.client.get(url)
eq_(response.status_code, 200)
for tag, value in regex.findall(response.content):
if value == 'build':
ok_('selected' in tag)
else:
ok_('selected' not in tag)
@mock.patch('requests.get')
def test_correlations_json(self, rget):
url = reverse('crashstats:correlations_json')
def mocked_get(url, params, **options):
if '/correlations/' in url:
ok_('report_type' in params)
eq_(params['report_type'], 'core-counts')
return Response({
"reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS",
"count": 13,
"load": "36% (4/11) vs. 26% (47/180) amd64 with 2 cores"
})
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(
url,
{'correlation_report_type': 'core-counts',
'product': 'WaterWolf',
'version': '19.0',
'platform': 'Windows NT',
'signature': 'FakeSignature'}
)
ok_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
eq_(struct['reason'], 'EXC_BAD_ACCESS / KERN_INVALID_ADDRESS')
@mock.patch('requests.get')
def test_correlations_signatures_json(self, rget):
url = reverse('crashstats:correlations_signatures_json')
<|fim▁hole|> if '/correlations/' in url:
return Response({
"hits": ["FakeSignature1",
"FakeSignature2"],
"total": 2
})
raise NotImplementedError(url)
rget.side_effect = mocked_get
response = self.client.get(
url,
{'correlation_report_type': 'core-counts',
'product': 'WaterWolf',
'version': '19.0',
'platforms': 'Windows NT,Linux'}
)
ok_(response.status_code, 200)
ok_('application/json' in response['content-type'])
struct = json.loads(response.content)
eq_(struct['total'], 2)
def test_unauthenticated_user_redirected_from_protected_page(self):
url = reverse(
'crashstats:exploitable_crashes',
args=(settings.DEFAULT_PRODUCT,)
)
response = self.client.get(url)
self.assertRedirects(
response,
'%s?%s=%s' % (
reverse('crashstats:login'),
REDIRECT_FIELD_NAME,
url,
)
)
def test_login_page_renders(self):
url = reverse('crashstats:login')
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('Login Required' in response.content)
ok_('Insufficient Privileges' not in response.content)
self._login()
response = self.client.get(url)
eq_(response.status_code, 200)
ok_('Login Required' not in response.content)
ok_('Insufficient Privileges' in response.content)
def test_your_permissions_page(self):
url = reverse('crashstats:permissions')
response = self.client.get(url)
eq_(response.status_code, 302)
self.assertRedirects(
response,
reverse('crashstats:login') + '?next=%s' % url
)
user = self._login()
response = self.client.get(url)
eq_(response.status_code, 200)
ok_(user.email in response.content)
# make some groups and attach permissions
self._create_group_with_permission(
'view_pii', 'Group A'
)
groupB = self._create_group_with_permission(
'view_exploitability', 'Group B'
)
user.groups.add(groupB)
assert not user.has_perm('crashstats.view_pii')
assert user.has_perm('crashstats.view_exploitability')
response = self.client.get(url)
eq_(response.status_code, 200)
ok_(PERMISSIONS['view_pii'] in response.content)
ok_(PERMISSIONS['view_exploitability'] in response.content)
doc = pyquery.PyQuery(response.content)
for row in doc('table.permissions tbody tr'):
cells = []
for td in doc('td', row):
cells.append(td.text.strip())
if cells[0] == PERMISSIONS['view_pii']:
eq_(cells[1], 'No')
elif cells[0] == PERMISSIONS['view_exploitability']:
eq_(cells[1], 'Yes!')<|fim▁end|> | def mocked_get(url, params, **options): |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! FFI bindings to searchsdk.<|fim▁hole|>#![experimental]
extern crate winapi;
use winapi::*;
extern "system" {
}<|fim▁end|> | #![no_std] |
<|file_name|>index.py<|end_file_name|><|fim▁begin|>#
# AFLTV XBMC Plugin
# Copyright (C) 2013 Kagenoshin
#
# AFLTV is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# AFLTV 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 AFLTV. If not, see <http://www.gnu.org/licenses/>.
#
# main imports
import sys, os, urllib2, urllib
import config
import utils
try:
import xbmc, xbmcgui, xbmcplugin, xbmcaddon
except ImportError:
pass
def make_list():
try:
items = []
__addon__ = xbmcaddon.Addon()
# Add the other feeds listed in the config file
for channel in config.CHANNELS:
items.append({'name': channel['name'], 'channel': channel['channel']})
items.append({'name': 'Settings', 'channel': 'settings'})
# fill media list<|fim▁hole|> ok = False
# send notification we're finished, successfully or unsuccessfully
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
def fill_media_list(items):
try:
ok = True
# enumerate through the list of categories and add the item to the media list
for i in items:
url = "%s?channel=%s" % (sys.argv[0], i['channel'])
#thumbnail = get_thumbnail(c.channel)
icon = "defaultfolder.png"
listitem = xbmcgui.ListItem(i['name'], iconImage=icon)
#listitem.setInfo('video',{'episode':s.get_num_episodes()})
# add the item to the media list
ok = xbmcplugin.addDirectoryItem(
handle=int(sys.argv[1]),
url=url,
listitem=listitem,
isFolder=True,
totalItems=len(config.CHANNELS) + 1
)
# if user cancels, call raise to exit loop
if (not ok):
raise
#xbmcplugin.setContent(handle=int(sys.argv[1]), content='tvshows')
except:
# user cancelled dialog or an error occurred
d = xbmcgui.Dialog()
d.ok('AFL Video Error', 'AFL Video encountered an error:', ' %s (%d) - %s' % (sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ]) )
# user cancelled dialog or an error occurred
print "ERROR: %s (%d) - %s" % (sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ],)
ok = False
return ok<|fim▁end|> | ok = fill_media_list(items)
except:
# oops print error message
print "ERROR: %s (%d) - %s" % (sys.exc_info()[2].tb_frame.f_code.co_name, sys.exc_info()[2].tb_lineno, sys.exc_info()[1]) |
<|file_name|>serializer.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack 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.
"""
Dict <--> XML de/serializer.
The identity API prefers attributes over elements, so we serialize that way
by convention, with a few hardcoded exceptions.
"""
from lxml import etree
import re
import six
from keystone.i18n import _
DOCTYPE = '<?xml version="1.0" encoding="UTF-8"?>'
XMLNS = 'http://docs.openstack.org/identity/api/v2.0'
XMLNS_LIST = [
{
'value': 'http://docs.openstack.org/identity/api/v2.0'
},
{
'prefix': 'OS-KSADM',
'value': 'http://docs.openstack.org/identity/api/ext/OS-KSADM/v1.0',
},
]
PARSER = etree.XMLParser(
resolve_entities=False,
remove_comments=True,
remove_pis=True)
# NOTE(dolph): lxml.etree.Entity() is just a callable that currently returns an
# lxml.etree._Entity instance, which doesn't appear to be part of the
# public API, so we discover the type dynamically to be safe
ENTITY_TYPE = type(etree.Entity('x'))
def from_xml(xml):
"""Deserialize XML to a dictionary."""
if xml is None:
return None
deserializer = XmlDeserializer()
return deserializer(xml)
def to_xml(d, xmlns=None):
"""Serialize a dictionary to XML."""
if d is None:
return None
serialize = XmlSerializer()
return serialize(d, xmlns)
class XmlDeserializer(object):
def __call__(self, xml_str):
"""Returns a dictionary populated by decoding the given xml string."""
dom = etree.fromstring(xml_str.strip(), PARSER)
return self.walk_element(dom, True)
def _deserialize_links(self, links):
return dict((x.attrib['rel'], x.attrib['href']) for x in links)
@staticmethod
def _qualified_name(tag, namespace):
"""Returns a qualified tag name.
The tag name may contain the namespace prefix or not, which can
be determined by specifying the parameter namespace.
"""
m = re.search('[^}]+$', tag)
tag_name = m.string[m.start():]
if not namespace:
return tag_name
bracket = re.search('[^{]+$', tag)
ns = m.string[bracket.start():m.start() - 1]
# If the namespace is
# http://docs.openstack.org/identity/api/ext/OS-KSADM/v1.0 for the
# root element, a prefix needs to add in front of the tag name.
prefix = None
for xmlns in XMLNS_LIST:
if xmlns['value'] == ns:
prefix = xmlns.get('prefix')
break
if prefix is not None:
return '%(PREFIX)s:%(tag_name)s' % {
'PREFIX': prefix, 'tag_name': tag_name}
else:
return tag_name
def walk_element(self, element, namespace=False):
"""Populates a dictionary by walking an etree element."""
values = {}
for k, v in six.iteritems(element.attrib):
# boolean-looking attributes become booleans in JSON
if k in ['enabled', 'truncated']:
if v in ['true']:
v = True
elif v in ['false']:
v = False
values[self._qualified_name(k, namespace)] = v
text = None
if element.text is not None:
text = element.text.strip()
# current spec does not have attributes on an element with text
values = values or text or {}
decoded_tag = XmlDeserializer._qualified_name(element.tag, namespace)
list_item_tag = None
if (decoded_tag[-1] == 's' and not values and
decoded_tag != 'access'):
# FIXME(gyee): special-case lists for now unti we
# figure out how to properly handle them.
# If any key ends with an 's', we are assuming it is a list.
# List element have no attributes.
values = list(values)
if decoded_tag == 'policies':
list_item_tag = 'policy'
else:
list_item_tag = decoded_tag[:-1]
if decoded_tag == 'links':
return {'links': self._deserialize_links(element)}
links = None
truncated = False
for child in [self.walk_element(x) for x in element
if not isinstance(x, ENTITY_TYPE)]:
if list_item_tag:
# FIXME(gyee): special-case lists for now until we
# figure out how to properly handle them.
# If any key ends with an 's', we are assuming it is a list.
if list_item_tag in child:
values.append(child[list_item_tag])
else:
if 'links' in child:
links = child['links']
else:
truncated = child['truncated']
else:
values = dict(values.items() + child.items())
# set empty and none-list element to None to align with JSON
if not values:
values = ""
d = {XmlDeserializer._qualified_name(element.tag, namespace): values}
if links:
d['links'] = links
d['links'].setdefault('next')
d['links'].setdefault('previous')
if truncated:
d['truncated'] = truncated['truncated']
return d
class XmlSerializer(object):
def __call__(self, d, xmlns=None):
"""Returns an xml etree populated by the given dictionary.
Optionally, namespace the etree by specifying an ``xmlns``.
"""
links = None
truncated = False
# FIXME(dolph): skipping links for now
for key in d.keys():
if '_links' in key:
d.pop(key)
# NOTE(gyee, henry-nash): special-case links and truncation
# attribute in collections
if 'links' == key:
if links:
# we have multiple links
raise Exception('Multiple links found')
links = d.pop(key)
if 'truncated' == key:
if truncated:
# we have multiple attributes
raise Exception(_('Multiple truncation attributes found'))
truncated = d.pop(key)
assert len(d.keys()) == 1, ('Cannot encode more than one root '
'element: %s' % d.keys())
# name the root dom element
name = d.keys()[0]
m = re.search('[^:]+$', name)
root_name = m.string[m.start():]
prefix = m.string[0:m.start() - 1]
for ns in XMLNS_LIST:
if prefix == ns.get('prefix'):
xmlns = ns['value']
break
# only the root dom element gets an xlmns
root = etree.Element(root_name, xmlns=(xmlns or XMLNS))
self.populate_element(root, d[name])
# NOTE(gyee, henry-nash): special-case links and truncation attribute
if links:
self._populate_links(root, links)
if truncated:
self._populate_truncated(root, truncated)
# TODO(dolph): you can get a doctype from lxml, using ElementTrees
return '%s\n%s' % (DOCTYPE, etree.tostring(root, pretty_print=True))
def _populate_links(self, element, links_json):
links = etree.Element('links')
for k, v in six.iteritems(links_json):
if v:
link = etree.Element('link')
link.set('rel', six.text_type(k))
link.set('href', six.text_type(v))
links.append(link)
element.append(links)
def _populate_truncated(self, element, truncated_value):
truncated = etree.Element('truncated')
self._populate_bool(truncated, 'truncated', truncated_value)
element.append(truncated)
def _populate_list(self, element, k, v):
"""Populates an element with a key & list value."""
# spec has a lot of inconsistency here!
container = element
if k == 'media-types':
# xsd compliance: <media-types> contains <media-type>s
# find an existing <media-types> element or make one
container = element.find('media-types')
if container is None:
container = etree.Element(k)
element.append(container)
name = k[:-1]
elif k == 'serviceCatalog' or k == 'catalog':
# xsd compliance: <serviceCatalog> contains <service>s
container = etree.Element(k)
element.append(container)
name = 'service'
elif k == 'roles' and element.tag == 'user':
name = 'role'
elif k == 'endpoints' and element.tag == 'service':
name = 'endpoint'
elif k == 'values' and element.tag[-1] == 's':
# OS convention is to contain lists in a 'values' element,
# so the list itself can have attributes, which is
# unnecessary in XML
name = element.tag[:-1]
elif k[-1] == 's':
container = etree.Element(k)
element.append(container)
if k == 'policies':
# need to special-case policies since policie is not a word
name = 'policy'
else:
name = k[:-1]
else:
name = k
for item in v:
child = etree.Element(name)
self.populate_element(child, item)
container.append(child)
def _populate_dict(self, element, k, v):
"""Populates an element with a key & dictionary value."""
if k == 'links':
# links is a special dict
self._populate_links(element, v)
else:
child = etree.Element(k)
self.populate_element(child, v)
element.append(child)
def _populate_bool(self, element, k, v):
"""Populates an element with a key & boolean value."""
# booleans are 'true' and 'false'<|fim▁hole|> element.set(k, six.text_type(v).lower())
def _populate_str(self, element, k, v):
"""Populates an element with a key & string value."""
if k in ['description']:
# always becomes an element
child = etree.Element(k)
child.text = six.text_type(v)
element.append(child)
else:
# add attributes to the current element
element.set(k, six.text_type(v))
def _populate_number(self, element, k, v):
"""Populates an element with a key & numeric value."""
# numbers can be handled as strings
self._populate_str(element, k, v)
def populate_element(self, element, value):
"""Populates an etree with the given value."""
if isinstance(value, list):
self._populate_sequence(element, value)
elif isinstance(value, dict):
self._populate_tree(element, value)
# NOTE(blk-u): For compatibility with Folsom, when serializing the
# v2.0 version element also add the links to the base element.
if value.get('id') == 'v2.0':
for item in value['links']:
child = etree.Element('link')
self.populate_element(child, item)
element.append(child)
elif isinstance(value, six.string_types):
element.text = six.text_type(value)
def _populate_sequence(self, element, l):
"""Populates an etree with a sequence of elements, given a list."""
# xsd compliance: child elements are singular: <users> has <user>s
name = element.tag
if element.tag[-1] == 's':
name = element.tag[:-1]
if name == 'policie':
name = 'policy'
for item in l:
child = etree.Element(name)
self.populate_element(child, item)
element.append(child)
def _populate_tree(self, element, d):
"""Populates an etree with attributes & elements, given a dict."""
for k, v in six.iteritems(d):
if isinstance(v, dict):
self._populate_dict(element, k, v)
elif isinstance(v, list):
self._populate_list(element, k, v)
elif isinstance(v, bool):
self._populate_bool(element, k, v)
elif isinstance(v, six.string_types):
self._populate_str(element, k, v)
elif type(v) in [int, float, long, complex]:
self._populate_number(element, k, v)<|fim▁end|> | |
<|file_name|>operation.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# © 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Skarphed.
#
# Skarphed is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later
# version.
#
# Skarphed 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with Skarphed.
# If not, see http://www.gnu.org/licenses/.
###########################################################
import os
from daemon import Daemon
from time import sleep
from StringIO import StringIO
from traceback import print_exc
from skarphedcore.configuration import Configuration
from skarphedcore.database import Database
from skarphedcore.core import Core
from skarphedcore.module import Module
from common.errors import OperationException
class Operation(object):
"""
Contais everything necessary to Handle Operations
"""
STATUS_PENDING = 0
STATUS_ACTIVE = 1
STATUS_FAILED = 2
VALID_STORAGE_TYPES = ('int','bool','str','unicode')
def __init__(self, parent_id = None):
"""
"""
self._id = None
self._parent = parent_id
self._values = {}
@classmethod
def drop_operation(cls,operation_id):
"""
Drops an Operation, identified by it's Operation Id and
it's children recursively
Drop deletes the Operations from Database
"""
db = Database()
stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS IN (0, 2) ;"
cur = db.query(stmnt,(operation_id,))
for row in cur.fetchallmap():
cls.drop_operation(row["OPE_ID"])
stmnt = "DELETE FROM OPERATIONS WHERE OPE_ID = ? AND OPE_STATUS IN (0, 2) ;"
db.query(stmnt,(operation_id,),commit=True)
<|fim▁hole|> """
Resets the state of an operation and it's children recursively to 0 (PENDING)
The operation is identified by a given operationId
"""
db = Database()
stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 2 ;"
cur = db.query(stmnt,(operation_id,))
for row in cur.fetchallmap():
cls.retry_operation(row["OPE_ID"])
stmnt = "UPDATE OPERATIONS SET OPE_STATUS = 0 WHERE OPE_ID = ? AND OPE_STATUS = 2 ;"
db.query(stmnt,(operation_id,),commit=True)
@classmethod
def cancel_operation(cls,operation_id):
"""
Cancels an Operation, identified by it's Operation Id and
it's children recursively
Cancel Deletes the Operation from Database
"""
db = Database()
stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 0 ;"
cur = db.query(stmnt,(operation_id,))
for row in cur.fetchallmap():
cls.cancel_operation(row["OPE_ID"])
stmnt = "DELETE FROM OPERATIONS WHERE OPE_ID = ? AND OPE_STATUS = 0 ;"
db.query(stmnt,(operation_id,),commit=True)
@classmethod
def restore_operation(cls, operation_record):
"""
Restore an Operationobject stored in the database by a Dataset consisting of
the operation's ID and the operation's TYPE:
For example: {"OPE_ID": 100, "OPE_TYPE": "TestOperation"}
Restores the Operationobject's _values-attribute by the data saved
in the DB-Table OPERATIONDATA
"""
classname = operation_record["OPE_TYPE"]
module = "" #TODO Implement modulename from database if Operation belongs to Module
is_operation_of_module = False
exec """
try:
type(%(class)s)
except NameError,e:
is_operation_of_module = True"""%{'class':classname}
if is_operation_of_module:
exec """
from %(module)s import %(class)s
operation = %(class)s()"""%{'class':classname,'module':module}
else:
exec """
operation = %(class)s()"""%{'class':classname}
operation.set_id(operation_record['OPE_ID'])
db = Database()
stmnt = "SELECT OPD_KEY, OPD_VALUE, OPD_TYPE FROM OPERATIONDATA WHERE OPD_OPE_ID = ? ;"
cur = db.query(stmnt,(operation_record["OPE_ID"],))
for row in cur.fetchallmap():
val = row["OPD_VALUE"]
exec """val = %s(val)"""%row["OPD_TYPE"]
operation.set_value(row["OPD_KEY"], val)
return operation
@classmethod
def process_children(cls, operation):
"""
Recursively executes the workloads of Operation's Childoperations
It hereby catches exceptions in the workloads, sets the OPE_STATUS
to 2 (FAILED) if a catch occurs, then passes the exception on to the
higher layer.
If an Operation succeeds, it's entry in DB gets deleted
"""
db = Database()
stmnt = "SELECT OPE_ID, OPE_TYPE FROM OPERATIONS WHERE OPE_OPE_PARENT = ? ORDER BY OPE_INVOKED ;"
stmnt_lock = "UPDATE OPERATIONS SET OPE_STATUS = 1 WHERE OPE_ID = ? ;"
cur = db.query(stmnt,(operation.get_id(),))
for row in cur.fetchallmap():
child_operation = cls.restore_operation(row)
db.query(stmnt_lock,(child_operation.get_id(),),commit=True)
try:
cls.process_children(child_operation)
child_operation.do_workload()
except Exception,e:
stmnt_err = "UPDATE OPERATIONS SET OPE_STATUS = 2 WHERE OPE_ID = ? ;"
db.query(stmnt_err,(int(row["OPE_ID"]),),commit=True)
#TODO GENERATE ERROR IN LOG
raise e
stmnt_delete = "DELETE FROM OPERATIONS WHERE OPE_ID = ?;"
db.query(stmnt_delete,(child_operation.get_id(),),commit=True)
@classmethod
def process_next(cls):
"""
Sets the status of the next toplevel operation to 1 (ACTIVE)
Fetches the next toplevel-operation from the database, applies a FILESYSTEMLOCK!
Which is /tmp/scv_operating.lck !!!
"""
db = Database()
configuration = Configuration()
if os.path.exists(configuration.get_entry("core.webpath")+"/scv_operating.lck"):
return False
lockfile = open(configuration.get_entry("core.webpath")+"/scv_operating.lck","w")
lockfile.close()
stmnt_lock = "UPDATE OPERATIONS SET OPE_STATUS = 1 \
WHERE OPE_ID IN ( \
SELECT OPE_ID FROM OPERATIONS \
WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 0 \
AND OPE_INVOKED = ( \
SELECT MIN(OPE_INVOKED) FROM OPERATIONS \
WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 0) \
) ;"
stmnt = "SELECT OPE_ID, OPE_TYPE FROM OPERATIONS WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 1 ;"
db.query(stmnt_lock,commit=True)
cur = db.query(stmnt)
res = cur.fetchallmap()
if len(res) > 0:
operation = cls.restore_operation(res[0])
try:
cls.process_children(operation)
operation.do_workload()
except Exception, e:
stmnt_err = "UPDATE OPERATIONS SET OPE_STATUS = 2 WHERE OPE_ID = ? ;"
db.query(stmnt_err,(operation.get_id(),),commit=True)
error = StringIO()
print_exc(None,error)
Core().log(error.getvalue())
ret = True
else:
ret = False
stmnt_delete = "DELETE FROM OPERATIONS WHERE OPE_STATUS = 1 ;"
db.query(stmnt_delete,commit=True)
db.commit()
try:
os.unlink(configuration.get_entry("core.webpath")+"/scv_operating.lck")
except OSError,e :
raise OperationException(OperationException.get_msg(0))
return ret
@classmethod
def get_current_operations_for_gui(cls, operation_types=None):
"""
Returns all Operations in an associative array.
The array's indices are the operationIDs
The Objects contain all information about the operations,
including the Data
"""
db = Database()
#TODO CHECK HOW LISTS ARE HANDLED IN FDB
if operation_types is not None and type(operation_types) == list:
stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE, OPE_STATUS FROM OPERATIONS WHERE OPE_TYPE IN (?) ORDER BY OPE_INVOKED ;"
cur = db.query(stmnt,(operation_types))
else:
stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE, OPE_STATUS FROM OPERATIONS ORDER BY OPE_INVOKED ;"
cur = db.query(stmnt)
ret = {}
for row in cur.fetchallmap():
operation = cls.restore_operation(row)
custom_values = operation.get_values()
ret[row["OPE_ID"]] = {"id":row["OPE_ID"],
"parent":row["OPE_OPE_PARENT"],
"invoked":str(row["OPE_INVOKED"]),
"type":row["OPE_TYPE"],
"status":row["OPE_STATUS"],
"data":custom_values}
return ret
def get_values(self):
"""
trivial
"""
return self._values
def get_value(self,key):
"""
trivial
"""
return self._values(key)
def set_value(self,key,value):
"""
trivial
"""
self._values[key] = value
def set_parent(self,parent_id):
"""
trivial
"""
self._parent = parent_id
def get_parent(self):
"""
trivial
"""
return self._parent
def set_db_id(self):
"""
Get a new Operation Id from the Database and assign it to this
Operation if this Operation's id is null. Afterwards return the
new Id
"""
if self._id is None:
self._id = Database().get_seq_next('OPE_GEN')
return self._id
def set_id(self, nr):
"""
trivial
"""
self._id = nr
def get_id(self):
"""
trivial
"""
return self._id
def store(self):
"""
Stores this Operation to database.
Also saves every user defined value in $_values as
long as it is a valid type
"""
db = Database()
self.set_db_id()
stmnt = "UPDATE OR INSERT INTO OPERATIONS (OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE) \
VALUES (?,?,CURRENT_TIMESTAMP,?) MATCHING (OPE_ID);"
db.query(stmnt,(self._id,self._parent,self.__class__.__name__),commit=True)
stmnt = "UPDATE OR INSERT INTO OPERATIONDATA (OPD_OPE_ID, OPD_KEY, OPD_VALUE, OPD_TYPE) \
VALUES ( ?, ?, ?, ?) MATCHING(OPD_OPE_ID,OPD_KEY);"
for key, value in self._values.items():
typ = str(type(value)).replace("<type '","",1).replace("'>","",1)
if typ not in Operation.VALID_STORAGE_TYPES:
continue
db.query(stmnt,(self._id,key,value,typ),commit=True)
def do_workload(self):
"""
This method must be overridden by inheriting classes.
The code inside this method will be executed when the
Operation is processed by Operation.processNext or
Operation.processChild
"""
pass
#MODULEINVOLVED
class ModuleOperation(Operation):
"""
Abstracts Operations that have to do with modules
"""
def __init__(self):
"""
trivial
"""
Operation.__init__(self)
def set_values(self,module):
"""
Sets this operations values from module metadata
"""
if type(module) == dict:
self.set_value("name",module["name"])
self.set_value("hrname",module["hrname"])
self.set_value("version_major",module["version_major"])
self.set_value("version_minor",module["version_minor"])
self.set_value("revision",module["revision"])
if module.has_key("signature"):
self.set_value("signature",module["signature"])
elif module.__class__.__name__ == "Module":
pass #TODO IMPLEMENT / DISCUSS AFTER IMPLEMENTING MODULE-SUBSYSTEM
def get_meta(self):
"""
trivial
"""
return self._values
@classmethod
def get_currently_processed_modules(cls):
"""
Returns an Array of ModuleOperation-Objects that are
currently listedin the queue
"""
db = Database()
stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_TYPE FROM OPERATIONS \
WHERE OPE_TYPE = 'ModuleInstallOperation' \
or OPE_TYPE = 'ModuleUninstallOperation' ;"
cur = db.query(stmnt);
ret = []
for row in cur.fetchallmap():
ret.append(Operation.restore_operation(row).get_meta())
return ret
def optimize_queue(self):
"""
abtract
"""
pass
#MODULEINVOLVED
class ModuleInstallOperation(ModuleOperation):
"""
Manages the process to install a module to this server
"""
def __init__(self):
"""
trivial
"""
ModuleOperation.__init__(self)
def do_workload(self):
"""
tell the module manager to install a specific module.
"""
Module.install_module(self.get_meta())
def optimize_queue(self):
"""
optimizes the queue.
"""
pass #TODO Implement
#MODULEINVOLVED
class ModuleUninstallOperation(ModuleOperation):
"""
Manages the process to uninstall a module to this server
"""
def __init__(self):
"""
trivial
"""
ModuleOperation.__init__(self)
def do_workload(self):
"""
tell the module manager to install a specific module.
"""
module = Module.get_module_by_name(self._values["name"])
module_manager.uninstall_module(module)
def optimize_queue(self):
"""
optimizes the queue.
"""
pass #TODO Implement
#MODULEINVOLVED
class ModuleUpdateOperation(ModuleOperation):
"""
Manages the process to uninstall a module to this server
"""
def __init__(self):
"""
trivial
"""
ModuleOperation.__init__(self)
def do_workload(self):
"""
tell the module manager to install a specific module.
"""
module = Module.get_module_by_name(self._values["name"])
module_manager.update_module(module)
def optimize_queue(self):
"""
optimizes the queue.
"""
pass #TODO Implement
class FailOperation(Operation):
"""
For unittest purposes: An Operation that always fails
"""
def __init__(self):
"""
trivial
"""
Operation.__init__(self)
def do_workload(self):
"""
simply fail
"""
raise Exception("Failoperation failed")
class TestOperation(Operation):
"""
For unittest purposes: An Operation that always succeds
"""
def __init__(self):
"""
trivial
"""
Operation.__init__(self)
def do_workload(self):
"""
simply succeed
"""
pass
class OperationDaemon(Daemon):
"""
This is the deamon that runs to actually execute the scheduled operations
"""
def __init__(self, pidfile):
"""
Initialize the deamon
"""
Daemon.__init__(self,pidfile)
def stop(self):
configuration = Configuration()
if os.path.exists(configuration.get_entry("core.webpath")+"/scv_operating.lck"):
os.remove(configuration.get_entry("core.webpath")+"/scv_operating.lck")
Daemon.stop(self)
def run(self):
"""
Do work if there is work to do, otherwise check every two seconds for new work.
"""
while True:
while Operation.process_next():
pass
sleep(2)<|fim▁end|> | @classmethod
def retry_operation(cls,operation_id): |
<|file_name|>socket_bio_adapter.cc<|end_file_name|><|fim▁begin|>// Copyright 2016 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 "net/socket/socket_bio_adapter.h"
#include <string.h>
#include <algorithm>
#include "base/bind.h"
#include "base/feature_list.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/threading/thread_task_runner_handle.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/socket/socket.h"
#include "net/socket/stream_socket.h"
#include "net/ssl/openssl_ssl_util.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "starboard/memory.h"
#include "starboard/types.h"
#include "third_party/boringssl/src/include/openssl/bio.h"
namespace {
net::NetworkTrafficAnnotationTag kTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("socket_bio_adapter", R"(
semantics {
sender: "Socket BIO Adapter"
description:
"SocketBIOAdapter is used only internal to //net code as an internal "
"detail to implement a TLS connection for a Socket class, and is not "
"being called directly outside of this abstraction."
trigger:
"Establishing a TLS connection to a remote endpoint. There are many "
"different ways in which a TLS connection may be triggered, such as "
"loading an HTTPS URL."
data:
"All data sent or received over a TLS connection. This traffic may "
"either be the handshake or application data. During the handshake, "
"the target host name, user's IP, data related to previous "
"handshake, client certificates, and channel ID, may be sent. When "
"the connection is used to load an HTTPS URL, the application data "
"includes cookies, request headers, and the response body."
destination: OTHER
destination_other:
"Any destination the implementing socket is connected to."
}
policy {
cookies_allowed: NO
setting: "This feature cannot be disabled."
policy_exception_justification: "Essential for navigation."
})");
} // namespace
namespace net {
SocketBIOAdapter::SocketBIOAdapter(StreamSocket* socket,
int read_buffer_capacity,
int write_buffer_capacity,
Delegate* delegate)
: socket_(socket),
read_buffer_capacity_(read_buffer_capacity),
read_offset_(0),
read_result_(0),
write_buffer_capacity_(write_buffer_capacity),
write_buffer_used_(0),
write_error_(OK),
delegate_(delegate),
weak_factory_(this) {
bio_.reset(BIO_new(&kBIOMethod));
bio_->ptr = this;
bio_->init = 1;
read_callback_ = base::BindRepeating(&SocketBIOAdapter::OnSocketReadComplete,
weak_factory_.GetWeakPtr());
write_callback_ = base::BindRepeating(
&SocketBIOAdapter::OnSocketWriteComplete, weak_factory_.GetWeakPtr());
}
SocketBIOAdapter::~SocketBIOAdapter() {
// BIOs are reference-counted and may outlive the adapter. Clear the pointer
// so future operations fail.
bio_->ptr = nullptr;
}
bool SocketBIOAdapter::HasPendingReadData() {
return read_result_ > 0;
}
size_t SocketBIOAdapter::GetAllocationSize() const {
size_t buffer_size = 0;
if (read_buffer_)
buffer_size += read_buffer_capacity_;
if (write_buffer_)
buffer_size += write_buffer_capacity_;
return buffer_size;
}
int SocketBIOAdapter::BIORead(char* out, int len) {
if (len <= 0)
return len;
// If there is no result available synchronously, report any Write() errors
// that were observed. Otherwise the application may have encountered a socket
// error while writing that would otherwise not be reported until the
// application attempted to write again - which it may never do. See
// https://crbug.com/249848.
if (write_error_ != OK && write_error_ != ERR_IO_PENDING &&
(read_result_ == 0 || read_result_ == ERR_IO_PENDING)) {
OpenSSLPutNetError(FROM_HERE, write_error_);
return -1;
}
if (read_result_ == 0) {
// Instantiate the read buffer and read from the socket. Although only |len|
// bytes were requested, intentionally read to the full buffer size. The SSL
// layer reads the record header and body in separate reads to avoid
// overreading, but issuing one is more efficient. SSL sockets are not
// reused after shutdown for non-SSL traffic, so overreading is fine.
DCHECK(!read_buffer_);
DCHECK_EQ(0, read_offset_);
read_buffer_ = base::MakeRefCounted<IOBuffer>(read_buffer_capacity_);
int result = ERR_READ_IF_READY_NOT_IMPLEMENTED;
if (base::FeatureList::IsEnabled(Socket::kReadIfReadyExperiment)) {
result = socket_->ReadIfReady(
read_buffer_.get(), read_buffer_capacity_,
base::Bind(&SocketBIOAdapter::OnSocketReadIfReadyComplete,
weak_factory_.GetWeakPtr()));
if (result == ERR_IO_PENDING)
read_buffer_ = nullptr;
}
if (result == ERR_READ_IF_READY_NOT_IMPLEMENTED) {
result = socket_->Read(read_buffer_.get(), read_buffer_capacity_,
read_callback_);
}
if (result == ERR_IO_PENDING) {
read_result_ = ERR_IO_PENDING;
} else {
HandleSocketReadResult(result);
}
}
// There is a pending Read(). Inform the caller to retry when it completes.
if (read_result_ == ERR_IO_PENDING) {
BIO_set_retry_read(bio());
return -1;
}
// If the last Read() failed, report the error.
if (read_result_ < 0) {
OpenSSLPutNetError(FROM_HERE, read_result_);
return -1;
}
// Report the result of the last Read() if non-empty.
CHECK_LT(read_offset_, read_result_);
len = std::min(len, read_result_ - read_offset_);
memcpy(out, read_buffer_->data() + read_offset_, len);
read_offset_ += len;
// Release the buffer when empty.
if (read_offset_ == read_result_) {
read_buffer_ = nullptr;
read_offset_ = 0;
read_result_ = 0;
}
return len;
}
void SocketBIOAdapter::HandleSocketReadResult(int result) {
DCHECK_NE(ERR_IO_PENDING, result);
// If an EOF, canonicalize to ERR_CONNECTION_CLOSED here, so that higher
// levels don't report success.
if (result == 0)
result = ERR_CONNECTION_CLOSED;
read_result_ = result;
// The read buffer is no longer needed.
if (read_result_ <= 0)
read_buffer_ = nullptr;
}
void SocketBIOAdapter::OnSocketReadComplete(int result) {
DCHECK_EQ(ERR_IO_PENDING, read_result_);
HandleSocketReadResult(result);
delegate_->OnReadReady();
}
void SocketBIOAdapter::OnSocketReadIfReadyComplete(int result) {
DCHECK_EQ(ERR_IO_PENDING, read_result_);
DCHECK_GE(OK, result);
// Do not use HandleSocketReadResult() because result == OK doesn't mean EOF.
read_result_ = result;
delegate_->OnReadReady();
}
int SocketBIOAdapter::BIOWrite(const char* in, int len) {
if (len <= 0)
return len;
// If the write buffer is not empty, there must be a pending Write() to flush
// it.
DCHECK(write_buffer_used_ == 0 || write_error_ == ERR_IO_PENDING);
// If a previous Write() failed, report the error.
if (write_error_ != OK && write_error_ != ERR_IO_PENDING) {
OpenSSLPutNetError(FROM_HERE, write_error_);
return -1;
}
// Instantiate the write buffer if needed.
if (!write_buffer_) {
DCHECK_EQ(0, write_buffer_used_);
write_buffer_ = base::MakeRefCounted<GrowableIOBuffer>();
write_buffer_->SetCapacity(write_buffer_capacity_);
}
// If the ring buffer is full, inform the caller to try again later.
if (write_buffer_used_ == write_buffer_->capacity()) {
BIO_set_retry_write(bio());
return -1;
}
int bytes_copied = 0;
// If there is space after the offset, fill it.
if (write_buffer_used_ < write_buffer_->RemainingCapacity()) {
int chunk =
std::min(write_buffer_->RemainingCapacity() - write_buffer_used_, len);
memcpy(write_buffer_->data() + write_buffer_used_, in, chunk);
in += chunk;
len -= chunk;
bytes_copied += chunk;
write_buffer_used_ += chunk;
}
// If there is still space for remaining data, try to wrap around.
if (len > 0 && write_buffer_used_ < write_buffer_->capacity()) {
// If there were any room after the offset, the previous branch would have
// filled it.
CHECK_LE(write_buffer_->RemainingCapacity(), write_buffer_used_);
int write_offset = write_buffer_used_ - write_buffer_->RemainingCapacity();
int chunk = std::min(len, write_buffer_->capacity() - write_buffer_used_);
memcpy(write_buffer_->StartOfBuffer() + write_offset, in, chunk);
in += chunk;
len -= chunk;
bytes_copied += chunk;
write_buffer_used_ += chunk;
}
// Either the buffer is now full or there is no more input.
DCHECK(len == 0 || write_buffer_used_ == write_buffer_->capacity());
// Schedule a socket Write() if necessary. (The ring buffer may previously
// have been empty.)
SocketWrite();
// If a read-interrupting write error was synchronously discovered,
// asynchronously notify OnReadReady. See https://crbug.com/249848. Avoid
// reentrancy by deferring it to a later event loop iteration.
if (write_error_ != OK && write_error_ != ERR_IO_PENDING &&
read_result_ == ERR_IO_PENDING) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&SocketBIOAdapter::CallOnReadReady,
weak_factory_.GetWeakPtr()));
}
return bytes_copied;
}
void SocketBIOAdapter::SocketWrite() {
while (write_error_ == OK && write_buffer_used_ > 0) {
int write_size =
std::min(write_buffer_used_, write_buffer_->RemainingCapacity());
int result = socket_->Write(write_buffer_.get(), write_size,
write_callback_, kTrafficAnnotation);
if (result == ERR_IO_PENDING) {
write_error_ = ERR_IO_PENDING;
return;
}
HandleSocketWriteResult(result);
}
}
void SocketBIOAdapter::HandleSocketWriteResult(int result) {
DCHECK_NE(ERR_IO_PENDING, result);
if (result < 0) {
write_error_ = result;
// The write buffer is no longer needed.
write_buffer_ = nullptr;
write_buffer_used_ = 0;
return;
}
// Advance the ring buffer.
write_buffer_->set_offset(write_buffer_->offset() + result);
write_buffer_used_ -= result;
if (write_buffer_->RemainingCapacity() == 0)
write_buffer_->set_offset(0);
write_error_ = OK;
// Release the write buffer if empty.
if (write_buffer_used_ == 0)
write_buffer_ = nullptr;
}
void SocketBIOAdapter::OnSocketWriteComplete(int result) {
DCHECK_EQ(ERR_IO_PENDING, write_error_);
bool was_full = write_buffer_used_ == write_buffer_->capacity();
HandleSocketWriteResult(result);
SocketWrite();
// If transitioning from being unable to accept data to being able to, signal
// OnWriteReady.
if (was_full) {
base::WeakPtr<SocketBIOAdapter> guard(weak_factory_.GetWeakPtr());<|fim▁hole|> delegate_->OnWriteReady();
// OnWriteReady may delete the adapter.
if (!guard)
return;
}
// Write errors are fed back into BIO_read once the read buffer is empty. If
// BIO_read is currently blocked, signal early that a read result is ready.
if (result < 0 && read_result_ == ERR_IO_PENDING)
delegate_->OnReadReady();
}
void SocketBIOAdapter::CallOnReadReady() {
if (read_result_ == ERR_IO_PENDING)
delegate_->OnReadReady();
}
SocketBIOAdapter* SocketBIOAdapter::GetAdapter(BIO* bio) {
DCHECK_EQ(&kBIOMethod, bio->method);
SocketBIOAdapter* adapter = reinterpret_cast<SocketBIOAdapter*>(bio->ptr);
if (adapter)
DCHECK_EQ(bio, adapter->bio());
return adapter;
}
int SocketBIOAdapter::BIOWriteWrapper(BIO* bio, const char* in, int len) {
BIO_clear_retry_flags(bio);
SocketBIOAdapter* adapter = GetAdapter(bio);
if (!adapter) {
OpenSSLPutNetError(FROM_HERE, ERR_UNEXPECTED);
return -1;
}
return adapter->BIOWrite(in, len);
}
int SocketBIOAdapter::BIOReadWrapper(BIO* bio, char* out, int len) {
BIO_clear_retry_flags(bio);
SocketBIOAdapter* adapter = GetAdapter(bio);
if (!adapter) {
OpenSSLPutNetError(FROM_HERE, ERR_UNEXPECTED);
return -1;
}
return adapter->BIORead(out, len);
}
long SocketBIOAdapter::BIOCtrlWrapper(BIO* bio,
int cmd,
long larg,
void* parg) {
switch (cmd) {
case BIO_CTRL_FLUSH:
// The SSL stack requires BIOs handle BIO_flush.
return 1;
}
NOTIMPLEMENTED();
return 0;
}
const BIO_METHOD SocketBIOAdapter::kBIOMethod = {
0, // type (unused)
nullptr, // name (unused)
SocketBIOAdapter::BIOWriteWrapper,
SocketBIOAdapter::BIOReadWrapper,
nullptr, // puts
nullptr, // gets
SocketBIOAdapter::BIOCtrlWrapper,
nullptr, // create
nullptr, // destroy
nullptr, // callback_ctrl
};
} // namespace net<|fim▁end|> | |
<|file_name|>contents.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)
class Contents:
@logtool.log_call
def __init__ (self, canvas, objects):
self.canvas = canvas
self.objects = objects
@logtool.log_call<|fim▁hole|> for obj in self.objects:
coords = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_type, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render ()<|fim▁end|> | def render (self):
with Page (self.canvas) as pg: |
<|file_name|>merge-funtoo-staging.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
import os
import sys
from merge_utils import *
xml_out = etree.Element("packages")
funtoo_staging_w = GitTree("funtoo-staging", "master", "repos@localhost:ports/funtoo-staging.git", root="/var/git/dest-trees/funtoo-staging", pull=False, xml_out=xml_out)
#funtoo_staging_w = GitTree("funtoo-staging-unfork", "master", "repos@localhost:ports/funtoo-staging-unfork.git", root="/var/git/dest-trees/funtoo-staging-unfork", pull=False, xml_out=None)
xmlfile="/home/ports/public_html/packages.xml"
nopush=False
funtoo_overlay = GitTree("funtoo-overlay", "master", "repos@localhost:funtoo-overlay.git", pull=True)
# We treat our Gentoo staging overlay specially, so it's listed separately. This overlay contains all Gentoo
# ebuilds, in a git repository. We use a special file in the funtoo-overlay/funtoo/scripts directory (next to
# this file) to provide a SHA1 of the commit of the gentoo-staging overlay that we want to use as a basis
# for our merges. Let's grab the SHA1 hash from that file:
p = os.path.join(funtoo_overlay.root,"funtoo/scripts/commit-staged")
if os.path.exists(p):
a = open(p,"r")
commit = a.readlines()[0].strip()
print("Using commit: %s" % commit)
else:
commit = None
gentoo_staging_r = GitTree("gentoo-staging", "master", "repos@localhost:ports/gentoo-staging.git", commit=commit, pull=True)
# These overlays are monitored for changes -- if there are changes in these overlays, we regenerate the entire
# tree. If there aren't changes in these overlays, we don't.
shards = {
"perl" : GitTree("gentoo-perl-shard", "1fc10379b04cb4aaa29e824288f3ec22badc6b33", "repos@localhost:gentoo-perl-shard.git", pull=True),
"kde" : GitTree("gentoo-kde-shard", "cd4e1129ddddaa21df367ecd4f68aab894e57b31", "repos@localhost:gentoo-kde-shard.git", pull=True),
"gnome" : GitTree("gentoo-gnome-shard", "ffabb752f8f4e23a865ffe9caf72f950695e2f26", "repos@localhost:ports/gentoo-gnome-shard.git", pull=True),
"x11" : GitTree("gentoo-x11-shard", "12c1bdf9a9bfd28f48d66bccb107c17b5f5af577", "repos@localhost:ports/gentoo-x11-shard.git", pull=True),
"office" : GitTree("gentoo-office-shard", "9a702057d23e7fa277e9626344671a82ce59442f", "repos@localhost:ports/gentoo-office-shard.git", pull=True),
"core" : GitTree("gentoo-core-shard", "56e5b9edff7dc27e828b71010d019dcbd8e176fd", "repos@localhost:gentoo-core-shard.git", pull=True)
}
# perl: 1fc10379b04cb4aaa29e824288f3ec22badc6b33 (Updated 6 Dec 2016)
# kde: cd4e1129ddddaa21df367ecd4f68aab894e57b31 (Updated 25 Dec 2016)
# gnome: ffabb752f8f4e23a865ffe9caf72f950695e2f26 (Updated 20 Sep 2016)
# x11: 12c1bdf9a9bfd28f48d66bccb107c17b5f5af577 (Updated 24 Dec 2016)
# office: 9a702057d23e7fa277e9626344671a82ce59442f (Updated 29 Nov 2016)
# core: 56e5b9edff7dc27e828b71010d019dcbd8e176fd (Updated 17 Dec 2016)
# funtoo-toolchain: b97787318b7ffcfeaacde82cd21ddd5e207ad1f4 (Updated 25 Dec 2016)
funtoo_overlays = {
"funtoo_media" : GitTree("funtoo-media", "master", "repos@localhost:funtoo-media.git", pull=True),
"plex_overlay" : GitTree("funtoo-plex", "master", "https://github.com/Ghent/funtoo-plex.git", pull=True),
#"gnome_fixups" : GitTree("gnome-3.16-fixups", "master", "repos@localhost:ports/gnome-3.16-fixups.git", pull=True),
"gnome_fixups" : GitTree("gnome-3.20-fixups", "master", "repos@localhost:ports/gnome-3.20-fixups.git", pull=True),
"funtoo_toolchain" : GitTree("funtoo-toolchain", "b97787318b7ffcfeaacde82cd21ddd5e207ad1f4", "repos@localhost:funtoo-toolchain-overlay.git", pull=True),
"ldap_overlay" : GitTree("funtoo-ldap", "master", "repos@localhost:funtoo-ldap-overlay.git", pull=True),
"deadbeef_overlay" : GitTree("deadbeef-overlay", "master", "https://github.com/damex/deadbeef-overlay.git", pull=True),
"gambas_overlay" : GitTree("gambas-overlay", "master", "https://github.com/damex/gambas-overlay.git", pull=True),
"wmfs_overlay" : GitTree("wmfs-overlay", "master", "https://github.com/damex/wmfs-overlay.git", pull=True),
"flora" : GitTree("flora", "master", "repos@localhost:flora.git", pull=True),
}
# These are other overlays that we merge into the Funtoo tree. However, we just pull in the most recent versions
# of these when we regenerate our tree.
other_overlays = {
"foo_overlay" : GitTree("foo-overlay", "master", "https://github.com/slashbeast/foo-overlay.git", pull=True),
"bar_overlay" : GitTree("bar-overlay", "master", "git://github.com/adessemond/bar-overlay.git", pull=True),
"squeezebox_overlay" : GitTree("squeezebox", "master", "git://anongit.gentoo.org/user/squeezebox.git", pull=True),
"pantheon_overlay" : GitTree("pantheon", "master", "https://github.com/pimvullers/elementary.git", pull=True),
"pinsard_overlay" : GitTree("pinsard", "master", "https://github.com/apinsard/sapher-overlay.git", pull=True),
"sabayon_for_gentoo" : GitTree("sabayon-for-gentoo", "master", "git://github.com/Sabayon/for-gentoo.git", pull=True),
"tripsix_overlay" : GitTree("tripsix", "master", "https://github.com/666threesixes666/tripsix.git", pull=True),
"faustoo_overlay" : GitTree("faustoo", "master", "https://github.com/fmoro/faustoo.git", pull=True),
"wltjr_overlay" : GitTree("wltjr", "master", "https://github.com/Obsidian-StudiosInc/os-xtoo", pull=True),
"vmware_overlay" : GitTree("vmware", "master", "git://anongit.gentoo.org/proj/vmware.git", pull=True)
}
funtoo_changes = False
if funtoo_overlay.changes:
funtoo_changes = True
elif gentoo_staging_r.changes:
funtoo_changes = True
else:
for fo in funtoo_overlays:
if funtoo_overlays[fo].changes:
funtoo_changes = True
break
# This next code regenerates the contents of the funtoo-staging tree. Funtoo's tree is itself composed of
# many different overlays which are merged in an automated fashion. This code does it all.
pull = True
if nopush:
push = False
else:
push = "master"
# base_steps define the initial steps that prepare our destination tree for writing. Checking out the correct
# branch, copying almost the full entirety of Gentoo's portage tree to our destination tree, and copying over
# funtoo overlay licenses, metadata, and also copying over GLSA's.
base_steps = [
GitCheckout("master"),
SyncFromTree(gentoo_staging_r, exclude=[
"/metadata/cache/**",
"ChangeLog",
"dev-util/metro",
"skel.ChangeLog",
]),
]
# Steps related to generating system profiles. These can be quite order-dependent and should be handled carefully.
# Generally, the funtoo_overlay sync should be first, then the gentoo_staging_r SyncFiles, which overwrites some stub
# files in the funtoo overlay.
profile_steps = [
SyncDir(funtoo_overlay.root, "profiles", "profiles", exclude=["categories", "updates"]),
CopyAndRename("profiles/funtoo/1.0/linux-gnu/arch/x86-64bit/subarch", "profiles/funtoo/1.0/linux-gnu/arch/pure64/subarch", lambda x: os.path.basename(x) + "-pure64"),
SyncFiles(gentoo_staging_r.root, {
"profiles/package.mask":"profiles/package.mask/00-gentoo",
"profiles/arch/amd64/package.use.mask":"profiles/funtoo/1.0/linux-gnu/arch/x86-64bit/package.use.mask/01-gentoo",
"profiles/features/multilib/package.use.mask":"profiles/funtoo/1.0/linux-gnu/arch/x86-64bit/package.use.mask/02-gentoo",
"profiles/arch/amd64/use.mask":"profiles/funtoo/1.0/linux-gnu/arch/x86-64bit/use.mask/01-gentoo",
"profiles/arch/x86/package.use.mask":"profiles/funtoo/1.0/linux-gnu/arch/x86-32bit/package.use.mask/01-gentoo",
"profiles/arch/x86/use.mask":"profiles/funtoo/1.0/linux-gnu/arch/x86-32bit/use.mask/01-gentoo",
"profiles/default/linux/package.use.mask":"profiles/funtoo/1.0/linux-gnu/package.use.mask/01-gentoo",
"profiles/default/linux/use.mask":"profiles/funtoo/1.0/linux-gnu/use.mask/01-gentoo",
"profiles/arch/amd64/no-multilib/package.use.mask":"profiles/funtoo/1.0/linux-gnu/arch/pure64/package.use.mask/01-gentoo",
"profiles/arch/amd64/no-multilib/package.mask":"profiles/funtoo/1.0/linux-gnu/arch/pure64/package.mask/01-gentoo",
"profiles/arch/amd64/no-multilib/use.mask":"profiles/funtoo/1.0/linux-gnu/arch/pure64/use.mask/01-gentoo"
}),
SyncFiles(funtoo_overlays["deadbeef_overlay"].root, {
"profiles/package.mask":"profiles/package.mask/deadbeef-mask"
}),
SyncFiles(funtoo_overlays["wmfs_overlay"].root, {
"profiles/package.mask":"profiles/package.mask/wmfs-mask"
}) ]
profile_steps += [
SyncFiles(funtoo_overlays["funtoo_toolchain"].root, {
"profiles/package.mask/funtoo-toolchain":"profiles/funtoo/1.0/linux-gnu/build/current/package.mask/funtoo-toolchain",
}),
SyncFiles(funtoo_overlays["funtoo_toolchain"].root, {
"profiles/package.mask/funtoo-toolchain":"profiles/funtoo/1.0/linux-gnu/build/stable/package.mask/funtoo-toolchain",
"profiles/package.mask/funtoo-toolchain-experimental":"profiles/funtoo/1.0/linux-gnu/build/experimental/package.mask/funtoo-toolchain",
}),
RunSed(["profiles/base/make.defaults"], ["/^PYTHON_TARGETS=/d", "/^PYTHON_SINGLE_TARGET=/d"]),
]
# Steps related to copying ebuilds. Note that order can make a difference here when multiple overlays are
# providing identical catpkgs.
# Ebuild additions -- these are less-risky changes because ebuilds are only added, and not replaced.
ebuild_additions = [
InsertEbuilds(other_overlays["bar_overlay"], select="all", skip=["app-emulation/qemu"], replace=False),
InsertEbuilds(other_overlays["squeezebox_overlay"], select="all", skip=None, replace=False),
InsertEbuilds(funtoo_overlays["deadbeef_overlay"], select="all", skip=None, replace=False),
InsertEbuilds(funtoo_overlays["gambas_overlay"], select="all", skip=None, replace=False),
InsertEbuilds(funtoo_overlays["wmfs_overlay"], select="all", skip=None, replace=False),
InsertEbuilds(funtoo_overlays["flora"], select="all", skip=None, replace=True, merge=True),
]
# Ebuild modifications -- these changes need to be treated more carefully as ordering can be important
# for wholesale replacing as well as merging.
ebuild_modifications = [
InsertEbuilds(other_overlays["vmware_overlay"], select=[ "app-emulation/vmware-modules" ], skip=None, replace=True, merge=True),
InsertEbuilds(other_overlays["pantheon_overlay"], select=[ "x11-libs/granite", "x11-libs/bamf", "x11-themes/plank-theme-pantheon", "pantheon-base/plank", "x11-wm/gala"], skip=None, replace=True, merge=True),
InsertEbuilds(other_overlays["faustoo_overlay"], select="all", skip=None, replace=True, merge=True),
InsertEbuilds(other_overlays["foo_overlay"], select="all", skip=["sys-fs/mdev-bb", "sys-fs/mdev-like-a-boss", "media-sound/deadbeef", "media-video/handbrake"], replace=["app-shells/rssh"]),
InsertEbuilds(funtoo_overlays["plex_overlay"], select=[ "media-tv/plex-media-server" ], skip=None, replace=True),
InsertEbuilds(other_overlays["sabayon_for_gentoo"], select=["app-admin/equo", "app-admin/matter", "sys-apps/entropy", "sys-apps/entropy-server", "sys-apps/entropy-client-services","app-admin/rigo", "sys-apps/rigo-daemon", "sys-apps/magneto-core", "x11-misc/magneto-gtk", "x11-misc/magneto-gtk3", "x11-themes/numix-icon-theme", "kde-misc/magneto-kde", "app-misc/magneto-loader", "media-video/kazam" ], replace=True),
InsertEbuilds(other_overlays["tripsix_overlay"], select=["media-sound/rakarrack"], skip=None, replace=True, merge=False),
InsertEbuilds(other_overlays["pinsard_overlay"], select=["app-portage/chuse", "dev-python/iwlib", "media-sound/pytify", "x11-wm/qtile"], skip=None, replace=True, merge=True),
InsertEbuilds(other_overlays["wltjr_overlay"], select=["mail-filter/assp", "mail-mta/netqmail"], skip=None, replace=True, merge=False),
]
ebuild_modifications += [
InsertEbuilds(funtoo_overlays["funtoo_media"], select="all", skip=None, replace=True),
InsertEbuilds(funtoo_overlays["ldap_overlay"], select="all", skip=["net-nds/openldap"], replace=True),
]
# Steps related to eclass copying:<|fim▁hole|>]
# General tree preparation steps -- finishing touches. This is where you should put steps that require all ebuilds
# from all trees to all be inserted (like AutoGlobMask calls) as well as misc. copying of files like licenses and
# updates files. It also contains misc. tweaks like mirror fixups and Portage tree minification.
treeprep_steps = [
SyncDir(funtoo_overlays["plex_overlay"].root,"licenses"),
]
master_steps = [
InsertEbuilds(shards["perl"], select="all", skip=None, replace=True),
InsertEclasses(shards["perl"], select=re.compile(".*\.eclass")),
InsertEbuilds(shards["x11"], select="all", skip=None, replace=True),
InsertEbuilds(shards["office"], select="all", skip=None, replace=True),
InsertEbuilds(shards["kde"], select="all", skip=None, replace=True),
InsertEclasses(shards["kde"], select=re.compile(".*\.eclass")),
InsertEbuilds(shards["gnome"], select="all", skip=None, replace=True),
InsertEbuilds(funtoo_overlays["gnome_fixups"], select="all", skip=None, replace=True),
InsertEbuilds(shards["core"], select="all", skip=None, replace=True),
InsertEclasses(shards["core"], select=re.compile(".*\.eclass")),
InsertEbuilds(funtoo_overlays["funtoo_toolchain"], select="all", skip=None, replace=True, merge=False),
InsertEbuilds(funtoo_overlay, select="all", skip=None, replace=True),
SyncDir(funtoo_overlay.root, "eclass"),
SyncDir(funtoo_overlay.root,"licenses"),
SyncDir(funtoo_overlay.root,"metadata"),
SyncFiles(funtoo_overlay.root, {
"COPYRIGHT.txt":"COPYRIGHT.txt",
"LICENSE.txt":"LICENSE.txt",
"README.rst":"README.rst",
"header.txt":"header.txt",
}),
]
treeprep_steps += [
MergeUpdates(funtoo_overlay.root),
AutoGlobMask("dev-lang/python", "python*_pre*", "funtoo-python_pre"),
ThirdPartyMirrors(),
ProfileDepFix(),
Minify(),
# Set name of repository as "gentoo". Unset masters.
RunSed(["metadata/layout.conf"], ["s/^repo-name = .*/repo-name = gentoo/", "/^masters =/d"]),
RunSed(["profiles/repo_name"], ["s/.*/gentoo/"])
]
all_steps = [ base_steps, profile_steps, ebuild_additions, eclass_steps, master_steps, ebuild_modifications, treeprep_steps ]
for step in all_steps:
funtoo_staging_w.run(step)
funtoo_staging_w.gitCommit(message="glorious funtoo updates",branch=push)
if xmlfile:
a=open(xmlfile,"wb")
etree.ElementTree(xml_out).write(a, encoding='utf-8', xml_declaration=True, pretty_print=True)
a.close()
print("merge-funtoo-staging.py completed successfully.")
sys.exit(0)
# vim: ts=4 sw=4 noet<|fim▁end|> |
eclass_steps = [
SyncDir(funtoo_overlays["deadbeef_overlay"].root,"eclass"),
|
<|file_name|>test_contacts_data_compliance.py<|end_file_name|><|fim▁begin|>import re
from models.contact import Contact
def test_all_contacts_on_homepage(app, db):
if app.contact.count() == 0:
app.contact.add(Contact(first_name="Mister", last_name="Muster", mobile_phone="123", email_1="[email protected]"))
contacts_from_homepage = sorted(app.contact.get_contact_list(), key = Contact.contact_id_or_max)
contacts_from_db = sorted(db.get_contact_list(), key = Contact.contact_id_or_max)
for i in range(len(contacts_from_homepage)):
hp_contact=contacts_from_homepage[i]
db_contact=contacts_from_db[i]
assert hp_contact.first_name == db_contact.first_name
assert hp_contact.last_name == db_contact.last_name
assert clear_address(hp_contact.address) == clear_address(db_contact.address)
assert clear_phone(hp_contact.all_phones_homepage) == clear_phone(merge_phones_homepage(db_contact))
assert hp_contact.all_emails_homepage == merge_emails_homepage(db_contact)
print("Successfully verified %s contacts vs Database" % str(len(contacts_from_homepage)))
"""def test_contact_on_homepage(app):
if app.contact.count() == 0:
app.contact.add(Contact(first_name="Mister", last_name="Muster", mobile_phone="123", email_1="[email protected]"))
index = randrange(len(app.contact.get_contact_list()))
contact_from_homepage = app.contact.get_contact_list()[index]
contact_from_editpage = app.contact.get_contact_data_editpage(index)
assert contact_from_homepage.first_name == contact_from_editpage.first_name
assert contact_from_homepage.last_name == contact_from_editpage.last_name
assert contact_from_homepage.address == contact_from_editpage.address
assert contact_from_homepage.all_phones_homepage == merge_phones_homepage(contact_from_editpage)
assert contact_from_homepage.all_emails_homepage == merge_emails_homepage(contact_from_editpage)"""
"""def test_phones_on_viewpage(app):
contact_from_viewpage = app.contact.get_contact_data_viewpage(0)
contact_from_editpage = app.contact.get_contact_data_editpage(0)
assert contact_from_viewpage.home_phone == contact_from_editpage.home_phone
assert contact_from_viewpage.work_phone == contact_from_editpage.work_phone
assert contact_from_viewpage.mobile_phone == contact_from_editpage.mobile_phone
assert contact_from_viewpage.fax == contact_from_editpage.fax"""
def clear(s):
#return "".join(symbol for symbol in s if symbol not in "[]()- 0")
return re.sub("[- ()]", "", s)
def clear_phone(number):
return re.sub("0", "", number)
def clear_address(address):
return re.sub("[\n\r\s+]", "", address)
def merge_phones_homepage(contact):
return "\n".join(filter(lambda x: x != "",<|fim▁hole|>
def merge_emails_homepage(contact):
return "\n".join(filter(lambda x: x != "", filter(lambda x: x is not None,
[contact.email_1, contact.email_2, contact.email_3])))<|fim▁end|> | map(lambda x: clear(x),
filter(lambda x: x is not None,
[contact.home_phone, contact.mobile_phone, contact.work_phone])))) |
<|file_name|>isprime.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# isprime.py
#
# Author: Billy Wilson Arante
# Created: 2016/06/16 PHT
# Modified: 2016/10/01 EDT (America/New York)
from sys import argv
def isprime(x):<|fim▁hole|>
"""
if x <= 1:
return False
for n in range(2, (x - 1)):
if x % n == 0:
return False
return True
def main():
"""Main"""
filename, number = argv
print isprime(int(number))
if __name__ == "__main__":
main()<|fim▁end|> | """Checks if x is prime number
Returns true if x is a prime number, otherwise false. |
<|file_name|>test_weekday.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0<|fim▁hole|># KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import unittest
from enum import Enum
from airflow.utils.weekday import WeekDay
class TestWeekDay(unittest.TestCase):
def test_weekday_enum_length(self):
assert len(WeekDay) == 7
def test_weekday_name_value(self):
weekdays = "MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY"
weekdays = weekdays.split()
for i, weekday in enumerate(weekdays, start=1):
weekday_enum = WeekDay(i)
assert weekday_enum == i
assert int(weekday_enum) == i
assert weekday_enum.name == weekday
assert weekday_enum in WeekDay
assert 0 < weekday_enum < 8
assert isinstance(weekday_enum, WeekDay)
assert isinstance(weekday_enum, int)
assert isinstance(weekday_enum, Enum)<|fim▁end|> | #
# 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 |
<|file_name|>types.ts<|end_file_name|><|fim▁begin|>import { InjectionToken, TemplateRef } from '@angular/core';
import { Observable } from 'rxjs';
import { Portal } from '@angular/cdk/portal';
<|fim▁hole|>export type TooltipPosition = 'left' | 'right' | 'top' | 'bottom';
export type TooltipPositions = TooltipPosition | [TooltipPosition];
export interface Tooltip {
arrowPosition?: TooltipPosition;
arrowPointer: boolean;
value?: string | Portal<any>;
stateChanged: Observable<any>;
}
export const TOOLTIP_TOKEN = new InjectionToken<Tooltip>('vcl_tooltip');<|fim▁end|> | |
<|file_name|>anoncoin_pt_PT.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_PT" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Anoncoin Core</source>
<translation>Sobre o Anoncoin Core</translation>
</message>
<message>
<location line="+39"/>
<source><b>Anoncoin Core</b> version</source>
<translation>versão do <b>Anoncoin Core</b></translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Este é um programa experimental.
Distribuído sob uma licença de software MIT/X11, por favor verifique o ficheiro anexo license.txt ou http://www.opensource.org/licenses/mit-license.php.
Este produto inclui software desenvolvido pelo Projecto OpenSSL para uso no OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por Eric Young ([email protected]) e software UPnP escrito por Thomas Bernard.</translation>
</message>
<message>
<location filename="../utilitydialog.cpp" line="+30"/>
<location line="+1"/>
<location line="+1"/>
<location line="+1"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="-3"/>
<source>The Anoncoin Core developers</source>
<translation>Os programadores Anoncoin Core</translation>
</message>
<message>
<location line="+1"/>
<source>The Bitcoin Core developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The Litecoin Core developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The Primecoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<location line="+2"/>
<source>(%1-bit)</source>
<translation>(%1-bit)</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+30"/>
<source>Double-click to edit address or label</source>
<translation>Clique duas vezes para editar o endereço ou o rótulo</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Criar um novo endereço</translation>
</message>
<message>
<location line="+3"/>
<source>&New</source>
<translation>&Novo</translation>
</message>
<message>
<location line="+11"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copiar o endereço selecionado para a área de transferência</translation>
</message>
<message>
<location line="+3"/>
<source>&Copy</source>
<translation>&Copiar</translation>
</message>
<message>
<location line="+11"/>
<source>Delete the currently selected address from the list</source>
<translation>Apagar o endereço selecionado da lista</translation>
</message>
<message>
<location line="+3"/>
<source>&Delete</source>
<translation>E&liminar\</translation>
</message>
<message>
<location line="+24"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar os dados no separador actual para um ficheiro</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Exportar</translation>
</message>
<message>
<location line="+17"/>
<source>C&lose</source>
<translation>F&echar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+45"/>
<source>Choose the address to send coins to</source>
<translation>Escolha o endereço para o qual pretende enviar moedas</translation>
</message>
<message>
<location line="+1"/>
<source>Choose the address to receive coins with</source>
<translation>Escolha o endereço com o qual pretende receber moedas</translation>
</message>
<message>
<location line="+5"/>
<source>C&hoose</source>
<translation>Escol&her</translation>
</message>
<message>
<location line="+6"/>
<source>Sending addresses</source>
<translation>Endereços de envio</translation>
</message>
<message>
<location line="+1"/>
<source>Receiving addresses</source>
<translation>Endereços de depósito</translation>
</message>
<message>
<location line="+7"/>
<source>These are your Anoncoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Estes são os seus endereços Anoncoin para enviar pagamentos. Verifique sempre o valor e o endereço de envio antes de enviar moedas.</translation>
</message>
<message>
<location line="+4"/>
<source>These are your Anoncoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation>Estes são os seus endereços Anoncoin para receber pagamentos. É recomendado que utilize um endereço novo para cada transacção.</translation>
</message>
<message>
<location line="+6"/>
<source>&Copy Address</source>
<translation>&Copiar Endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Copy &Label</source>
<translation>Copiar &Rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+194"/>
<source>Export Address List</source>
<translation>Exportar Lista de Endereços</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Ficheiro separado por vírgulas (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Exporting Failed</source>
<translation>A Exportação Falhou</translation>
</message>
<message>
<location line="+1"/>
<source>There was an error trying to save the address list to %1.</source>
<translation>Ocorreu um erro ao tentar guardar a lista de endereços em %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+169"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sem rótulo)</translation>
</message>
</context>
<context>
<name>AnoncoinGUI</name>
<message>
<location filename="../anoncoingui.cpp" line="+82"/>
<source>Anoncoin Core</source>
<translation>Anoncoin Core</translation>
</message>
<message>
<location line="+9"/>
<source>Wallet</source>
<translation>Carteira</translation>
</message>
<message>
<location line="+2"/>
<source>Node</source>
<translation>Nó</translation>
</message>
<message>
<location line="+14"/>
<location line="+427"/>
<source>[testnet]</source>
<translation>[rede de testes]</translation>
</message>
<message>
<location line="-290"/>
<source>&Overview</source>
<translation>Visã&o geral</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Mostrar visão geral da carteira</translation>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation>&Enviar</translation>
</message>
<message>
<location line="+1"/>
<source>Send coins to a Anoncoin address</source>
<translation>Enviar moedas para um endereço anoncoin</translation>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation>&Receber</translation>
</message>
<message>
<location line="+1"/>
<source>Request payments (generates QR codes and anoncoin: URIs)</source>
<translation>Solicitar pagamentos (gera códigos QR e URIs anoncoin:)</translation>
</message>
<message>
<location line="+6"/>
<source>&Transactions</source>
<translation>&Transações</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Navegar pelo histórico de transações</translation>
</message>
<message>
<location line="+17"/>
<source>E&xit</source>
<translation>Fec&har</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Sair da aplicação</translation>
</message>
<message>
<location line="+4"/>
<location line="+2"/>
<source>&About Anoncoin Core</source>
<translation>&Sobre o Anoncoin Core</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Anoncoin</source>
<translation>Mostrar informação sobre o Anoncoin</translation>
</message>
<message>
<location line="+3"/>
<location line="+2"/>
<source>About &Qt</source>
<translation>Sobre &Qt</translation>
</message>
<message>
<location line="+2"/>
<source>Show information about Qt</source>
<translation>Mostrar informação sobre Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opções...</translation>
</message>
<message><|fim▁hole|> <location line="+1"/>
<source>Modify configuration options for Anoncoin</source>
<translation>Modificar opções de configuração para anoncoin</translation>
</message>
<message>
<location line="+3"/>
<location line="+2"/>
<source>&Show / Hide</source>
<translation>Mo&strar / Ocultar</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Mostrar ou esconder a janela principal</translation>
</message>
<message>
<location line="+2"/>
<source>&Encrypt Wallet...</source>
<translation>E&ncriptar Carteira...</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Encriptar as chaves privadas que pertencem à sua carteira</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>&Guardar Carteira...</translation>
</message>
<message>
<location line="+1"/>
<source>Backup wallet to another location</source>
<translation>Faça uma cópia de segurança da carteira para outra localização</translation>
</message>
<message>
<location line="+1"/>
<source>&Change Passphrase...</source>
<translation>Mudar &Palavra-passe...</translation>
</message>
<message>
<location line="+1"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Mudar a frase de segurança utilizada na encriptação da carteira</translation>
</message>
<message>
<location line="+1"/>
<source>Sign &message...</source>
<translation>Assinar &mensagem...</translation>
</message>
<message>
<location line="+1"/>
<source>Sign messages with your Anoncoin addresses to prove you own them</source>
<translation>Assine mensagens com os seus endereços Anoncoin para provar que os controla</translation>
</message>
<message>
<location line="+1"/>
<source>&Verify message...</source>
<translation>&Verificar mensagem...</translation>
</message>
<message>
<location line="+1"/>
<source>Verify messages to ensure they were signed with specified Anoncoin addresses</source>
<translation>Verifique mensagens para assegurar que foram assinadas com o endereço Anoncoin especificado</translation>
</message>
<message>
<location line="+2"/>
<source>&Debug window</source>
<translation>Janela de &depuração</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Abrir consola de diagnóstico e depuração</translation>
</message>
<message>
<location line="+2"/>
<source>&Sending addresses...</source>
<translation>A &enviar endereços...</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of used sending addresses and labels</source>
<translation>Mostrar a lista de rótulos e endereços de envio usados</translation>
</message>
<message>
<location line="+1"/>
<source>&Receiving addresses...</source>
<translation>A &receber endereços...</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of used receiving addresses and labels</source>
<translation>Mostrar a lista de rótulos e endereços de receção usados</translation>
</message>
<message>
<location line="+2"/>
<source>Open &URI...</source>
<translation>Abrir &URI...</translation>
</message>
<message>
<location line="+1"/>
<source>Open a anoncoin: URI or payment request</source>
<translation>Abrir URI anoncoin: ou pedido de pagamento</translation>
</message>
<message>
<location line="+2"/>
<source>&Command-line options</source>
<translation>Opções da linha de &comandos</translation>
</message>
<message>
<location line="+1"/>
<source>Show the Anoncoin Core help message to get a list with possible Anoncoin command-line options</source>
<translation>Mostrar a mensagem de ajuda do Anoncoin Core para obter uma lista com possíveis opções de linha de comandos</translation>
</message>
<message>
<location line="+34"/>
<source>&File</source>
<translation>&Ficheiro</translation>
</message>
<message>
<location line="+14"/>
<source>&Settings</source>
<translation>Con&figurações</translation>
</message>
<message>
<location line="+9"/>
<source>&Help</source>
<translation>A&juda</translation>
</message>
<message>
<location line="+15"/>
<source>Tabs toolbar</source>
<translation>Barra de separadores</translation>
</message>
<message>
<location line="+29"/>
<source>Wallet is using I2P-network only!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Wallet is using Tor-network only</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Wallet is using I2P and Tor networks (Darknet mode)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Wallet is using I2P and Tor networks, also Tor as a proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Wallet is using mixed or non-I2P (clear) network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Wallet is running with a random generated I2P-address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Wallet is running with a static I2P-address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<location line="+5"/>
<source>Anoncoin client</source>
<translation>Cliente Anoncoin</translation>
</message>
<message numerus="yes">
<location line="+155"/>
<source>%n active connection(s) to Anoncoin clearnet peers</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+16"/>
<source>%n active connection(s) to I2P-Anoncoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+14"/>
<source>Synchronizing with network...</source>
<translation>A sincronizar com a rede...</translation>
</message>
<message>
<location line="+3"/>
<source>Importing blocks from disk...</source>
<translation>A importar blocos do disco...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>A reindexar blocos no disco...</translation>
</message>
<message>
<location line="+4"/>
<source>No block source available...</source>
<translation>Nenhuma fonte de blocos disponível...</translation>
</message>
<message>
<location line="+10"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Processados %1 blocos do histórico de transações.</translation>
</message>
<message>
<location line="+5"/>
<source>Up to date</source>
<translation>Atualizado</translation>
</message>
<message numerus="yes">
<location line="+21"/>
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation>%1 e %2</translation>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation><numerusform>%n ano</numerusform><numerusform>%n anos</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 em atraso</translation>
</message>
<message>
<location line="+5"/>
<source>Catching up...</source>
<translation>Recuperando o atraso...</translation>
</message>
<message>
<location line="+16"/>
<source>Last received block was generated %1 ago.</source>
<translation>O último bloco recebido foi gerado %1 atrás.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transações posteriores não serão visíveis por enquanto.</translation>
</message>
<message>
<location line="+13"/>
<source>Anoncoin</source>
<translation>Anoncoin</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Erro</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Informação</translation>
</message>
<message>
<location line="+79"/>
<source>Sent transaction</source>
<translation>Transação enviada</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transação recebida</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Quantia: %2
Tipo: %3
Endereço: %4</translation>
</message>
<message>
<location line="+69"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>A carteira está <b>encriptada</b> e atualmente <b>desbloqueada</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>A carteira está <b>encriptada</b> e atualmente <b>bloqueada</b></translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Diálogo de frase de segurança</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Insira a frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nova frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repita a nova frase de segurança</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+41"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Insira a nova frase de segurança da sua carteira.<br/>Por favor, use uma frase de <b>10 ou mais caracteres aleatórios,</b> ou <b>oito ou mais palavras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Encriptar carteira</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquear carteira</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Desencriptar carteira</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Alterar frase de segurança</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Escreva a antiga frase de segurança da carteira, seguida da nova.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirmar encriptação da carteira</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR ANONCOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Tem a certeza que deseja encriptar a carteira?</translation>
</message>
<message>
<location line="+9"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Carteira encriptada</translation>
</message>
<message>
<location line="-56"/>
<source>Anoncoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your anoncoins from being stolen by malware infecting your computer.</source>
<translation>O cliente Anoncoin irá agora ser fechado para terminar o processo de encriptação. Recorde que a encriptação da sua carteira não protegerá totalmente os seus anoncoins de serem roubados por programas maliciosos que infectem o seu computador.</translation>
</message>
<message>
<location line="+4"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANTE: Qualquer cópia de segurança da carteira anterior deverá ser substituída com o novo ficheiro de carteira, agora encriptado. Por razões de segurança, cópias de segurança não encriptadas tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation>
</message>
<message>
<location line="+9"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>A encriptação da carteira falhou</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>As frases de segurança fornecidas não coincidem.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>O desbloqueio da carteira falhou</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>A desencriptação da carteira falhou</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>A frase de segurança da carteira foi alterada com êxito.</translation>
</message>
<message>
<location line="+47"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Atenção: A tecla Caps Lock está activa!</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+143"/>
<source>Network Alert</source>
<translation>Alerta da Rede</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control Address Selection</source>
<translation>Seleção de Endereço Coin Control</translation>
</message>
<message>
<location line="+34"/>
<source>Quantity:</source>
<translation>Quantidade:</translation>
</message>
<message>
<location line="+29"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+45"/>
<source>Amount:</source>
<translation>Quantia:</translation>
</message>
<message>
<location line="+29"/>
<source>Priority:</source>
<translation>Prioridade:</translation>
</message>
<message>
<location line="+45"/>
<source>Fee:</source>
<translation>Taxa:</translation>
</message>
<message>
<location line="+32"/>
<source>Low Output:</source>
<translation>Saída Baixa:</translation>
</message>
<message>
<location line="+48"/>
<source>After Fee:</source>
<translation>Depois da Taxa:</translation>
</message>
<message>
<location line="+32"/>
<source>Change:</source>
<translation>Troco:</translation>
</message>
<message>
<location line="+56"/>
<source>(un)select all</source>
<translation>(des)seleccionar todos</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Modo árvore</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Modo lista</translation>
</message>
<message>
<location line="+53"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+10"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmados</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmada</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioridade</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+42"/>
<source>Copy address</source>
<translation>Copiar endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar rótulo</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copiar ID da transação</translation>
</message>
<message>
<location line="+1"/>
<source>Lock unspent</source>
<translation>Bloquear não gastos</translation>
</message>
<message>
<location line="+1"/>
<source>Unlock unspent</source>
<translation>Desbloquear não gastos</translation>
</message>
<message>
<location line="+22"/>
<source>Copy quantity</source>
<translation>Copiar quantidade</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Copiar taxa</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copiar valor após taxa</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copiar prioridade</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar output baixo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar alteração</translation>
</message>
<message>
<location line="+332"/>
<source>highest</source>
<translation>muito alta</translation>
</message>
<message>
<location line="+1"/>
<source>higher</source>
<translation>mais alta</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>alta</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>média-alta</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>média</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>média-baixa</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>baixa</translation>
</message>
<message>
<location line="+1"/>
<source>lower</source>
<translation>mais baixa</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>muito alta</translation>
</message>
<message>
<location line="+11"/>
<source>(%1 locked)</source>
<translation>(%1 bloqueados)</translation>
</message>
<message>
<location line="+32"/>
<source>none</source>
<translation>nenhum</translation>
</message>
<message>
<location line="+141"/>
<source>Dust</source>
<translation>Pó</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>sim</translation>
</message>
<message>
<location line="+0"/>
<source>no</source>
<translation>não</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is greater than 1000 bytes.</source>
<translation>Este rótulo fica vermelha se o tamanho da transacção exceder os 1000 bytes.</translation>
</message>
<message>
<location line="+1"/>
<location line="+5"/>
<source>This means a fee of at least %1 per kB is required.</source>
<translation>Isto significa que uma taxa de pelo menos %1 por kB é necessária.</translation>
</message>
<message>
<location line="-4"/>
<source>Can vary +/- 1 byte per input.</source>
<translation>Pode variar +/- 1 byte por input.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions with higher priority are more likely to get included into a block.</source>
<translation>Transacções com uma prioridade mais alta têm uma maior probabilidade de serem incluídas num bloco.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the priority is smaller than "medium".</source>
<translation>Esta legenda fica vermelha, se a prioridade for menor que "média".</translation>
</message>
<message>
<location line="+3"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.</source>
<translation>Este rótulo fica vermelho se algum recipiente receber uma quantia menor que %1.</translation>
</message>
<message>
<location line="+1"/>
<location line="+4"/>
<source>This means a fee of at least %1 is required.</source>
<translation>Isto significa que uma taxa de pelo menos %1 é necessária.</translation>
</message>
<message>
<location line="-3"/>
<source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source>
<translation>Quantias abaixo de 0.546 vezes a taxa mínima de retransmissão são mostradas como "pó".</translation>
</message>
<message>
<location line="+2"/>
<source>This label turns red, if the change is smaller than %1.</source>
<translation>Esta legenda fica vermelha, se o troco for menor do que %1.</translation>
</message>
<message>
<location line="+43"/>
<location line="+61"/>
<source>(no label)</source>
<translation>(sem rótulo)</translation>
</message>
<message>
<location line="-7"/>
<source>change from %1 (%2)</source>
<translation>troco de %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(troco)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Endereço</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Rótulo</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address list entry</source>
<translation>O rótulo associado com esta entrada no livro de endereços</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>E&ndereço</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation>O endereço associado com o esta entrada no livro de endereços. Isto só pode ser modificado para endereços de saída.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+29"/>
<source>New receiving address</source>
<translation>Novo endereço de entrada</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Novo endereço de saída</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar endereço de entrada</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar endereço de saída</translation>
</message>
<message>
<location line="+71"/>
<source>The entered address "%1" is not a valid Anoncoin address.</source>
<translation>O endereço introduzido "%1" não é um endereço anoncoin válido.</translation>
</message>
<message>
<location line="+5"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>O endereço introduzido "%1" já se encontra no livro de endereços.</translation>
</message>
<message>
<location line="+5"/>
<source>Could not unlock wallet.</source>
<translation>Impossível desbloquear carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Falha ao gerar nova chave.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<location filename="../intro.cpp" line="+69"/>
<source>A new data directory will be created.</source>
<translation>Uma nova pasta de dados será criada.</translation>
</message>
<message>
<location line="+22"/>
<source>name</source>
<translation>nome</translation>
</message>
<message>
<location line="+2"/>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation>A pasta já existe. Adicione %1 se pretender criar aqui uma nova pasta.</translation>
</message>
<message>
<location line="+3"/>
<source>Path already exists, and is not a directory.</source>
<translation>Caminho já existe, e não é uma pasta.</translation>
</message>
<message>
<location line="+7"/>
<source>Cannot create data directory here.</source>
<translation>Não pode ser criada uma pasta de dados aqui.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<location filename="../forms/helpmessagedialog.ui" line="+19"/>
<source>Anoncoin Core - Command-line options</source>
<translation>Anoncoin Core - Opções de linha de comandos</translation>
</message>
<message>
<location filename="../utilitydialog.cpp" line="+24"/>
<source>Anoncoin Core</source>
<translation>Anoncoin Core</translation>
</message>
<message>
<location line="+0"/>
<source>version</source>
<translation>versão</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Utilização:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>opções da linha de comandos</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Opções de Interface</translation>
</message>
<message>
<location line="+1"/>
<source>Choose data directory on startup (default: 0)</source>
<translation>Escolha a pasta de dados ao iniciar (por defeito: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Definir linguagem, por exemplo "pt_PT" (por defeito: linguagem do sistema)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Iniciar minimizado</translation>
</message>
<message>
<location line="+1"/>
<source>Set SSL root certificates for payment request (default: -system-)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Mostrar imagem ao iniciar (por defeito: 1)</translation>
</message>
</context>
<context>
<name>I2POptionsWidget</name>
<message>
<location filename="../forms/i2poptionswidget.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use I2P only (-onlynet=i2p)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>http://www.i2p2.i2p/i2cp.html#options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source><a href="http://www.i2p2.i2p/i2cp.html#options">Help</a></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>SAM host</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>127.0.0.1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SAM port</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Tunnel name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Anoncoin-client</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Current
I2P-address...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Generate
I2P-address...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>I2CP options of inbound tunnels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>inbound.quantity </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>inbound.length </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>inbound.lengthVariance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>inbound.backupQuantity </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>inbound.allowZeroHop </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>inbound.IPRestriction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+65"/>
<source>I2CP options of outbound tunnels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>outbound.quantity </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>outbound.length </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>outbound.lengthVariance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>outbound.backupQuantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>outbound.allowZeroHop </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>outbound.IPRestriction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>outbound.priority</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>Intro</name>
<message>
<location filename="../forms/intro.ui" line="+14"/>
<source>Welcome</source>
<translation>Bem-vindo</translation>
</message>
<message>
<location line="+9"/>
<source>Welcome to Anoncoin Core.</source>
<translation>Bem-vindo ao Anoncoin Core.</translation>
</message>
<message>
<location line="+26"/>
<source>As this is the first time the program is launched, you can choose where Anoncoin Core will store its data.</source>
<translation>Sendo esta a primeira vez que o programa é iniciado, poderá escolher onde o Anoncoin Core irá guardar os seus dados.</translation>
</message>
<message>
<location line="+10"/>
<source>Anoncoin Core will download and store a copy of the Anoncoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source>
<translation>O Anoncoin Core vai transferir e armazenar uma cópia do "block chain" (cadeia de blocos). Pelo menos %1GB de dados serão armazenados nesta pasta, e vão crescer ao longo do tempo. A sua carteira também irá ser armazenada nesta pasta.</translation>
</message>
<message>
<location line="+10"/>
<source>Use the default data directory</source>
<translation>Utilizar a pasta de dados padrão</translation>
</message>
<message>
<location line="+7"/>
<source>Use a custom data directory:</source>
<translation>Utilizar uma pasta de dados personalizada:</translation>
</message>
<message>
<location filename="../intro.cpp" line="+82"/>
<source>Anoncoin</source>
<translation>Anoncoin</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Specified data directory "%1" cannot be created.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Error</source>
<translation>Erro</translation>
</message>
<message>
<location line="+9"/>
<source>GB of free space available</source>
<translation>GB de espaço livre disponível</translation>
</message>
<message>
<location line="+3"/>
<source>(of %1GB needed)</source>
<translation>(de %1GB necessários)</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<location filename="../forms/openuridialog.ui" line="+14"/>
<source>Open URI</source>
<translation>Abir URI</translation>
</message>
<message>
<location line="+6"/>
<source>Open payment request from URI or file</source>
<translation>Abrir pedido de pagamento de um URI ou ficheiro</translation>
</message>
<message>
<location line="+9"/>
<source>URI:</source>
<translation>URI:</translation>
</message>
<message>
<location line="+11"/>
<source>Select payment request file</source>
<translation>Seleccione o ficheiro de pedido de pagamento</translation>
</message>
<message>
<location filename="../openuridialog.cpp" line="+48"/>
<source>Select payment request file to open</source>
<translation>Seleccione o ficheiro de pedido de pagamento a abrir</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opções</translation>
</message>
<message>
<location line="+13"/>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically start Anoncoin after logging in to the system.</source>
<translation>Começar o Anoncoin automaticamente ao iniciar sessão no sistema.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Anoncoin on system login</source>
<translation>&Começar o Anoncoin ao iniciar o sistema</translation>
</message>
<message>
<location line="+9"/>
<source>Size of &database cache</source>
<translation>Tamanho da cache da base de &dados</translation>
</message>
<message>
<location line="+16"/>
<source>MB</source>
<translation>MB</translation>
</message>
<message>
<location line="+27"/>
<source>Number of script &verification threads</source>
<translation>Número de processos de &verificação de scripts</translation>
</message>
<message>
<location line="+13"/>
<source>(0 = auto, <0 = leave that many cores free)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>W&allet</source>
<translation>C&arteira</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Taxa de transação opcional por KB que ajuda a assegurar que as suas transações serão processadas rapidamente. A maioria das transações tem 1 kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Pagar &taxa de transação</translation>
</message>
<message>
<location line="+44"/>
<source>Expert</source>
<translation>Especialista</translation>
</message>
<message>
<location line="+6"/>
<source>Whether to show coin control features or not.</source>
<translation>Escolha para mostrar funcionalidades de Coin Control ou não.</translation>
</message>
<message>
<location line="+3"/>
<source>Enable coin &control features</source>
<translation>Ativar funcionalidades de controlo de transação.</translation>
</message>
<message>
<location line="+7"/>
<source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source>
<translation>No caso de desativar o gasto de troco não confirmado, o troco de uma transação não poderá ser utilizado até que essa transação tenha pelo menos uma confirmação. Isto também afeta o cálculo do seu saldo.</translation>
</message>
<message>
<location line="+3"/>
<source>&Spend unconfirmed change</source>
<translation>&Gastar troco não confirmado</translation>
</message>
<message>
<location line="+11"/>
<source>&Network</source>
<translation>&Rede</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Anoncoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Abrir a porta do cliente anoncoin automaticamente no seu router. Isto apenas funciona se o seu router suportar UPnP e este se encontrar ligado.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapear porta usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Anoncoin network through a SOCKS proxy.</source>
<translation>Ligar à rede Anoncoin através de um proxy SOCKS.</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy (default proxy):</source>
<translation>Ligar através de um proxy SO&CKS (proxy por defeito):</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP do proxy:</translation>
</message>
<message>
<location line="+25"/>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>Endereço IP do proxy (p.ex. IPv4: 127.0.0.1 / IPv6: ::1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Porta:</translation>
</message>
<message>
<location line="+25"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Porta do proxy (p.ex. 9050)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Janela</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Apenas mostrar o ícone da bandeja de sistema após minimizar a janela.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizar para a bandeja de sistema e não para a barra de ferramentas</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimize ao invés de sair da aplicação quando a janela é fechada. Com esta opção selecionada, a aplicação apenas será encerrada só quando escolher Sair da aplicação no menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizar ao fechar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>Vis&ualização</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Linguagem da interface de utilizador:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Anoncoin.</source>
<translation>A linguagem da interface do utilizador pode ser definida aqui. Esta definição entrará em efeito após reiniciar o Anoncoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unidade para mostrar quantias:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Escolha a subdivisão unitária a ser mostrada por defeito na aplicação e ao enviar moedas.</translation>
</message>
<message>
<location line="+11"/>
<location line="+13"/>
<source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Third party transaction URLs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Active command-line options that override above options:</source>
<translation>Opções de linha de comandos ativas que se sobrepõem ás opções anteriores:</translation>
</message>
<message>
<location line="+43"/>
<source>Reset all client options to default.</source>
<translation>Repor todas as opções do cliente.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Repor Opções</translation>
</message>
<message>
<location line="+61"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+71"/>
<source>default</source>
<translation>padrão</translation>
</message>
<message>
<location line="+64"/>
<source>none</source>
<translation>nenhum</translation>
</message>
<message>
<location line="+100"/>
<source>Confirm options reset</source>
<translation>Confirme a reposição de opções</translation>
</message>
<message>
<location line="+1"/>
<location line="+42"/>
<source>Client restart required to activate changes.</source>
<translation>É necessário reiniciar o cliente para ativar as alterações.</translation>
</message>
<message>
<location line="-42"/>
<source>Client will be shutdown, do you want to proceed?</source>
<translation>O cliente será desligado, deseja continuar?</translation>
</message>
<message>
<location line="+46"/>
<source>This change would require a client restart.</source>
<translation>Esta alteração requer um reinício do cliente.</translation>
</message>
<message>
<location line="+12"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>This setting will take effect after restarting Anoncoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>The supplied proxy address is invalid.</source>
<translation>O endereço de proxy introduzido é inválido. </translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulário</translation>
</message>
<message>
<location line="+43"/>
<source>Balances</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+372"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Anoncoin network after a connection is established, but this process has not completed yet.</source>
<translation>A informação mostrada poderá estar desatualizada. A sua carteira sincroniza automaticamente com a rede Anoncoin depois de estabelecer ligação, mas este processo ainda não está completo.</translation>
</message>
<message>
<location line="-327"/>
<source>Unconfirmed transactions to watch-only addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>Total de transações por confirmar, que ainda não estão contabilizadas no seu saldo gastável</translation>
</message>
<message>
<location line="+25"/>
<source>Mined balance in watch-only addresses that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<location line="+16"/>
<source>Mined balance that has not yet matured</source>
<translation>O saldo minado ainda não amadureceu</translation>
</message>
<message>
<location line="+29"/>
<source>Immature:</source>
<translation>Imaturo:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>O seu saldo total actual</translation>
</message>
<message>
<location line="+25"/>
<source>Current total balance in watch-only addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Watch-only:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Available:</source>
<translation>Disponível:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>O seu saldo (gastável) disponível</translation>
</message>
<message>
<location line="+25"/>
<source>Your current balance in watch-only addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Pending:</source>
<translation>Pendente:</translation>
</message>
<message>
<location line="+7"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Recent transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+132"/>
<location line="+1"/>
<source>out of sync</source>
<translation>fora de sincronia</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+293"/>
<location line="+206"/>
<location line="+13"/>
<location line="+95"/>
<location line="+18"/>
<location line="+16"/>
<source>Payment request error</source>
<translation>Erro de pedido de pagamento</translation>
</message>
<message>
<location line="-347"/>
<source>Cannot start anoncoin: click-to-pay handler</source>
<translation>Impossível iniciar o controlador de anoncoin: click-to-pay</translation>
</message>
<message>
<location line="+104"/>
<location line="+13"/>
<source>URI handling</source>
<translation>Manuseamento de URI</translation>
</message>
<message>
<location line="-12"/>
<source>Payment request fetch URL is invalid: %1</source>
<translation>O URL de pedido de pagamento é inválido: %1</translation>
</message>
<message>
<location line="+13"/>
<source>URI cannot be parsed! This can be caused by an invalid Anoncoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Payment request file handling</source>
<translation>Controlo de pedidos de pagamento.</translation>
</message>
<message>
<location line="+1"/>
<source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+73"/>
<source>Unverified payment requests to custom payment scripts are unsupported.</source>
<translation>Pedidos de pagamento não-verificados para scripts de pagamento personalizados não são suportados.</translation>
</message>
<message>
<location line="+8"/>
<source>Requested payment amount of %1 is too small (considered dust).</source>
<translation>Quantia solicitada para pagamento de %1 é muito pequena (considerada "pó").</translation>
</message>
<message>
<location line="+51"/>
<source>Refund from %1</source>
<translation>Reembolsar de %1</translation>
</message>
<message>
<location line="+43"/>
<source>Error communicating with %1: %2</source>
<translation>Erro ao comunicar com %1: %2</translation>
</message>
<message>
<location line="+24"/>
<source>Payment request cannot be parsed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Bad response from server %1</source>
<translation>Má resposta do servidor %1</translation>
</message>
<message>
<location line="+22"/>
<source>Network request error</source>
<translation>Erro de pedido de rede</translation>
</message>
<message>
<location line="+11"/>
<source>Payment acknowledged</source>
<translation>Pagamento confirmado</translation>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<location filename="../peertablemodel.cpp" line="+120"/>
<source>Address/Hostname</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>User Agent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Ping Time</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../anoncoinunits.cpp" line="+175"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../guiutil.cpp" line="+102"/>
<source>Enter a Anoncoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduza um endereço Anoncoin (p.ex. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+697"/>
<source>%1 d</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>NETWORK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>UNKNOWN</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>None</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>%1 ms</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<location filename="../receiverequestdialog.cpp" line="+37"/>
<source>&Save Image...</source>
<translation>&Salvar Imagem...</translation>
</message>
<message>
<location line="+3"/>
<source>&Copy Image</source>
<translation>&Copiar Imagem</translation>
</message>
<message>
<location line="+32"/>
<source>Save QR Code</source>
<translation>Guardar Código QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Image (*.png)</source>
<translation>Imagem PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+14"/>
<source>Debug window</source>
<translation>Janela de depuração</translation>
</message>
<message>
<location line="+10"/>
<source>&Information</source>
<translation>&Informação</translation>
</message>
<message>
<location line="+15"/>
<source>General</source>
<translation>Geral</translation>
</message>
<message>
<location line="+7"/>
<source>Client name</source>
<translation>Nome do Cliente</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+465"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<source>N/A</source>
<translation>N/D</translation>
</message>
<message>
<location line="-967"/>
<source>Client version</source>
<translation>Versão do Cliente</translation>
</message>
<message>
<location line="+23"/>
<source>Using OpenSSL version</source>
<translation>Usando versão OpenSSL</translation>
</message>
<message>
<location line="+26"/>
<source>Using BerkeleyDB version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Build date</source>
<translation>Data de compilação</translation>
</message>
<message>
<location line="+23"/>
<source>Startup time</source>
<translation>Hora de inicialização</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Rede</translation>
</message>
<message>
<location line="+7"/>
<source>Name</source>
<translation>Nome</translation>
</message>
<message>
<location line="+23"/>
<source>Number of connections</source>
<translation>Número de ligações</translation>
</message>
<message>
<location line="+29"/>
<source>Block chain</source>
<translation>Cadeia de blocos</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Número actual de blocos</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Data do último bloco</translation>
</message>
<message>
<location line="+42"/>
<source>Debug log file</source>
<translation>Ficheiro de registo de depuração</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Anoncoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Abrir o ficheiro de registo de depuração da pasta de dados actual. Isto pode demorar alguns segundos para ficheiros de registo maiores.</translation>
</message>
<message>
<location line="+3"/>
<source>&Open</source>
<translation>&Abrir</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<location line="+49"/>
<source>Clear console</source>
<translation>Limpar consola</translation>
</message>
<message>
<location line="+23"/>
<source>&Network Traffic</source>
<translation>&Tráfego de Rede</translation>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation>&Limpar</translation>
</message>
<message>
<location line="+16"/>
<source>Totals</source>
<translation>Totais</translation>
</message>
<message>
<location line="+64"/>
<source>Received</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Sent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>&Peers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<location filename="../rpcconsole.cpp" line="+244"/>
<location line="+338"/>
<source>Select a peer to view detailed information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Direction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>User Agent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Services</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Starting Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Sync Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Ban Score</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Connection Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Bytes Sent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Bytes Received</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Ping Time</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-209"/>
<source>Welcome to the Anoncoin RPC console.</source>
<translation>Bem-vindo à consola RPC Anoncoin.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use as setas para cima e para baixo para navegar no histórico e <b>Ctrl-L</b> para limpar o ecrã.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Insira <b>help</b> para visualizar os comandos disponíveis.</translation>
</message>
<message>
<location line="+32"/>
<source>In:</source>
<translation>Entrada:</translation>
</message>
<message>
<location line="+1"/>
<source>Out:</source>
<translation>Saída:</translation>
</message>
<message>
<location line="+101"/>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation>%1 KB</translation>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation>%1 m</translation>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation>%1 h</translation>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation>%1 h %2 m</translation>
</message>
<message>
<location line="+91"/>
<source>via %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+1"/>
<source>never</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Inbound</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Outbound</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Unknown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<location line="+1"/>
<source>Fetching...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<location filename="../forms/receivecoinsdialog.ui" line="+34"/>
<source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source>
<translation>Reutilize um dos endereços de entrada usados anteriormente. Reutilizar endereços pode levar a riscos de segurança e de privacidade. Não use esta função a não ser que esteja a gerar novamente uma requisição de pagamento feita anteriormente.</translation>
</message>
<message>
<location line="+3"/>
<source>R&euse an existing receiving address (not recommended)</source>
<translation>Reutilizar um endereço de receção existente (não recomendado)</translation>
</message>
<message>
<location line="+14"/>
<location line="+23"/>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Anoncoin network.</source>
<translation>Uma mensagem opcional para anexar ao pedido de pagamento, que será exibida quando o pedido for aberto. Nota: A mensagem não será enviada com o pagamento através da rede Anoncoin.</translation>
</message>
<message>
<location line="-20"/>
<source>&Message:</source>
<translation>&Mensagem:</translation>
</message>
<message>
<location line="+13"/>
<location line="+21"/>
<source>An optional label to associate with the new receiving address.</source>
<translation>Um rótulo opcional a associar ao novo endereço de receção.</translation>
</message>
<message>
<location line="-7"/>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation>Utilize este formulário para solicitar pagamentos. Todos os campos são <b>opcionais</b>.</translation>
</message>
<message>
<location line="+10"/>
<source>&Label:</source>
<translation>Rótu&lo:</translation>
</message>
<message>
<location line="+13"/>
<location line="+22"/>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation>Uma quantia opcional a solicitar. Deixe em branco ou zero para não solicitar uma quantidade específica.</translation>
</message>
<message>
<location line="-19"/>
<source>&Amount:</source>
<translation>&Quantia:</translation>
</message>
<message>
<location line="+34"/>
<source>&Request payment</source>
<translation>&Requisitar Pagamento</translation>
</message>
<message>
<location line="+17"/>
<source>Clear all fields of the form.</source>
<translation>Limpar todos os campos do formulário.</translation>
</message>
<message>
<location line="+3"/>
<source>Clear</source>
<translation>Limpar</translation>
</message>
<message>
<location line="+78"/>
<source>Requested payments history</source>
<translation>Histórico de pagamentos solicitados</translation>
</message>
<message>
<location line="+22"/>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation>Mostrar o pedido seleccionado (faz o mesmo que clicar 2 vezes numa entrada)</translation>
</message>
<message>
<location line="+3"/>
<source>Show</source>
<translation>Mostrar</translation>
</message>
<message>
<location line="+14"/>
<source>Remove the selected entries from the list</source>
<translation>Remover as entradas seleccionadas da lista</translation>
</message>
<message>
<location line="+3"/>
<source>Remove</source>
<translation>Remover</translation>
</message>
<message>
<location filename="../receivecoinsdialog.cpp" line="+40"/>
<source>Copy label</source>
<translation>Copiar rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy message</source>
<translation>Copiar mensagem</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<location filename="../forms/receiverequestdialog.ui" line="+29"/>
<source>QR Code</source>
<translation>Código QR</translation>
</message>
<message>
<location line="+46"/>
<source>Copy &URI</source>
<translation>Copiar &URI</translation>
</message>
<message>
<location line="+7"/>
<source>Copy &Address</source>
<translation>Copi&ar Endereço</translation>
</message>
<message>
<location line="+7"/>
<source>&Save Image...</source>
<translation>&Salvar Imagem...</translation>
</message>
<message>
<location filename="../receiverequestdialog.cpp" line="+65"/>
<source>Request payment to %1</source>
<translation>Requisitar Pagamento para %1</translation>
</message>
<message>
<location line="+6"/>
<source>Payment information</source>
<translation>Informação de Pagamento</translation>
</message>
<message>
<location line="+1"/>
<source>URI</source>
<translation>URI</translation>
</message>
<message>
<location line="+2"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+2"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+2"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+2"/>
<source>Message</source>
<translation>Mensagem</translation>
</message>
<message>
<location line="+10"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI resultante muito longo. Tente reduzir o texto do rótulo / mensagem.</translation>
</message>
<message>
<location line="+5"/>
<source>Error encoding URI into QR Code.</source>
<translation>Erro ao codificar URI em Código QR.</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<location filename="../recentrequeststablemodel.cpp" line="+26"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+0"/>
<source>Message</source>
<translation>Mensagem</translation>
</message>
<message>
<location line="+40"/>
<source>(no label)</source>
<translation>(sem rótulo)</translation>
</message>
<message>
<location line="+9"/>
<source>(no message)</source>
<translation>(sem mensagem)</translation>
</message>
<message>
<location line="+8"/>
<source>(no amount)</source>
<translation>(sem quantia)</translation>
</message>
<message>
<location line="+35"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+382"/>
<location line="+84"/>
<source>Send Coins</source>
<translation>Enviar Moedas</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Funcionalidades de Coin Control:</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Entradas...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>selecionadas automáticamente</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Fundos insuficientes!</translation>
</message>
<message>
<location line="+89"/>
<source>Quantity:</source>
<translation>Quantidade:</translation>
</message>
<message>
<location line="+35"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Quantia:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioridade:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Taxa:</translation>
</message>
<message>
<location line="+32"/>
<source>Low Output:</source>
<translation>Output Baixo:</translation>
</message>
<message>
<location line="+48"/>
<source>After Fee:</source>
<translation>Depois da taxa:</translation>
</message>
<message>
<location line="+32"/>
<source>Change:</source>
<translation>Troco:</translation>
</message>
<message>
<location line="+44"/>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation>Se isto estiver ativo, mas o endereço de troco estiver vazio ou for inválido, o troco irá ser enviado para um novo endereço.</translation>
</message>
<message>
<location line="+3"/>
<source>Custom change address</source>
<translation>Endereço de troco personalizado</translation>
</message>
<message>
<location line="+121"/>
<source>Confirm the send action</source>
<translation>Confirme ação de envio</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Enviar</translation>
</message>
<message>
<location line="+20"/>
<source>Clear all fields of the form.</source>
<translation>Limpar todos os campos do formulário.</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Limpar Tudo</translation>
</message>
<message>
<location line="+17"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar para múltiplos destinatários de uma vez</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Adicionar &Destinatário</translation>
</message>
<message>
<location line="+38"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-415"/>
<source>Copy quantity</source>
<translation>Copiar quantidade</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Copiar taxa</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copiar valor após taxa</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copiar prioridade</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar output baixo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar alteração</translation>
</message>
<message>
<location line="+101"/>
<location line="+5"/>
<location line="+5"/>
<location line="+4"/>
<source>%1 to %2</source>
<translation>%1 para %2</translation>
</message>
<message>
<location line="+35"/>
<source>Are you sure you want to send?</source>
<translation>Tem a certeza que deseja enviar?</translation>
</message>
<message>
<location line="+9"/>
<source>added as transaction fee</source>
<translation>adicionados como taxa de transação</translation>
</message>
<message>
<location line="+12"/>
<source>Total Amount %1 (= %2)</source>
<translation>Quantia Total %1 (= %2)</translation>
</message>
<message>
<location line="+2"/>
<source>or</source>
<translation>ou</translation>
</message>
<message>
<location line="+2"/>
<source>Confirm send coins</source>
<translation>Confirme envio de moedas</translation>
</message>
<message>
<location line="+155"/>
<source>Payment request expired</source>
<translation>Pedido de pagamento expirou</translation>
</message>
<message>
<location line="+8"/>
<source>Invalid payment address %1</source>
<translation>Endereço de pagamento inválido %1</translation>
</message>
<message>
<location line="+42"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>O endereço de destino não é válido, por favor verifique.</translation>
</message>
<message>
<location line="+3"/>
<source>The amount to pay must be larger than 0.</source>
<translation>A quantia a pagar deverá ser maior que 0.</translation>
</message>
<message>
<location line="+3"/>
<source>The amount exceeds your balance.</source>
<translation>A quantia excede o seu saldo.</translation>
</message>
<message>
<location line="+3"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>O total excede o seu saldo quando a taxa de transação de %1 for incluída.</translation>
</message>
<message>
<location line="+3"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Endereço duplicado encontrado, apenas poderá enviar uma vez para cada endereço por cada operação de envio.</translation>
</message>
<message>
<location line="+3"/>
<source>Transaction creation failed!</source>
<translation>Erro: A criação da transação falhou! </translation>
</message>
<message>
<location line="+4"/>
<source>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.</source>
<translation>A transação foi rejeitada! Isto poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas tiverem sido gastas na cópia mas não tiverem sido marcadas como gastas aqui.</translation>
</message>
<message>
<location line="+113"/>
<source>Warning: Invalid Anoncoin address</source>
<translation>Aviso: Endereço Anoncoin inválido</translation>
</message>
<message>
<location line="+9"/>
<source>Warning: Unknown change address</source>
<translation>Aviso: Endereço de troco desconhecido</translation>
</message>
<message>
<location line="+11"/>
<source>(no label)</source>
<translation>(sem rótulo)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+21"/>
<source>This is a normal payment.</source>
<translation>Este é um pagamento normal.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay &To:</source>
<translation>&Pagar A:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>O endereço para onde enviar o pagamento (p.ex. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+7"/>
<source>Choose previously used address</source>
<translation>Escolher endereço usado previamente</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Cole endereço da área de transferência</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<location line="+524"/>
<location line="+536"/>
<source>Remove this entry</source>
<translation>Remover esta entrada</translation>
</message>
<message>
<location line="-1044"/>
<source>&Label:</source>
<translation>Rótu&lo:</translation>
</message>
<message>
<location line="+13"/>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation>Introduza um rótulo para este endereço para o adicionar à sua lista de endereços usados</translation>
</message>
<message>
<location line="+7"/>
<location line="+521"/>
<location line="+536"/>
<source>A&mount:</source>
<translation>Qu&antia:</translation>
</message>
<message>
<location line="-1041"/>
<source>Message:</source>
<translation>Mensagem:</translation>
</message>
<message>
<location line="+10"/>
<source>A message that was attached to the anoncoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Anoncoin network.</source>
<translation>Uma mensagem que estava anexada ao URI anoncoin: que será armazenada com a transação para sua referência. Nota: Esta mensagem não será enviada através da rede Anoncoin.</translation>
</message>
<message>
<location line="+426"/>
<source>This is an unverified payment request.</source>
<translation>Este é um pedido de pagamento não-verificado.</translation>
</message>
<message>
<location line="+18"/>
<location line="+532"/>
<source>Pay To:</source>
<translation>Pagar A:</translation>
</message>
<message>
<location line="-498"/>
<location line="+536"/>
<source>Memo:</source>
<translation>Memorando:</translation>
</message>
<message>
<location line="-56"/>
<source>This is a verified payment request.</source>
<translation>Este é um pedido de pagamento verificado.</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+31"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Escreva um rótulo para este endereço para o adicionar ao seu livro de endereços</translation>
</message>
</context>
<context>
<name>ShowI2PAddresses</name>
<message>
<location filename="../forms/i2pshowaddresses.ui" line="+20"/>
<source>Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>If you want to use a permanent I2P-address you have to set a 'mydestination' option in the configuration file:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Ready to save parameter (If you want to use this address save this text in the configuration file and keep it secret):</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Address (you can publish it):</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Short base32-address:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Copy "mydestination" parameter
to the clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Copy public address
to the clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Copy b32-address
to the clipboard</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<location filename="../utilitydialog.cpp" line="+48"/>
<source>Anoncoin Core is shutting down...</source>
<translation>O Anoncoin Core está a encerrar...</translation>
</message>
<message>
<location line="+1"/>
<source>Do not shut down the computer until this window disappears.</source>
<translation>Não desligue o computador enquanto esta janela não desaparecer.</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Assinaturas - Assinar / Verificar uma Mensagem</translation>
</message>
<message>
<location line="+10"/>
<source>&Sign Message</source>
<translation>A&ssinar Mensagem</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Pode assinar mensagens com os seus endereços para provar que são seus. Tenha atenção ao assinar mensagens ambíguas, pois ataques de phishing podem tentar enganá-lo de modo a assinar a sua identidade para os atacantes. Apenas assine declarações detalhadas com as quais concorde.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>O endereço a utilizar para assinar a mensagem (p.ex. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+7"/>
<location line="+210"/>
<source>Choose previously used address</source>
<translation>Escolher endereço usado previamente</translation>
</message>
<message>
<location line="-200"/>
<location line="+210"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-200"/>
<source>Paste address from clipboard</source>
<translation>Colar endereço da área de transferência</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Escreva aqui a mensagem que deseja assinar</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Assinatura</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiar a assinatura actual para a área de transferência</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Anoncoin address</source>
<translation>Assine uma mensagem para provar que é dono deste endereço Anoncoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Assinar &Mensagem</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Repor todos os campos de assinatura de mensagem</translation>
</message>
<message>
<location line="+3"/>
<location line="+143"/>
<source>Clear &All</source>
<translation>Limpar &Tudo</translation>
</message>
<message>
<location line="-84"/>
<source>&Verify Message</source>
<translation>&Verificar Mensagem</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Introduza o endereço de assinatura, mensagem (assegure-se que copia quebras de linha, espaços, tabulações, etc. exactamente) e assinatura abaixo para verificar a mensagem. Tenha atenção para não ler mais na assinatura do que o que estiver na mensagem assinada, para evitar ser enganado por um atacante que se encontre entre si e quem assinou a mensagem.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>O endereço utilizado para assinar a mensagem (p.ex. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+37"/>
<source>Verify the message to ensure it was signed with the specified Anoncoin address</source>
<translation>Verifique a mensagem para assegurar que foi assinada com o endereço Anoncoin especificado</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verificar &Mensagem</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Repor todos os campos de verificação de mensagem</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+30"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Clique "Assinar mensagem" para gerar a assinatura</translation>
</message>
<message>
<location line="+2"/>
<source>Enter an Anoncoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<location line="+80"/>
<source>The entered address is invalid.</source>
<translation>O endereço introduzido é inválido.</translation>
</message>
<message>
<location line="-80"/>
<location line="+8"/>
<location line="+72"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Por favor verifique o endereço e tente de novo.</translation>
</message>
<message>
<location line="-80"/>
<location line="+80"/>
<source>The entered address does not refer to a key.</source>
<translation>O endereço introduzido não refere a nenhuma chave.</translation>
</message>
<message>
<location line="-72"/>
<source>Wallet unlock was cancelled.</source>
<translation>O desbloqueio da carteira foi cancelado.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>A chave privada para o endereço introduzido não está disponível.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Assinatura de mensagem falhou.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mensagem assinada.</translation>
</message>
<message>
<location line="+58"/>
<source>The signature could not be decoded.</source>
<translation>A assinatura não pôde ser descodificada.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Por favor verifique a assinatura e tente de novo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>A assinatura não condiz com o conteúdo da mensagem.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verificação da mensagem falhou.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mensagem verificada.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+35"/>
<source>ANONCOIN CORE DEVELOPERS</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+80"/>
<source>KB/s</source>
<translation>KB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message numerus="yes">
<location filename="../transactiondesc.cpp" line="+29"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation>em conflito:</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/desligado</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/não confirmada</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmações</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message>
<location line="+5"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ainda não foi transmitida com sucesso</translation>
</message>
<message numerus="yes">
<location line="+2"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Origem</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Gerado</translation>
</message>
<message>
<location line="+5"/>
<location line="+13"/>
<location line="+72"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="-72"/>
<source>unknown</source>
<translation>desconhecido</translation>
</message>
<message>
<location line="+1"/>
<location line="+20"/>
<location line="+69"/>
<source>To</source>
<translation>Para</translation>
</message>
<message>
<location line="-87"/>
<source>own address</source>
<translation>endereço próprio</translation>
</message>
<message>
<location line="+0"/>
<location line="+69"/>
<source>watch-only</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>label</source>
<translation>rótulo</translation>
</message>
<message>
<location line="+34"/>
<location line="+12"/>
<location line="+53"/>
<location line="+26"/>
<location line="+53"/>
<source>Credit</source>
<translation>Crédito</translation>
</message>
<message numerus="yes">
<location line="-142"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>matura em %n bloco</numerusform><numerusform>matura em %n blocos</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>não aceite</translation>
</message>
<message>
<location line="+59"/>
<location line="+25"/>
<location line="+53"/>
<source>Debit</source>
<translation>Débito</translation>
</message>
<message>
<location line="-68"/>
<source>Total debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Total credit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Transaction fee</source>
<translation>Taxa de transação</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Valor líquido</translation>
</message>
<message>
<location line="+6"/>
<location line="+9"/>
<source>Message</source>
<translation>Mensagem</translation>
</message>
<message>
<location line="-7"/>
<source>Comment</source>
<translation>Comentário</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID da Transação</translation>
</message>
<message>
<location line="+18"/>
<source>Merchant</source>
<translation>Comerciante</translation>
</message>
<message>
<location line="+7"/>
<source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Moedas geradas deverão maturar por %1 blocos antes de poderem ser gastas. Quando gerou este bloco, ele foi transmitido para a rede para ser incluído na cadeia de blocos. Se a inclusão na cadeia de blocos falhar, o seu estado irá ser alterado para "não aceite" e as moedas não poderão ser gastas. Isto poderá acontecer ocasionalmente se outro nó da rede gerar um bloco a poucos segundos de diferença do seu.</translation>
</message>
<message>
<location line="+8"/>
<source>Debug information</source>
<translation>Informação de depuração</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transação</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Entradas</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<source>true</source>
<translation>verdadeiro</translation>
</message>
<message>
<location line="-1"/>
<location line="+1"/>
<source>false</source>
<translation>falso</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalhes da transação</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta janela mostra uma descrição detalhada da transação</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+237"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message numerus="yes">
<location line="+55"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline</source>
<translation>Offline</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Não confirmado:</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>A confirmar (%1 de %2 confirmações recomendadas)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmada (%1 confirmações)</translation>
</message>
<message>
<location line="+3"/>
<source>Conflicted</source>
<translation>Em Conflito:</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Imaturo (%1 confirmações, estará disponível após %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Gerado mas não aceite</translation>
</message>
<message>
<location line="+39"/>
<source>Received with</source>
<translation>Recebido com</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recebido de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado para</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pagamento a si mesmo</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minadas</translation>
</message>
<message>
<location line="+28"/>
<source>watch-only</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>(n/a)</source>
<translation>(n/d)</translation>
</message>
<message>
<location line="+209"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado da transação. Passar o cursor por cima deste campo para mostrar o número de confirmações.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Data e hora em que a transação foi recebida.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Whether or not a watch-only address is involved in this transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Endereço de destino da transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Quantia retirada ou adicionada ao saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+68"/>
<location line="+16"/>
<source>All</source>
<translation>Todas</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoje</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Este mês</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mês passado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este ano</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Período...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recebida com</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviada para</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Para si mesmo</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minadas</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Outras</translation>
</message>
<message>
<location line="+6"/>
<source>Enter address or label to search</source>
<translation>Escreva endereço ou rótulo a procurar</translation>
</message>
<message>
<location line="+6"/>
<source>Min amount</source>
<translation>Quantia mínima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copiar endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copiar ID da Transação</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editar rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Mostrar detalhes da transação</translation>
</message>
<message>
<location line="+179"/>
<source>Export Transaction History</source>
<translation>Exportar Histórico de Transacções</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Ficheiro separado por vírgulas (*.csv)</translation>
</message>
<message>
<location line="+9"/>
<source>Confirmed</source>
<translation>Confirmada</translation>
</message>
<message>
<location line="+2"/>
<source>Watch-only</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+2"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+3"/>
<source>Exporting Failed</source>
<translation>A Exportação Falhou</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the transaction history to %1.</source>
<translation>Ocorreu um erro ao tentar guardar o histórico de transações em %1.</translation>
</message>
<message>
<location line="+4"/>
<source>Exporting Successful</source>
<translation>Exportação Bem Sucedida</translation>
</message>
<message>
<location line="+0"/>
<source>The transaction history was successfully saved to %1.</source>
<translation>O histórico de transacções foi com guardado com sucesso em %1.</translation>
</message>
<message>
<location line="+109"/>
<source>Range:</source>
<translation>Período:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>até</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
<message>
<location filename="../anoncoingui.cpp" line="+135"/>
<source>Unit to show amounts in. Click to select another unit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletFrame</name>
<message>
<location filename="../walletframe.cpp" line="+27"/>
<source>No wallet has been loaded.</source>
<translation>Nenhuma carteira foi carregada.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+286"/>
<source>Send Coins</source>
<translation>Enviar Moedas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+45"/>
<source>&Export</source>
<translation>&Exportar</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar os dados no separador actual para um ficheiro</translation>
</message>
<message>
<location line="+184"/>
<source>Backup Wallet</source>
<translation>Cópia de Segurança da Carteira</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet Data (*.dat)</source>
<translation>Dados da Carteira (*.dat)</translation>
</message>
<message>
<location line="+6"/>
<source>Backup Failed</source>
<translation>Cópia de Segurança Falhou</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to %1.</source>
<translation>Ocorreu um erro ao tentar guardar os dados da carteira em %1.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Cópia de Segurança Bem Sucedida</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to %1.</source>
<translation>Os dados da carteira foram guardados com sucesso em %1.</translation>
</message>
</context>
<context>
<name>anoncoin-core</name>
<message>
<location filename="../anoncoinstrings.cpp" line="+12"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=anoncoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Anoncoin Alert" [email protected]
</source>
<translation>%s, deverá definir uma rpcpassword no ficheiro de configuração:
%s
É recomendado que use a seguinte palavra-passe aleatória:
rpcuser=anoncoinrpc
rpcpassword=%s
(não é necessário lembrar esta palavra-passe)
O nome de utilizador e palavra-passe NÃO PODEM ser iguais.
Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.
Também é recomendado definir um alertnotify para que seja alertado sobre problemas;
por exemplo: alertnotify=echo %%s | mail -s "Alerta Anoncoin" [email protected]</translation>
</message>
<message>
<location line="+13"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation>Cifras aceitáveis (por defeito: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+3"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv4: %s</translation>
</message>
<message>
<location line="+2"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv6, a usar IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Associar a endereço específico e escutar sempre nele. Use a notação [anfitrião]:porta para IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Anoncoin Core is probably already running.</source>
<translation>Impossível trancar a pasta de dados %s. Provavelmente o Anoncoin Core já está a ser executado.</translation>
</message>
<message>
<location line="+3"/>
<source>Continuously rate-limit free transactions to <n>*1000 bytes per minute (default:15)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source>
<translation>Entre no modo de teste de regressão, que usa uma cadeia especial cujos blocos podem ser resolvidos instantaneamente.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: Listening for incoming connections failed (listen returned error %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>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.</source>
<translation>Erro: A transação foi rejeitada! Isso poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas tiverem sido gastas na cópia mas não tiverem sido marcadas como gastas aqui.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Erro: Esta transação requer uma taxa de transação mínima de %s devido á sua quantia, complexidade, ou uso de fundos recebidos recentemente!</translation>
</message>
<message>
<location line="+3"/>
<source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source>
<translation>Executar comando quando um alerta relevante for recebido ou em caso de uma divisão longa da cadeia de blocos (no comando, %s é substituído pela mensagem)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Executar comando quando o melhor bloco mudar (no comando, %s é substituído pela hash do bloco)</translation>
</message>
<message>
<location line="+3"/>
<source>Fees smaller than this are considered zero fee (for transaction creation) (default:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Flush database activity from memory pool to disk log every <n> megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification of -checkblocks is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>In this mode -genproclimit controls how many blocks are generated immediately.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Número de segundos a impedir que nós com comportamento indesejado se liguem de novo (por defeito: 86400)</translation>
</message>
<message>
<location line="+3"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation>Informação de depuração (por defeito: 0, fornecer uma <categoria> é opcional)</translation>
</message>
<message>
<location line="+2"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source>
<translation>Definir tamanho máximo de transações com alta-prioridade/baixa-taxa em bytes (por defeito: %d)</translation>
</message>
<message>
<location line="+2"/>
<source>Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Set the processor limit for when generation is on (-1 = unlimited, default: -1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Esta é uma versão de testes pré-lançamento - use à sua responsabilidade - não usar para minar ou aplicações comerciais</translation>
</message>
<message>
<location line="+3"/>
<source>Unable to bind to %s on this computer. Anoncoin Core is probably already running.</source>
<translation>Incapaz de vincular à porta %s neste computador. O Anoncoin Core provavelmente já está a correr.</translation>
</message>
<message>
<location line="+3"/>
<source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source>
<translation>Usar um proxy SOCKS5 separado para aceder a pares através de Tor hidden services (por defeito: -proxy)</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation>Aviso: A rede não parece estar completamente de acordo! Parece que alguns mineiros estão com dificuldades técnicas.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Atenção: Parecemos não estar de acordo com os nossos pares! Poderá ter que atualizar o seu cliente, ou outros nós poderão ter que atualizar os seus clientes.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</translation>
</message>
<message>
<location line="+3"/>
<source>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.</source>
<translation>Atenção: wallet.dat corrompido, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar uma cópia de segurança.</translation>
</message>
<message>
<location line="+4"/>
<source>
If you want to use a permanent I2P-address you have to set options in the configuration file:
Your Config file is: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>
This is your Address + private key (save this text in the configuration file and keep it secret):
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>
This is your Address (you can make it public):
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>
Your Short base32-address:
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>(default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(default: wallet.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation><categoria> pode ser:</translation>
</message>
<message>
<location line="+1"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceitar comandos de linha de comandos e JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Adicionar um nó para se ligar e tentar manter a ligação aberta</translation>
</message>
<message>
<location line="+1"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation>
</message>
<message>
<location line="+1"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitir ligações JSON-RPC do endereço IP especificado</translation>
</message>
<message>
<location line="+1"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation>
</message>
<message>
<location line="+1"/>
<source>Block creation options:</source>
<translation>Opções de criação de bloco:</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot downgrade wallet</source>
<translation>Impossível mudar a carteira para uma versão anterior</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Não foi possível resolver o endereço -bind: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Não foi possível resolver o endereço -externalip: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Impossível escrever endereço por defeito</translation>
</message>
<message>
<location line="+1"/>
<source>Clear list of wallet transactions (diagnostic tool; implies -rescan)</source>
<translation>Limpar lista de transações (ferramenta de diagnóstico; implica -rescan)</translation>
</message>
<message>
<location line="+1"/>
<source>Connect only to the specified node(s)</source>
<translation>Apenas ligar ao(s) nó(s) especificado(s)</translation>
</message>
<message>
<location line="+1"/>
<source>Connect through SOCKS5 proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation>
</message>
<message>
<location line="+1"/>
<source>Connecting to the I2P Router...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Connection options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Corrupted block database detected</source>
<translation>Cadeia de blocos corrompida detectada</translation>
</message>
<message>
<location line="+1"/>
<source>Debugging/Testing options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Disable safemode, override a real safe mode event (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descobrir endereço IP próprio (padrão: 1 ao escutar sem -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do not load the wallet and disable wallet RPC calls</source>
<translation>Não carregar a carteira e desativar chamadas RPC de carteira.</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Deseja reconstruir agora a base de dados de blocos.</translation>
</message>
<message>
<location line="+1"/>
<source>Done loading</source>
<translation>Carregamento completo</translation>
</message>
<message>
<location line="+1"/>
<source>Error - Unable to Generate I2P Destination.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error - Unable to report I2P Destination.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing block database</source>
<translation>Erro ao inicializar a cadeia de blocos</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Erro ao inicializar o ambiente %s da base de dados da carteira</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Erro ao carregar base de dados de blocos</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Erro ao carregar wallet.dat</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Erro ao carregar wallet.dat: Carteira danificada</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Anoncoin</source>
<translation>Erro ao carregar wallet.dat: A Carteira requer uma versão mais recente do Anoncoin</translation>
</message>
<message>
<location line="+1"/>
<source>Error opening block database</source>
<translation>Erro ao abrir a base de dados de blocos</translation>
</message>
<message>
<location line="+1"/>
<source>Error</source>
<translation>Erro</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Disk space is low!</source>
<translation>Erro: Pouco espaço em disco!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Unsupported argument -tor found, use -onion.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Erro: Carteira bloqueada, incapaz de criar transação! </translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Erro: erro do sistema:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Falhou a escutar em qualquer porta. Use -listen=0 se quiser isto.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Falha ao ler informação do bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Falha ao ler bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Falha ao sincronizar índice de blocos</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Falha ao escrever índice de blocos</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Falha ao escrever informação do bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Falha ao escrever bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Falha ao escrever informação do ficheiro</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Falha ao escrever na base de dados de moedas</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Falha ao escrever índice de transações</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Falha ao escrever histórico de modificações</translation>
</message>
<message>
<location line="+1"/>
<source>Fee per kB to add to transactions you send</source>
<translation>Taxa por KB a adicionar a transações enviadas</translation>
</message>
<message>
<location line="+1"/>
<source>Fees smaller than this are considered zero fee (for relaying) (default:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Force safe mode (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Gerar moedas (por defeito: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Generated an I2P destination for you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Quantos blocos verificar ao inicializar (por defeito: 288, 0 = todos)</translation>
</message>
<message>
<location line="+1"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation>Se uma <categoria> não é fornecida, imprimir toda a informação de depuração.</translation>
</message>
<message>
<location line="+1"/>
<source>Importing...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importar blocos de um ficheiro blk000??.dat externo</translation>
</message>
<message>
<location line="+1"/>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation>Bloco génese incorreto ou nenhum bloco génese encontrado. Pasta de dados errada para a rede?</translation>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation>Informação</translation>
</message>
<message>
<location line="+1"/>
<source>Initialization sanity check failed. Anoncoin Core is shutting down.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fundos insuficientes</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid -onion address: '%s'</source>
<translation>Endereço -onion inválido: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Endereço -proxy inválido: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Quantia inválida para -minrelaytxfee=<quantidade>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Quantia inválida para -mintxfee=<quantidade>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Quantia inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Quantia inválida</translation>
</message>
<message>
<location line="+1"/>
<source>Keep at most <n> unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Keep at most <n> unconnectable transactions in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Limit size of signature cache to <n> entries (default: 50000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Loading addresses...</source>
<translation>A carregar endereços...</translation>
</message>
<message>
<location line="+1"/>
<source>Loading block index...</source>
<translation>A carregar índice de blocos...</translation>
</message>
<message>
<location line="+1"/>
<source>Loading wallet...</source>
<translation>A carregar carteira...</translation>
</message>
<message>
<location line="+1"/>
<source>Log transaction priority and fee per kB when mining blocks (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Manter índice de transações completo (por defeito: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Manter no máximo <n> ligações a outros nós da rede (por defeito: 125)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximo armazenamento intermédio de recepção por ligação, <n>*1000 bytes (por defeito: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximo armazenamento intermédio de envio por ligação, <n>*1000 bytes (por defeito: 1000)</translation>
</message>
<message>
<location line="+1"/>
<source>Node relay options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not enough file descriptors available.</source>
<translation>Os descritores de ficheiros disponíveis são insuficientes.</translation>
</message>
<message>
<location line="+1"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Apenas aceitar cadeia de blocos coincidente com pontos de controle internos (por defeito: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (ipv4, ipv6, onion or i2p)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Options:</source>
<translation>Opções:</translation>
</message>
<message>
<location line="+1"/>
<source>Password for JSON-RPC connections</source>
<translation>Palavra-passe para ligações JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp (default: 1)</source>
<translation>Adicionar data e hora à informação de depuração (por defeito: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Print block on startup, if found in block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Print block tree on startup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>RPC server options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Randomly drop 1 of every <n> network messages</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Randomly fuzz 1 of every <n> network messages</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Reconstruir a cadeia de blocos a partir dos ficheiros blk000??.dat atuais</translation>
</message>
<message>
<location line="+1"/>
<source>Relay and mine data carrier transactions (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Procurar transações em falta na cadeia de blocos</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Reexaminando...</translation>
</message>
<message>
<location line="+1"/>
<source>Results also written to your debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Run a thread to flush wallet periodically (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr o processo em segundo plano e aceitar comandos</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Ficheiro de certificado do servidor (por defeito: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Chave privada do servidor (por defeito: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database cache size in megabytes (%d to %d, default: %d)</source>
<translation>Definir o tamanho da cache de base de dados em megabytes (%d a %d, padrão: %d)</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Definir o tamanho da memória de chaves para <n> (por defeito: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Set maximum block size in bytes (default: %d)</source>
<translation>Definir tamanho máximo por bloco em bytes (por defeito: %d)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Definir tamanho minímo de um bloco em bytes (por defeito: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Defina o número de processos para servir as chamadas RPC (por defeito: 4)</translation>
</message>
<message>
<location line="+1"/>
<source>Sets the DB_PRIVATE flag in the wallet db environment (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show all debugging options (usage: --help -help-debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show benchmark information (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Falhou assinatura da transação</translation>
</message>
<message>
<location line="+1"/>
<source>Specify configuration file (default: anoncoin.conf)</source>
<translation>Especificar ficheiro de configuração (por defeito: anoncoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify connection timeout in milliseconds (default: 20000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify data directory</source>
<translation>Especificar pasta de dados</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: anoncoind.pid)</source>
<translation>Especificar ficheiro pid (por defeito: anoncoind.pid)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify wallet file (within data directory)</source>
<translation>Especifique ficheiro de carteira (dentro da pasta de dados)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Especifique o seu endereço público</translation>
</message>
<message>
<location line="+1"/>
<source>Spend unconfirmed change when sending transactions (default: 1)</source>
<translation>Gastar saldo não confirmado ao enviar transações (padrão: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>System error: </source>
<translation>Erro de sistema:</translation>
</message>
<message>
<location line="+1"/>
<source>This help message</source>
<translation>Esta mensagem de ajuda</translation>
</message>
<message>
<location line="+1"/>
<source>This is intended for regression testing tools and app development.</source>
<translation>Isto têm como fim a realização de testes de regressão para pools e desenvolvimento de aplicações.</translation>
</message>
<message>
<location line="+1"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Tolerância para desligar nós com comportamento indesejável (por defeito: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>To use the %s option</source>
<translation>Para usar a opção %s</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amount too small</source>
<translation>Quantia da transação é muito baixa</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Quantia da transação deverá ser positiva</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transação grande demais</translation>
</message>
<message>
<location line="+1"/>
<source>Unable to bind to %s on this computer (bind returned error %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Rede desconhecida especificada em -onlynet: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Upgrade wallet to latest format</source>
<translation>Atualize a carteira para o formato mais recente</translation>
</message>
<message>
<location line="+1"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usar OpenSSL (https) para ligações JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Utilizar a rede de testes</translation>
</message>
<message>
<location line="+1"/>
<source>Username for JSON-RPC connections</source>
<translation>Nome de utilizador para ligações JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying blocks...</source>
<translation>A verificar blocos...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>A verificar carteira...</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet %s resides outside data directory %s</source>
<translation>A carteira %s reside fora da pasta de dados %s</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart Anoncoin to complete</source>
<translation>A Carteira precisou de ser reescrita: reinicie o Anoncoin para completar o processo</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet options:</source>
<translation>Opções da carteira:</translation>
</message>
<message>
<location line="+1"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation>Atenção: Argumento obsoleto -debugnet ignorado, usar -debug=net</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the database using -reindex to change -txindex</source>
<translation>É necessário reconstruir as bases de dados usando -reindex para mudar o -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>Zapping all transactions from wallet...</source>
<translation>A limpar todas as transações da carteira...</translation>
</message>
<message>
<location line="+1"/>
<source>on startup</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrompido, recuperação falhou</translation>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>canvas_ext.rs<|end_file_name|><|fim▁begin|>use crate::cache;<|fim▁hole|>use euclid::default::Point2D;
use euclid::vec2;
use vitral::Canvas;
use vitral::{color, Align};
use world::Icon;
/// Magog-specific extensions to Canvas API.
pub trait CanvasExt {
fn draw_entity(&mut self, pos: Point2D<i32>, icon: Icon, count: u32);
fn draw_item_icon(&mut self, pos: Point2D<i32>, icon: Icon, count: u32) {
self.draw_entity(pos + vec2(0, -2), icon, count); // TODO
}
}
impl CanvasExt for Canvas<'_> {
fn draw_entity(&mut self, pos: Point2D<i32>, icon: Icon, count: u32) {
let vec = ScreenVector::from_untyped(pos.to_vector());
for splat in &cache::entity(icon)[0] {
self.draw_image_2color(
&splat.image,
(vec - splat.offset).to_point().to_untyped(),
splat.color,
splat.back_color,
);
}
if count > 1 {
self.draw_outline_text(
&*cache::tiny_font(),
pos - vec2(9, 9),
Align::Left,
color::SILVER,
color::GRAY2,
&format!("{}", count),
);
}
}
}<|fim▁end|> | use crate::view::ScreenVector; |
<|file_name|>Immediate.hh<|end_file_name|><|fim▁begin|>/*
* emucpu -- Emulates processors
* Copyright (C) 2009 Joseph Freeman (jfree143dev AT gmail DOT com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
@file Immediate.hh
@brief Read-only implementation of INumberReadableWritable for immediate values.
*/
#ifndef EMUCPU__IMMEDIATE_HH
#define EMUCPU__IMMEDIATE_HH
#include "INumberReadableWritable.hh"
#include <iostream>
#include "Types.hh"
/**
@class Immediate
@brief Read-only implementation of INumberReadableWritable for immediate values.
*/
template<typename T>
class Immediate : public INumberReadableWritable<T> {
T *m_num;
bool m_deletable;
public:
/** */
Immediate () {
m_num = new T ();
m_deletable = true;
}
/** */
Immediate (const Immediate<T> &src) {
//if (src.m_deletable) {
m_num = new T ();
*m_num = *(src.m_num);
m_deletable = true;
/*
}
else {
m_num = src.m_num;
m_deletable = false;
}
*/
}
/** */
Immediate (T &r, bool cp=false) {
if (cp) {
m_num = new T ();
*m_num = r;
m_deletable = true;
}
else {
m_num = &r;
m_deletable = false;
}
}
/** */
Immediate (const T &r) {
m_num = new T ();
*m_num = r;
m_deletable = true;
}
/** */
virtual ~Immediate () {
if (m_deletable) {
delete m_num;
}
}
private:
void reinitialize (T &r) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
}
void reinitialize (const T &r) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
}
public:
/** @brief Implicit cast to stored value. */
virtual operator const T& () const {
return *m_num;
}
/** @brief Get the stored value. */
virtual const T& getValue () const {
return *m_num;
}
private:
virtual uint16 getSegment () const {
std::cerr << "Debug: class Immediate has no segment" << std::endl;
return 0;
}
virtual uint16 getOffset () const {
std::cerr << "Debug: class Immediate has no offset" << std::endl;
return 0;
}
virtual const INumberReadableWritable<T>& operator++ () {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual const T operator++ (int32) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *m_num;
}
virtual const INumberReadableWritable<T>& operator-- () {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual const T operator-- (int32) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *m_num;
}
virtual INumberReadableWritable<T>& operator= (const T &right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator= (const INumberReadableWritable<T> &right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator= (const Immediate<T> &right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator+= (const T& right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator-= (const T& right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator*= (const T& right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator/= (const T& right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator%= (const T& right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator^= (const T& right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator&= (const T& right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator|= (const T& right) {<|fim▁hole|> }
virtual INumberReadableWritable<T>& operator>>= (const T& right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
virtual INumberReadableWritable<T>& operator<<= (const T& right) {
std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this;
}
}; //end class Immediate
#endif //EMUCPU__IMMEDIATE_HH<|fim▁end|> | std::cerr << "Debug: class Immediate is read-only" << std::endl;
return *this; |
<|file_name|>XExpressionImpl.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.
*/
package com.intellij.xdebugger.impl.breakpoints;
import com.intellij.lang.Language;
import com.intellij.xdebugger.XExpression;
import com.intellij.xdebugger.evaluation.EvaluationMode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author egor
*/
public class XExpressionImpl implements XExpression {
public static final XExpression EMPTY_EXPRESSION = fromText("", EvaluationMode.EXPRESSION);
public static final XExpression EMPTY_CODE_FRAGMENT = fromText("", EvaluationMode.CODE_FRAGMENT);
@NotNull private final String myExpression;
private final Language myLanguage;
private final String myCustomInfo;
private final EvaluationMode myMode;
public XExpressionImpl(@NotNull String expression, Language language, String customInfo) {
this(expression, language, customInfo, EvaluationMode.EXPRESSION);
}
public XExpressionImpl(@NotNull String expression, Language language, String customInfo, EvaluationMode mode) {
myExpression = expression;
myLanguage = language;
myCustomInfo = customInfo;
myMode = mode;
}
@NotNull
@Override
public String getExpression() {
return myExpression;
}
@Override
public Language getLanguage() {
return myLanguage;
}
@Override
public String getCustomInfo() {
return myCustomInfo;
}
@Override
public EvaluationMode getMode() {
return myMode;
}<|fim▁hole|> @Nullable
public static XExpressionImpl fromText(@Nullable String text) {
return text != null ? new XExpressionImpl(text, null, null, EvaluationMode.EXPRESSION) : null;
}
@Nullable
public static XExpressionImpl fromText(@Nullable String text, EvaluationMode mode) {
return text != null ? new XExpressionImpl(text, null, null, mode) : null;
}
public static XExpressionImpl changeMode(XExpression expression, EvaluationMode mode) {
return new XExpressionImpl(expression.getExpression(), expression.getLanguage(), expression.getCustomInfo(), mode);
}
@Override
public String toString() {
return myExpression;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
XExpressionImpl that = (XExpressionImpl)o;
if (myCustomInfo != null ? !myCustomInfo.equals(that.myCustomInfo) : that.myCustomInfo != null) return false;
if (!myExpression.equals(that.myExpression)) return false;
if (myLanguage != null ? !myLanguage.equals(that.myLanguage) : that.myLanguage != null) return false;
if (myMode != that.myMode) return false;
return true;
}
@Override
public int hashCode() {
int result = myExpression.hashCode();
result = 31 * result + (myLanguage != null ? myLanguage.hashCode() : 0);
result = 31 * result + (myCustomInfo != null ? myCustomInfo.hashCode() : 0);
result = 31 * result + (myMode != null ? myMode.hashCode() : 0);
return result;
}
}<|fim▁end|> | |
<|file_name|>clients.js<|end_file_name|><|fim▁begin|>// Reset
$('.touch .client-wrap').click(function(event){
var target = $( event.target );
if ( target.hasClass( "client-close" ) ) {
$('.client-wrap div.client').addClass('reset');
}
else{
$('.client-wrap div.client').removeClass('reset');
}
});
// David Walsh simple lazy loading
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
img.setAttribute('src', img.getAttribute('data-src'));<|fim▁hole|> img.onload = function() {
img.removeAttribute('data-src');
};
});<|fim▁end|> | |
<|file_name|>model.py<|end_file_name|><|fim▁begin|># Copyright 2017 SAS Project 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.
# This module implements the combination of the eHata and ITM models
# according to the requirements developed in the Winnforum WG1 Propagation
# task group.
import math
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ehata import ehata
from itm import pytm
from geo import tropoClim
from geo import refractivity
from geo import ned_indexer
from geo import nlcd_indexer
from geo import land_use
from geo import vincenty
# f in MHz; d and h1/h2 all in meters
def FreeSpacePathLoss(f, d, h1, h2):
r = math.sqrt(d*d + (h1-h2)*(h1-h2))
return 20*math.log10(r) + 20*math.log10(f) - 27.56
class PropagationLossModel:
def __init__(self, itu_dir, ned_dir, nlcd_dir):
self.climIndx = tropoClim.ClimateIndexer(itu_dir)
self.refractivityIndx = refractivity.RefractivityIndexer(itu_dir)
self.nedIndx = ned_indexer.NedIndexer(ned_dir)
self.nlcdIndx = nlcd_indexer.NlcdIndexer(nlcd_dir)
# Calculate the ITM adjusted propagation loss given the
# assumptions on the ITM model.
def ITM_AdjustedPropagationLoss(self, lat1, lng1, h1, lat2, lng2, h2, f, reliability):
dielectric_constant = 25.0 # good ground
soil_conductivity = 0.02 # good ground
polarization = 1
confidence = 0.5
# get surface refractivity and radio climate from path midpoint
dist, bearing, rev_bearing = vincenty.dist_bear_vincenty(lat1, lng1, lat2, lng2)
lat_c, lng_c, alpha2 = vincenty.to_dist_bear_vincenty(lat1, lng1, dist/2.0, bearing)
print 'Midpoint = %f, %f' % (lat_c, lng_c)
radio_climate = self.climIndx.TropoClim(lat_c, lng_c)
refractivity = self.refractivityIndx.Refractivity(lat_c, lng_c)
print 'Using climate %d' % radio_climate
print 'Using refractivity %f' % refractivity
print 'Using freq %f' % f
profile = self.nedIndx.Profile(lat1, lng1, lat2, lng2)
print profile[0], profile[1]
#print profile
print 'total distance is ', profile[0]*profile[1]
loss = pytm.point_to_point(profile, h1, h2,
dielectric_constant,
soil_conductivity,
refractivity,
f,
radio_climate,
polarization,
confidence,
reliability)
print 'ITM P2P is ', loss
return loss
# Adjusted propagation loss according to the adjustments in R2-SGN-04
# distance d, heights h1, h2 all in meters
# frequency f in MHz
def ExtendedHata_AdjustedPropagationLoss(self, lat1, lng1, h1, lat2, lng2, h2, f, land_cat):
d, bearing, rev_bearing = vincenty.dist_bear_vincenty(lat1, lng1, lat2, lng2)
d = d*1000.0
print 'EHata distance=', d
if d <= 100.0:
# return FSPL
print 'FSPL'
return FreeSpacePathLoss(f, d, h1, h2)
if d > 100.0 and d <= 1000.0:
print 'interp FSPL and ehata'
# interpolate FSPL and ehata
fspl_loss = FreeSpacePathLoss(f, 100.0, h1, h2)
print ' fspl_loss=', fspl_loss
ehata_loss, abm = ehata.ExtendedHata_MedianBasicPropLoss(f, 1.0, h1, h2, land_cat)
print ' ehata_loss=', ehata_loss
print ' ( abm=', abm
return fspl_loss + (1.0 + math.log10(d/1000.0))*(ehata_loss - fspl_loss)
if d > 1000.0 and d < 80000.0:
# return eHata value without adjustment.
print 'EHata only for d=%f' % d
profile = self.nedIndx.Profile(lat1, lng1, lat2, lng2)
return ehata.ExtendedHata_PropagationLoss(f, h1, h2, land_cat, profile)
if d >= 80000.0:
print 'EHata for distance %f > 80km' % d
# Derive profile_80km
lat_80, lng_80, heading = vincenty.to_dist_bear_vincenty(lat1, lng1, 80.0, bearing)
print '80km point is %f %f' % (lat_80, lng_80)
profile_80km = self.nedIndx.Profile(lat1, lng1, lat_80, lng_80)
# Find J adjustment...
ehata_loss = ehata.ExtendedHata_PropagationLoss(f, h1, h2, land_cat, profile_80km)
itm_loss = self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat_80, lng_80, h2, f, 0.5)
J = ehata_loss - itm_loss
print 'Got ehata=%f itm=%f J=%f' % (ehata_loss, itm_loss, J)
if J < 0.0:
J = 0.0
return self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, 0.5) + J
def LandClassification(self, lat, lng):
code = self.nlcdIndx.NlcdCode(lat, lng)
return self.nlcdIndx.NlcdLandCategory(code)
# This is the oracle for propagation loss from point 1 to point 2 at frequency f (Mhz).
def PropagationLoss(self, f, lat1, lng1, h1, lat2, lng2, h2, land_cat=''):
if land_cat == '':
code = self.nlcdIndx.NlcdCode(lat2, lng2)
if code == 11:
code = self.nlcdIndx.NlcdCode(lat1, lng1)
land_cat = land_use.NlcdLandCategory(code)
print 'Using land_cat =', land_cat
# Calculate effective heights of tx and rx:
profile = self.nedIndx.Profile(lat1, lng1, lat2, lng2)
h1eff, h2eff = EffectiveHeights(h1, h2, profile)
if land_cat == 'RURAL' or h1eff >= 200: # Only h1eff (CBSD effective height) counts
itm_loss = self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, 0.5)
print 'Returning itm_loss for rural > 200: ', itm_loss
return itm_loss
else:
itm_loss = self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, 0.5)
ehata_loss = self.ExtendedHata_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, land_cat)
if ehata_loss > itm_loss:<|fim▁hole|># Run directly, takes args of "lat1, lng1, h1, lat2, lng2, h2, f" and prints the
# (median) propagation loss in dB.
if __name__ == '__main__':
dir = os.path.dirname(os.path.realpath(__file__))
rootDir = os.path.dirname(os.path.dirname(dir))
ituDir = os.path.join(os.path.join(rootDir, 'data'), 'itu')
nedDir = os.path.join(os.path.join(rootDir, 'data'), 'ned')
nlcdDir = os.path.join(os.path.join(rootDir, 'data'), 'nlcd')
prop = PropagationLossModel(ituDir, nedDir, nlcdDir)
loss = prop.PropagationLoss(float(sys.argv[1]), float(sys.argv[2]), float(sys.argv[3]),
float(sys.argv[4]), float(sys.argv[5]), float(sys.argv[6]),
float(sys.argv[7]))
print 'Propagation Loss = ', loss, ' dB'<|fim▁end|> | return ehata_loss
return itm_loss
|
<|file_name|>example-nrf24-recv.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Example program to receive packets from the radio link
#
import virtGPIO as GPIO
from lib_nrf24 import NRF24
import time
pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]]
radio2 = NRF24(GPIO, GPIO.SpiDev())
radio2.begin(9, 7)
radio2.setRetries(15,15)
radio2.setPayloadSize(32)
radio2.setChannel(0x60)
radio2.setDataRate(NRF24.BR_2MBPS)
radio2.setPALevel(NRF24.PA_MIN)
radio2.setAutoAck(True)
radio2.enableDynamicPayloads()
radio2.enableAckPayload()
radio2.openWritingPipe(pipes[0])
radio2.openReadingPipe(1, pipes[1])
radio2.startListening()
radio2.stopListening()
radio2.printDetails()
radio2.startListening()
c=1
while True:
akpl_buf = [c,1, 2, 3,4,5,6,7,8,9,0,1, 2, 3,4,5,6,7,8]
pipe = [0]
while not radio2.available(pipe):
time.sleep(10000/1000000.0)
recv_buffer = []
radio2.read(recv_buffer, radio2.getDynamicPayloadSize())
print ("Received:") ,
print (recv_buffer)
c = c + 1
if (c&1) == 0:<|fim▁hole|> print ("Loaded payload reply:"),
print (akpl_buf)
else:
print ("(No return payload)")<|fim▁end|> | radio2.writeAckPayload(1, akpl_buf, len(akpl_buf)) |
<|file_name|>recording-job-created-event.js<|end_file_name|><|fim▁begin|>/**
* Copyright 2016 Google Inc.
*
* 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.
*/
goog.provide('audioCat.audio.record.RecordingJobCreatedEvent');
goog.require('audioCat.audio.record.Event');
goog.require('audioCat.utility.Event');
/**
* An event marking the creation of a new recording job.
* @param {!audioCat.audio.record.RecordingJob} recordingJob The newly created<|fim▁hole|> */
audioCat.audio.record.RecordingJobCreatedEvent = function(recordingJob) {
goog.base(this, audioCat.audio.record.Event.DEFAULT_RECORDING_JOB_CREATED);
/**
* The newly made recording job.
* @type {!audioCat.audio.record.RecordingJob}
*/
this.recordingJob = recordingJob;
};
goog.inherits(
audioCat.audio.record.RecordingJobCreatedEvent, audioCat.utility.Event);<|fim▁end|> | * job recording.
* @constructor
* @extends {audioCat.utility.Event} |
<|file_name|>util.js<|end_file_name|><|fim▁begin|>import { IS_DART, StringWrapper, isBlank, isPresent, isString, isArray } from 'angular2/src/facade/lang';
var CAMEL_CASE_REGEXP = /([A-Z])/g;
var DASH_CASE_REGEXP = /-([a-z])/g;
var SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
var DOUBLE_QUOTE_ESCAPE_STRING_RE = /"|\\|\n|\r|\$/g;
export var MODULE_SUFFIX = IS_DART ? '.dart' : '.js';
export var CONST_VAR = IS_DART ? 'const' : 'var';
export function camelCaseToDashCase(input) {
return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, (m) => { return '-' + m[1].toLowerCase(); });
}
export function dashCaseToCamelCase(input) {
return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, (m) => { return m[1].toUpperCase(); });
}
export function escapeSingleQuoteString(input) {
<|fim▁hole|> return `'${escapeString(input, SINGLE_QUOTE_ESCAPE_STRING_RE)}'`;
}
export function escapeDoubleQuoteString(input) {
if (isBlank(input)) {
return null;
}
return `"${escapeString(input, DOUBLE_QUOTE_ESCAPE_STRING_RE)}"`;
}
function escapeString(input, re) {
return StringWrapper.replaceAllMapped(input, re, (match) => {
if (match[0] == '$') {
return IS_DART ? '\\$' : '$';
}
else if (match[0] == '\n') {
return '\\n';
}
else if (match[0] == '\r') {
return '\\r';
}
else {
return `\\${match[0]}`;
}
});
}
export function codeGenExportVariable(name) {
if (IS_DART) {
return `const ${name} = `;
}
else {
return `var ${name} = exports['${name}'] = `;
}
}
export function codeGenConstConstructorCall(name) {
if (IS_DART) {
return `const ${name}`;
}
else {
return `new ${name}`;
}
}
export function codeGenValueFn(params, value, fnName = '') {
if (IS_DART) {
return `${codeGenFnHeader(params, fnName)} => ${value}`;
}
else {
return `${codeGenFnHeader(params, fnName)} { return ${value}; }`;
}
}
export function codeGenFnHeader(params, fnName = '') {
if (IS_DART) {
return `${fnName}(${params.join(',')})`;
}
else {
return `function ${fnName}(${params.join(',')})`;
}
}
export function codeGenToString(expr) {
if (IS_DART) {
return `'\${${expr}}'`;
}
else {
// JS automatically converts to string...
return expr;
}
}
export function splitAtColon(input, defaultValues) {
var parts = StringWrapper.split(input.trim(), /\s*:\s*/g);
if (parts.length > 1) {
return parts;
}
else {
return defaultValues;
}
}
export class Statement {
constructor(statement) {
this.statement = statement;
}
}
export class Expression {
constructor(expression, isArray = false) {
this.expression = expression;
this.isArray = isArray;
}
}
export function escapeValue(value) {
if (value instanceof Expression) {
return value.expression;
}
else if (isString(value)) {
return escapeSingleQuoteString(value);
}
else if (isBlank(value)) {
return 'null';
}
else {
return `${value}`;
}
}
export function codeGenArray(data) {
return `[${data.map(escapeValue).join(',')}]`;
}
export function codeGenFlatArray(values) {
var result = '([';
var isFirstArrayEntry = true;
var concatFn = IS_DART ? '.addAll' : 'concat';
for (var i = 0; i < values.length; i++) {
var value = values[i];
if (value instanceof Expression && value.isArray) {
result += `]).${concatFn}(${value.expression}).${concatFn}([`;
isFirstArrayEntry = true;
}
else {
if (!isFirstArrayEntry) {
result += ',';
}
isFirstArrayEntry = false;
result += escapeValue(value);
}
}
result += '])';
return result;
}
export function codeGenStringMap(keyValueArray) {
return `{${keyValueArray.map(codeGenKeyValue).join(',')}}`;
}
function codeGenKeyValue(keyValue) {
return `${escapeValue(keyValue[0])}:${escapeValue(keyValue[1])}`;
}
export function addAll(source, target) {
for (var i = 0; i < source.length; i++) {
target.push(source[i]);
}
}
export function flattenArray(source, target) {
if (isPresent(source)) {
for (var i = 0; i < source.length; i++) {
var item = source[i];
if (isArray(item)) {
flattenArray(item, target);
}
else {
target.push(item);
}
}
}
return target;
}<|fim▁end|> | if (isBlank(input)) {
return null;
}
|
<|file_name|>categories.ts<|end_file_name|><|fim▁begin|>import { CategoriesActions, CategoriesActionTypes } from '../actions';
export interface State {
data: string[];
}
const initialState: State = {
data: []
};
export function reducer(state = initialState, action: CategoriesActions): State {
switch (action.type) {
case CategoriesActionTypes.LoadSuccess: {
return {
...state,
data: action.payload.categories
};
}
default: {
return state;
}<|fim▁hole|>}
export const getData = (state: State) => state.data;<|fim▁end|> | } |
<|file_name|>canvas.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use euclid::{Transform2D, Point2D, Vector2D, Rect, Size2D};
use ipc_channel::ipc::IpcSender;
use std::default::Default;
use std::str::FromStr;
use webrender_api;
#[derive(Clone, Deserialize, Serialize)]
pub enum FillRule {
Nonzero,
Evenodd,
}
#[derive(Clone, Deserialize, Serialize)]
pub enum CanvasMsg {
Canvas2d(Canvas2dMsg),
FromLayout(FromLayoutMsg),
FromScript(FromScriptMsg),
Recreate(Size2D<i32>),
Close,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct CanvasImageData {
pub image_key: webrender_api::ImageKey,
}
#[derive(Clone, Deserialize, Serialize)]
pub enum Canvas2dMsg {
Arc(Point2D<f32>, f32, f32, f32, bool),
ArcTo(Point2D<f32>, Point2D<f32>, f32),
DrawImage(Vec<u8>, Size2D<f64>, Rect<f64>, Rect<f64>, bool),
DrawImageSelf(Size2D<f64>, Rect<f64>, Rect<f64>, bool),
DrawImageInOther(
IpcSender<CanvasMsg>, Size2D<f64>, Rect<f64>, Rect<f64>, bool, IpcSender<()>),
BeginPath,
BezierCurveTo(Point2D<f32>, Point2D<f32>, Point2D<f32>),
ClearRect(Rect<f32>),
Clip,
ClosePath,
Ellipse(Point2D<f32>, f32, f32, f32, f32, f32, bool),
Fill,
FillText(String, f64, f64, Option<f64>),
FillRect(Rect<f32>),
GetImageData(Rect<i32>, Size2D<f64>, IpcSender<Vec<u8>>),
IsPointInPath(f64, f64, FillRule, IpcSender<bool>),
LineTo(Point2D<f32>),
MoveTo(Point2D<f32>),
PutImageData(Vec<u8>, Vector2D<f64>, Size2D<f64>, Rect<f64>),
QuadraticCurveTo(Point2D<f32>, Point2D<f32>),
Rect(Rect<f32>),
RestoreContext,
SaveContext,
StrokeRect(Rect<f32>),
Stroke,
SetFillStyle(FillOrStrokeStyle),
SetStrokeStyle(FillOrStrokeStyle),
SetLineWidth(f32),
SetLineCap(LineCapStyle),
SetLineJoin(LineJoinStyle),
SetMiterLimit(f32),
SetGlobalAlpha(f32),
SetGlobalComposition(CompositionOrBlending),
SetTransform(Transform2D<f32>),
SetShadowOffsetX(f64),
SetShadowOffsetY(f64),
SetShadowBlur(f64),
SetShadowColor(RGBA),
}
#[derive(Clone, Deserialize, Serialize)]
pub enum FromLayoutMsg {
SendData(IpcSender<CanvasImageData>),
}
#[derive(Clone, Deserialize, Serialize)]
pub enum FromScriptMsg {
SendPixels(IpcSender<Option<Vec<u8>>>),
}
#[derive(Clone, Deserialize, MallocSizeOf, Serialize)]
pub struct CanvasGradientStop {
pub offset: f64,
pub color: RGBA,
}
#[derive(Clone, Deserialize, MallocSizeOf, Serialize)]
pub struct LinearGradientStyle {<|fim▁hole|> pub stops: Vec<CanvasGradientStop>
}
impl LinearGradientStyle {
pub fn new(x0: f64, y0: f64, x1: f64, y1: f64, stops: Vec<CanvasGradientStop>)
-> LinearGradientStyle {
LinearGradientStyle {
x0: x0,
y0: y0,
x1: x1,
y1: y1,
stops: stops,
}
}
}
#[derive(Clone, Deserialize, MallocSizeOf, Serialize)]
pub struct RadialGradientStyle {
pub x0: f64,
pub y0: f64,
pub r0: f64,
pub x1: f64,
pub y1: f64,
pub r1: f64,
pub stops: Vec<CanvasGradientStop>
}
impl RadialGradientStyle {
pub fn new(x0: f64, y0: f64, r0: f64, x1: f64, y1: f64, r1: f64, stops: Vec<CanvasGradientStop>)
-> RadialGradientStyle {
RadialGradientStyle {
x0: x0,
y0: y0,
r0: r0,
x1: x1,
y1: y1,
r1: r1,
stops: stops,
}
}
}
#[derive(Clone, Deserialize, Serialize)]
pub struct SurfaceStyle {
pub surface_data: Vec<u8>,
pub surface_size: Size2D<i32>,
pub repeat_x: bool,
pub repeat_y: bool,
}
impl SurfaceStyle {
pub fn new(surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat_x: bool, repeat_y: bool)
-> SurfaceStyle {
SurfaceStyle {
surface_data: surface_data,
surface_size: surface_size,
repeat_x: repeat_x,
repeat_y: repeat_y,
}
}
}
#[derive(Clone, Deserialize, Serialize)]
pub enum FillOrStrokeStyle {
Color(RGBA),
LinearGradient(LinearGradientStyle),
RadialGradient(RadialGradientStyle),
Surface(SurfaceStyle),
}
#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)]
pub enum LineCapStyle {
Butt = 0,
Round = 1,
Square = 2,
}
impl FromStr for LineCapStyle {
type Err = ();
fn from_str(string: &str) -> Result<LineCapStyle, ()> {
match string {
"butt" => Ok(LineCapStyle::Butt),
"round" => Ok(LineCapStyle::Round),
"square" => Ok(LineCapStyle::Square),
_ => Err(()),
}
}
}
#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)]
pub enum LineJoinStyle {
Round = 0,
Bevel = 1,
Miter = 2,
}
impl FromStr for LineJoinStyle {
type Err = ();
fn from_str(string: &str) -> Result<LineJoinStyle, ()> {
match string {
"round" => Ok(LineJoinStyle::Round),
"bevel" => Ok(LineJoinStyle::Bevel),
"miter" => Ok(LineJoinStyle::Miter),
_ => Err(()),
}
}
}
#[derive(Clone, Copy, Deserialize, PartialEq, Serialize)]
pub enum RepetitionStyle {
Repeat,
RepeatX,
RepeatY,
NoRepeat,
}
impl FromStr for RepetitionStyle {
type Err = ();
fn from_str(string: &str) -> Result<RepetitionStyle, ()> {
match string {
"repeat" => Ok(RepetitionStyle::Repeat),
"repeat-x" => Ok(RepetitionStyle::RepeatX),
"repeat-y" => Ok(RepetitionStyle::RepeatY),
"no-repeat" => Ok(RepetitionStyle::NoRepeat),
_ => Err(()),
}
}
}
#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)]
pub enum CompositionStyle {
SrcIn,
SrcOut,
SrcOver,
SrcAtop,
DestIn,
DestOut,
DestOver,
DestAtop,
Copy,
Lighter,
Xor,
}
impl FromStr for CompositionStyle {
type Err = ();
fn from_str(string: &str) -> Result<CompositionStyle, ()> {
match string {
"source-in" => Ok(CompositionStyle::SrcIn),
"source-out" => Ok(CompositionStyle::SrcOut),
"source-over" => Ok(CompositionStyle::SrcOver),
"source-atop" => Ok(CompositionStyle::SrcAtop),
"destination-in" => Ok(CompositionStyle::DestIn),
"destination-out" => Ok(CompositionStyle::DestOut),
"destination-over" => Ok(CompositionStyle::DestOver),
"destination-atop" => Ok(CompositionStyle::DestAtop),
"copy" => Ok(CompositionStyle::Copy),
"lighter" => Ok(CompositionStyle::Lighter),
"xor" => Ok(CompositionStyle::Xor),
_ => Err(())
}
}
}
impl CompositionStyle {
pub fn to_str(&self) -> &str {
match *self {
CompositionStyle::SrcIn => "source-in",
CompositionStyle::SrcOut => "source-out",
CompositionStyle::SrcOver => "source-over",
CompositionStyle::SrcAtop => "source-atop",
CompositionStyle::DestIn => "destination-in",
CompositionStyle::DestOut => "destination-out",
CompositionStyle::DestOver => "destination-over",
CompositionStyle::DestAtop => "destination-atop",
CompositionStyle::Copy => "copy",
CompositionStyle::Lighter => "lighter",
CompositionStyle::Xor => "xor",
}
}
}
#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)]
pub enum BlendingStyle {
Multiply,
Screen,
Overlay,
Darken,
Lighten,
ColorDodge,
ColorBurn,
HardLight,
SoftLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
}
impl FromStr for BlendingStyle {
type Err = ();
fn from_str(string: &str) -> Result<BlendingStyle, ()> {
match string {
"multiply" => Ok(BlendingStyle::Multiply),
"screen" => Ok(BlendingStyle::Screen),
"overlay" => Ok(BlendingStyle::Overlay),
"darken" => Ok(BlendingStyle::Darken),
"lighten" => Ok(BlendingStyle::Lighten),
"color-dodge" => Ok(BlendingStyle::ColorDodge),
"color-burn" => Ok(BlendingStyle::ColorBurn),
"hard-light" => Ok(BlendingStyle::HardLight),
"soft-light" => Ok(BlendingStyle::SoftLight),
"difference" => Ok(BlendingStyle::Difference),
"exclusion" => Ok(BlendingStyle::Exclusion),
"hue" => Ok(BlendingStyle::Hue),
"saturation" => Ok(BlendingStyle::Saturation),
"color" => Ok(BlendingStyle::Color),
"luminosity" => Ok(BlendingStyle::Luminosity),
_ => Err(())
}
}
}
impl BlendingStyle {
pub fn to_str(&self) -> &str {
match *self {
BlendingStyle::Multiply => "multiply",
BlendingStyle::Screen => "screen",
BlendingStyle::Overlay => "overlay",
BlendingStyle::Darken => "darken",
BlendingStyle::Lighten => "lighten",
BlendingStyle::ColorDodge => "color-dodge",
BlendingStyle::ColorBurn => "color-burn",
BlendingStyle::HardLight => "hard-light",
BlendingStyle::SoftLight => "soft-light",
BlendingStyle::Difference => "difference",
BlendingStyle::Exclusion => "exclusion",
BlendingStyle::Hue => "hue",
BlendingStyle::Saturation => "saturation",
BlendingStyle::Color => "color",
BlendingStyle::Luminosity => "luminosity",
}
}
}
#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)]
pub enum CompositionOrBlending {
Composition(CompositionStyle),
Blending(BlendingStyle),
}
impl Default for CompositionOrBlending {
fn default() -> CompositionOrBlending {
CompositionOrBlending::Composition(CompositionStyle::SrcOver)
}
}
impl FromStr for CompositionOrBlending {
type Err = ();
fn from_str(string: &str) -> Result<CompositionOrBlending, ()> {
if let Ok(op) = CompositionStyle::from_str(string) {
return Ok(CompositionOrBlending::Composition(op));
}
if let Ok(op) = BlendingStyle::from_str(string) {
return Ok(CompositionOrBlending::Blending(op));
}
Err(())
}
}
// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this.
pub fn byte_swap(data: &mut [u8]) {
let length = data.len();
// FIXME(rust #27741): Range::step_by is not stable yet as of this writing.
let mut i = 0;
while i < length {
let r = data[i + 2];
data[i + 2] = data[i + 0];
data[i + 0] = r;
i += 4;
}
}
pub fn multiply_u8_pixel(a: u8, b: u8) -> u8 {
return (a as u32 * b as u32 / 255) as u8;
}
pub fn byte_swap_and_premultiply(data: &mut [u8]) {
let length = data.len();
let mut i = 0;
while i < length {
let r = data[i + 2];
let g = data[i + 1];
let b = data[i + 0];
let a = data[i + 3];
data[i + 0] = multiply_u8_pixel(r, a);
data[i + 1] = multiply_u8_pixel(g, a);
data[i + 2] = multiply_u8_pixel(b, a);
i += 4;
}
}<|fim▁end|> | pub x0: f64,
pub y0: f64,
pub x1: f64,
pub y1: f64, |
<|file_name|>toc_tree.go<|end_file_name|><|fim▁begin|>// This is free and unencumbered software released into the public
// domain. For more information, see <http://unlicense.org> or the
// accompanying UNLICENSE file.
package navigator
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"github.com/nelsam/gxui"
"github.com/nelsam/gxui/math"
"github.com/nelsam/gxui/mixins"
"github.com/nelsam/gxui/themes/basic"
"github.com/nelsam/vidar/command/focus"
"github.com/nelsam/vidar/commander/bind"
)
var (
genericColor = gxui.Color{
R: 0.6,
G: 0.8,
B: 1,
A: 1,
}
nameColor = gxui.Color{
R: 0.6,
G: 1,
B: 0.5,
A: 1,
}
nonGoColor = gxui.Color{
R: 0.9,
G: 0.9,
B: 0.9,
A: 1,
}
errColor = gxui.Color{
R: 0.9,
G: 0.2,
B: 0,
A: 1,
}
skippableColor = gxui.Color{
R: 0.9,
G: 0.6,
B: 0.8,
A: 1,
}
// Since the const values aren't exported by go/build, I've just copied them
// from https://github.com/golang/go/blob/master/src/go/build/syslist.go
gooses = []string{
"android", "darwin", "dragonfly", "freebsd", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "windows",
}
goarches = []string{
"386", "amd64", "amd64p32", "arm", "armbe", "arm64", "arm64be", "ppc64", "ppc64le", "mips", "mipsle", "mips64",
"mips64le", "mips64p32", "mips64p32le", "ppc", "s390", "s390x", "sparc", "sparc64",
}
)
type Commander interface {
Bindable(name string) bind.Bindable
Execute(bind.Bindable)
}
type Opener interface {
For(...focus.Opt) bind.Bindable
}
type genericNode struct {
mixins.LinearLayout
driver gxui.Driver
theme gxui.Theme
button *treeButton
children gxui.LinearLayout
}
func newGenericNode(driver gxui.Driver, theme gxui.Theme, name string, color gxui.Color) *genericNode {
g := &genericNode{}
g.Init(g, driver, theme, name, color)
return g
}
func (n *genericNode) Init(outer mixins.LinearLayoutOuter, driver gxui.Driver, theme gxui.Theme, name string, color gxui.Color) {
n.LinearLayout.Init(outer, theme)
n.driver = driver
n.theme = theme
n.SetDirection(gxui.TopToBottom)
n.button = newTreeButton(driver, theme.(*basic.Theme), name)
n.button.Label().SetColor(color)
n.LinearLayout.AddChild(n.button)
n.children = theme.CreateLinearLayout()
n.children.SetDirection(gxui.TopToBottom)
n.children.SetMargin(math.Spacing{L: 10})
}
func (n *genericNode) AddChild(c gxui.Control) *gxui.Child {
child := n.children.AddChild(c)
if len(n.children.Children()) > 1 {
return child
}
n.button.SetExpandable(true)
n.button.OnClick(func(gxui.MouseEvent) {
if n.children.Attached() {
n.LinearLayout.RemoveChild(n.children)
n.button.Collapse()
return
}
n.LinearLayout.AddChild(n.children)
n.button.Expand()
})
return child
}
func (n *genericNode) MissingChild() gxui.Control {
if n.children.Attached() {
return nil
}
return n.children
}
type packageNode struct {
genericNode
cmdr Commander
consts, vars, types, funcs *genericNode
typeMap map[string]*Name
}
func newPackageNode(cmdr Commander, driver gxui.Driver, theme gxui.Theme, name string) *packageNode {
node := &packageNode{
cmdr: cmdr,
consts: newGenericNode(driver, theme, "constants", genericColor),
vars: newGenericNode(driver, theme, "vars", genericColor),
types: newGenericNode(driver, theme, "types", genericColor),
funcs: newGenericNode(driver, theme, "funcs", genericColor),
typeMap: make(map[string]*Name),
}
node.Init(node, driver, theme, name, skippableColor)
node.AddChild(node.consts)
node.AddChild(node.vars)
node.AddChild(node.types)
node.AddChild(node.funcs)
return node
}
func (p *packageNode) expand() {
p.consts.button.Click(gxui.MouseEvent{})
p.vars.button.Click(gxui.MouseEvent{})
p.types.button.Click(gxui.MouseEvent{})
p.funcs.button.Click(gxui.MouseEvent{})
}
func (p *packageNode) addConsts(consts ...*Name) {
for _, c := range consts {
p.consts.AddChild(c)
}
}
func (p *packageNode) addVars(vars ...*Name) {
for _, v := range vars {
p.vars.AddChild(v)
}
}
func (p *packageNode) addTypes(types ...*Name) {
for _, typ := range types {
// Since we can't guarantee that we parsed the type declaration before
// any method declarations, we have to check to see if the type already
// exists.
existingType, ok := p.typeMap[typ.button.Text()]
if !ok {
p.typeMap[typ.button.Text()] = typ
p.types.AddChild(typ)
continue
}
existingType.button.Label().SetColor(typ.button.Label().Color())
existingType.filepath = typ.filepath
existingType.position = typ.position
}
}
func (p *packageNode) addFuncs(funcs ...*Name) {
for _, f := range funcs {
p.funcs.AddChild(f)
}
}
func (p *packageNode) addMethod(typeName string, method *Name) {
typ, ok := p.typeMap[typeName]
if !ok {
typ = newName(p.cmdr, p.driver, p.theme, typeName, nameColor)
p.typeMap[typeName] = typ
p.types.AddChild(typ)
}
typ.AddChild(method)
}
type Location struct {
filepath string
position token.Position
}
func (l Location) File() string {
return l.filepath
}
func (l Location) Position() token.Position {
return l.position
}
type Name struct {
genericNode
Location
cmdr Commander
}
func newName(cmdr Commander, driver gxui.Driver, theme gxui.Theme, name string, color gxui.Color) *Name {
node := &Name{cmdr: cmdr}
node.Init(node, driver, theme, name, color)
node.button.OnClick(func(gxui.MouseEvent) {
cmd := node.cmdr.Bindable("focus-location").(Opener)
node.cmdr.Execute(cmd.For(focus.Path(node.File()), focus.Offset(node.Position().Offset)))
})
return node
}
type TOC struct {
mixins.LinearLayout
cmdr Commander
driver gxui.Driver
theme gxui.Theme
dir string
fileSet *token.FileSet
packageMap map[string]*packageNode
lock sync.Mutex
}
func NewTOC(cmdr Commander, driver gxui.Driver, theme gxui.Theme, dir string) *TOC {
toc := &TOC{
cmdr: cmdr,
driver: driver,
theme: theme,
dir: dir,
}
toc.Init(toc, theme)
toc.Reload()
return toc
}
func (t *TOC) Reload() {
t.lock.Lock()
defer t.lock.Unlock()
defer t.expandPackages()
t.fileSet = token.NewFileSet()
t.RemoveAll()
t.packageMap = make(map[string]*packageNode)
allFiles, err := ioutil.ReadDir(t.dir)
if err != nil {
log.Printf("Received error reading directory %s: %s", t.dir, err)
return
}
t.parseFiles(t.dir, allFiles...)
}
func (t *TOC) expandPackages() {
for _, c := range t.Children() {
pkg, ok := c.Control.(*packageNode)
if !ok {
continue
}
pkg.button.Click(gxui.MouseEvent{})
pkg.expand()
}
}
func (t *TOC) parseFiles(dir string, files ...os.FileInfo) {
filesNode := newGenericNode(t.driver, t.theme, "files", skippableColor)
t.AddChild(filesNode)
defer filesNode.button.Click(gxui.MouseEvent{})
for _, file := range files {
if file.IsDir() {
continue
}
fileNode := t.parseFile(dir, file)
fileNode.filepath = filepath.Join(dir, file.Name())
filesNode.AddChild(fileNode)
}
}
func (t *TOC) parseFile(dir string, file os.FileInfo) *Name {
if !strings.HasSuffix(file.Name(), ".go") {
return newName(t.cmdr, t.driver, t.theme, file.Name(), nonGoColor)
}
path := filepath.Join(dir, file.Name())
f, err := parser.ParseFile(t.fileSet, path, nil, parser.ParseComments)
if err != nil {
return newName(t.cmdr, t.driver, t.theme, file.Name(), errColor)
}
t.parseAstFile(path, f)
return newName(t.cmdr, t.driver, t.theme, file.Name(), nameColor)
}
func (t *TOC) parseAstFile(filepath string, file *ast.File) *packageNode {
buildTags := findBuildTags(filepath, file)
buildTagLine := strings.Join(buildTags, " ")
packageName := file.Name.String()
pkgNode, ok := t.packageMap[packageName]<|fim▁hole|> if !ok {
pkgNode = newPackageNode(t.cmdr, t.driver, t.theme, packageName)
t.packageMap[pkgNode.button.Text()] = pkgNode
t.AddChild(pkgNode)
}
for _, decl := range file.Decls {
switch src := decl.(type) {
case *ast.GenDecl:
t.parseGenDecl(pkgNode, src, filepath, buildTagLine)
case *ast.FuncDecl:
if src.Name.String() == "init" {
// There can be multiple inits in the package, so this
// doesn't really help us in the TOC.
continue
}
text := src.Name.String()
if buildTagLine != "" {
text = fmt.Sprintf("%s (%s)", text, buildTagLine)
}
name := newName(t.cmdr, t.driver, t.theme, text, nameColor)
name.filepath = filepath
name.position = t.fileSet.Position(src.Pos())
if src.Recv == nil {
pkgNode.addFuncs(name)
continue
}
recvTyp := src.Recv.List[0].Type
if starExpr, ok := recvTyp.(*ast.StarExpr); ok {
recvTyp = starExpr.X
}
recvTypeName := recvTyp.(*ast.Ident).String()
pkgNode.addMethod(recvTypeName, name)
}
}
return pkgNode
}
func (t *TOC) parseGenDecl(pkgNode *packageNode, decl *ast.GenDecl, filepath, buildTags string) {
switch decl.Tok.String() {
case "const":
pkgNode.addConsts(t.valueNamesFrom(filepath, buildTags, decl.Specs)...)
case "var":
pkgNode.addVars(t.valueNamesFrom(filepath, buildTags, decl.Specs)...)
case "type":
// I have yet to see a case where a type declaration has len(Specs) != 0.
typeSpec := decl.Specs[0].(*ast.TypeSpec)
name := typeSpec.Name.String()
if buildTags != "" {
name = fmt.Sprintf("%s (%s)", name, buildTags)
}
typ := newName(t.cmdr, t.driver, t.theme, name, nameColor)
typ.filepath = filepath
typ.position = t.fileSet.Position(typeSpec.Pos())
pkgNode.addTypes(typ)
}
}
func (t *TOC) valueNamesFrom(filepath, buildTags string, specs []ast.Spec) (names []*Name) {
for _, spec := range specs {
valSpec, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
for _, name := range valSpec.Names {
if name.String() == "_" {
// _ can be redeclared multiple times, so providing access to
// it in the TOC isn't that useful.
continue
}
n := name.String()
if buildTags != "" {
n = fmt.Sprintf("%s (%s)", n, buildTags)
}
node := newName(t.cmdr, t.driver, t.theme, n, nameColor)
node.filepath = filepath
node.position = t.fileSet.Position(name.Pos())
names = append(names, node)
}
}
return names
}
func findBuildTags(filename string, file *ast.File) (tags []string) {
fileTag := parseFileTag(filename)
if fileTag != "" {
tags = append(tags, fileTag)
}
for _, commentBlock := range file.Comments {
if commentBlock.End() >= file.Package-1 {
// A build tag comment *must* have an empty line between it
// and the `package` declaration.
continue
}
for _, comment := range commentBlock.List {
newTags := parseTag(comment)
tags = applyTags(newTags, tags)
}
}
return tags
}
func applyTags(newTags, prevTags []string) (combinedTags []string) {
if len(prevTags) == 0 {
return newTags
}
if len(newTags) == 0 {
return prevTags
}
for _, newTag := range newTags {
for _, prevTag := range prevTags {
combinedTags = append(combinedTags, prevTag+","+newTag)
}
}
return
}
func parseFileTag(filename string) (fileTag string) {
filename = strings.TrimSuffix(filename, ".go")
filename = strings.TrimSuffix(filename, "_test")
var goarch, goos string
for _, arch := range goarches {
archSuffix := "_" + arch
if strings.HasSuffix(filename, archSuffix) {
goarch = arch
filename = strings.TrimSuffix(filename, archSuffix)
break
}
}
for _, os := range gooses {
osSuffix := "_" + os
if strings.HasSuffix(filename, osSuffix) {
goos = os
filename = strings.TrimSuffix(filename, osSuffix)
break
}
}
if goos != "" {
fileTag += goos
}
if goarch != "" {
if fileTag != "" {
fileTag += ","
}
fileTag += goarch
}
return fileTag
}
func parseTag(commentLine *ast.Comment) []string {
comment := commentLine.Text
if !strings.HasPrefix(comment, "// +build ") {
return nil
}
tags := strings.TrimPrefix(comment, "// +build ")
return strings.Split(tags, " ")
}<|fim▁end|> | |
<|file_name|>searx.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import unicodedata
from urlparse import urlparse
from threading import Thread
import httplib, sys
from Queue import Queue
import itertools
import codecs
import csv
import sys
import ssl
import re
if len(sys.argv) < 3:
print "Usage: %s <csv database> <out csv>" % (sys.argv[0])
exit()
# Unicode CSV reader
# http://stackoverflow.com/a/6187936
class UnicodeCsvReader(object):
def __init__(self, f, encoding="utf-8", **kwargs):
self.csv_reader = csv.reader(f, **kwargs)
self.encoding = encoding
def __iter__(self):
return self
def next(self):
# read and split the csv row into fields
row = self.csv_reader.next()
# now decode
return [unicode(cell, self.encoding) for cell in row]
@property
def line_num(self):
return self.csv_reader.line_num
class UnicodeDictReader(csv.DictReader):
def __init__(self, f, encoding="utf-8", fieldnames=None, **kwds):
csv.DictReader.__init__(self, f, fieldnames=fieldnames, **kwds)
self.reader = UnicodeCsvReader(f, encoding=encoding, **kwds)
# Remove particles and parenthesis in names
def cleanNames(names):
filtered_names = []
for word in names:
if len(word) and word[0].lower() != word[0]:
filtered_names.append(word)
return filtered_names
# Strips accents from a unicode string
def stripAccents(s):
return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')
# Generates all 2+ permutations of the given array
def allCombinations(tab):
out = []
for n in range(2, len(tab) + 1):
for comb in itertools.combinations(tab, n):
out.append(" ".join(comb))
return out
# Cycles through available urls and returns the next one in the list
def getNextBaseURL():
out = getNextBaseURL.urllist[getNextBaseURL.counter % len(getNextBaseURL.urllist)]
getNextBaseURL.counter += 1
return out
getNextBaseURL.counter = 0
getNextBaseURL.urllist = [l.strip() for l in open("urls.txt", "r")]
def fetchHandles(ourl, handles):
try:
url = urlparse(ourl)
conn = httplib.HTTPSConnection(url.netloc, context=ssl._create_unverified_context())
conn.request("GET", ourl)
res = conn.getresponse()
if res.status != 200:
print res.reason, ourl
return
for line in csv.reader((l for l in res.read().split("\n")[1:])):
if len(line) < 2:
continue
match = re.match('https?://twitter.com/(\w+)[^/]*$', line[1])
if match:
handle = match.group(1)
if handle not in handles:
handles.append(handle)
except Exception, e:
print "Error(%s): %s" % (ourl, e)
exit()
return<|fim▁hole|> names, region, party = q.get()
clean_names = cleanNames(stripAccents(names).split(" "))
handles = []
for comb in allCombinations(clean_names):
query = comb.replace(" ", "+") + "+" + region + "+" + party + "+site:twitter.com"
url = base + "/?format=csv&q=" + query
fetchHandles(url, handles)
with codecs.open(sys.argv[2], "a", "utf-8") as out:
out.write("%s, %s\n" % (names, handles))
print "%s, %s" % (names, handles)
q.task_done()
concurrent = 50
q = Queue(concurrent * 2)
for i in range(concurrent):
t = Thread(target=doQueries)
t.daemon = True
t.start()
try:
with open(sys.argv[1], 'rb') as csvfile:
first = True
for line in UnicodeCsvReader(csvfile):
if first:
first = False
continue
names = line[0]
region = stripAccents(line[3]).replace(" ", "+")
party = stripAccents(line[5]).replace(" ", "+")
if party == "C's" or party == u"C´s":
party = "Ciudadanos"
q.put((names, region, party))
q.join()
except KeyboardInterrupt:
sys.exit(1)<|fim▁end|> |
def doQueries():
base = getNextBaseURL()
while True: |
<|file_name|>game.rs<|end_file_name|><|fim▁begin|>use rand::{thread_rng, Rng};
use sdl2::render;
use sdl2::rect::Rect;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use basic2d::Vec2;
use snake::{Snake, Move};
// Game structure
pub struct Game {
pub snakes: Vec<Snake>,
fruit: Vec2<i32>,
width: u32,
height: u32,
grid_size: u32
}
impl Game {
/// Initialises the game
pub fn new(width: u32, height: u32, grid_size: u32) -> Game {
let mut game = Game {
snakes: vec![Snake::new_with_defaults(Vec2::new(5, 5))],
fruit: Vec2::new(0, 0),
width: width,
height: height,
grid_size: grid_size
};
game.fruit = game.rand_grid_point();
game
}
/// Draws the game
pub fn draw(&mut self, renderer: &mut render::Renderer) {
// Draw fruit
renderer.set_draw_color(Color::RGB(0xAA, 0x30, 0x30));
renderer.fill_rect(self.point_to_rect(self.fruit)).unwrap();
// Draw snakes
renderer.set_draw_color(Color::RGB(0x60, 0xAA, 0x60));
for snake in &self.snakes {
let head = snake.get_head();
renderer.fill_rect(self.point_to_rect(head)).unwrap();
let tail_components = snake.tail_to_points();
for &component in &tail_components {
renderer.fill_rect(self.point_to_rect(component)).unwrap();
}
}
}
fn point_to_rect(&self, point: Vec2<i32>) -> Rect {
Rect::new(
self.grid_size as i32 * point.x,
self.grid_size as i32 * point.y,
self.grid_size,
self.grid_size,
)
}
/// Updates the game using the time elapsed since the last update
pub fn update(&mut self, elapsed_time: f32) {
for i in 0..self.snakes.len() {
self.snakes[i].update(elapsed_time);
let collision = self.snakes[i].check_collision(self.width, self.height,
&self.snakes[i].tail_to_points());
if collision {
self.snakes[i].dead = true;
}
let head = self.snakes[i].get_head();
if head == self.fruit {
self.snakes[i].score += 10;
self.snakes[i].add_segment();
self.new_fruit();
}
}
}
pub fn key_down(&mut self, keycode: Keycode) {
match keycode {
Keycode::Up => self.snakes[0].set_move(Move::Up),
Keycode::Down => self.snakes[0].set_move(Move::Down),
Keycode::Left => self.snakes[0].set_move(Move::Left),
Keycode::Right => self.snakes[0].set_move(Move::Right),
_ => {},
}
}
// Generates a random point on the grid
fn rand_grid_point(&self) -> Vec2<i32> {
Vec2::new(
(thread_rng().gen::<u32>() % self.width) as i32,
(thread_rng().gen::<u32>() % self.height) as i32
)
}
<|fim▁hole|> // FIXME: snakes should return iterators that iterate through their
// components instead of allocating vectors.
let mut walls = vec![];
for snake in &self.snakes {
walls.extend(snake.tail_to_points());
walls.push(snake.get_head());
}
// Move until the fruit is not covered by the snake
while walls.iter().any(|&w| self.fruit == w) {
self.fruit = self.rand_grid_point();
}
}
}<|fim▁end|> | /// Randomizes the position of the fruit
pub fn new_fruit(&mut self) { |
<|file_name|>domcrypt_worker.js<|end_file_name|><|fim▁begin|>/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* the Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Justin Dolske <[email protected]> (original author)
* David Dahl <[email protected]>
* Sergio Ruiz <[email protected]> [1]
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* NOTES:
*
* The WeaveCrypto object in this file was originally pulled from hg.mozilla.org
*
* http://hg.mozilla.org/mozilla-central/ \
* raw-file/d0c40fc38702/services/crypto/modules/WeaveCrypto.js
*
* WeaveCrypto's API as it was released in Firefox 4 was reduced in scope due
* to Sync's move to J-Pake, hence the need for this more complete version.
*
* This version has the additional APIs 'sign' and 'verify' and has been
* edited for use in a ChromeWorker.
*
* [1] This version has been modified for direct public and private key import
* in DER format to support sign, verify, encrypt and decrypt in
* such case. Also DSA and ElGamal key generation has been added.
*
*/
var DEBUG = false;
const PUB_ALGO = {
RSA: 1,
RSA_E: 2,
RSA_S: 3,
ELGAMAL_E: 16,
DSA: 17,
ECDH: 18,
ECDSA: 19,
ELGAMAL: 20
}
function log(aMessage) {
if (!DEBUG){
return;
}
var _msg = "domcrypt_worker: " + " " + aMessage + "\n";
dump(_msg);
}
const GENERATE_KEYPAIR = "generateKeypair";
const GENERATE_RANDOM = "generateRandom";
const ENCRYPT = "encrypt";
const DECRYPT = "decrypt";
const SIGN = "sign";
const VERIFY = "verify";
const GENERATE_SYM_KEY = "generateSymKey";
const SYM_ENCRYPT = "symEncrypt";
const SYM_DECRYPT = "symDecrypt";
const WRAP_SYM_KEY = "wrapSymKey";
const VERIFY_PASSPHRASE = "verifyPassphrase";
const SHUTDOWN = "shutdown";
const INITIALIZE = "init";
onmessage = function(aEvent) {
var data = JSON.parse(aEvent.data);
switch(data.action) {
case INITIALIZE:
WeaveCrypto.initNSS(data.nssPath);
DEBUG = data.debug || false;
break;
case GENERATE_KEYPAIR:
result = WeaveCryptoWrapper.generateKeypair(data.keyType, data.keypairBits);
postMessage(JSON.stringify({ keypairData: result, action: "keypairGenerated" }));
break;
case GENERATE_RANDOM:
result = WeaveCryptoWrapper.generateRandom(data.aLength);
postMessage(JSON.stringify({ randomBytes: result, action: "randomGenerated" }));
break;
case ENCRYPT:
result = WeaveCryptoWrapper.encrypt(data.plainText, data.pubKey);
postMessage(JSON.stringify({ cipherMessage: result, action: "dataEncrypted" }));
break;
case DECRYPT:
result = WeaveCryptoWrapper.decrypt(data.aCipherMessage,
data.derSecKey);
postMessage(JSON.stringify({ plainText: result, action: "dataDecrypted" }));
break;
case SIGN:
result = WeaveCryptoWrapper.sign(data.hash,
data.derSecKey,
data.derPubKey);
postMessage(JSON.stringify({ signature: result, action: "messageSigned" }));
break;
case VERIFY:
result = WeaveCryptoWrapper.verify(data.hash,
data.signature,
data.pubKey);
postMessage(JSON.stringify({ verification: result, action: "messageVerified" }));
break;
case SHUTDOWN:
WeaveCrypto.shutdown();
default:
break;
}
}
/**
* WeaveCryptoWrapper
*
* Wrap the WeaveCrypto API in a more elegant way. This is very similar to the
* original DOMCrypt extension code
*
*/
var WeaveCryptoWrapper = {
/**
* generateKeypair
*
* Create a KeyPair for general purpose
*
* @param int Type of Key algorithm
* int Key length in bits
* @returns object
* The object returned looks like:
* { action: "keypairGenerated",
* privKey: <PRIVATE KEY>,
* created: <DATE CREATED>
* }
*/
generateKeypair: function WCW_generateKeypair(keyType, keypairBits)
{
var privOut = {};
try {
WeaveCrypto.generateKeypair(keyType, keypairBits, privOut);
let results = { action: "keypairGenerated",
privKey: privOut,
created: Date.now()
};
return results;
}
catch (ex) {
log(ex);
log(ex.stack);
throw(ex);
}
},
/**
* generateRandom
*
* Create a random bytes
*
* @param int Numbes of random bytes to create
* @returns object
* The object returned looks like:
* { action: "randomGenerated",
* randomBytes: <STRING OF RANDOM BYTES>
* }
*/
generateRandom: function WCW_generateRandom(nbytes)
{
try {
var randomBytes = WeaveCrypto.generateRandomBytes(nbytes);
let results = { action: "randomGenerated",
randomBytes: randomBytes
};
return results;
}
catch (ex) {
log(ex);
log(ex.stack);
throw(ex);
}
},
/**
* encrypt
*
* Encrypt data with a public key
*
* @param string aSessionkey
* The base64 session key data that will be encrypted
* @param string aPublicKey
* The recipient's DER base64 encoded public key
* @returns Object
* A 'message' object:
* { content: <ENCRYPTED_STRING>,
* pubKey: <RECIPIENT PUB_KEY>,
* wrappedKey: <WRAPPED SYM_KEY>,
* iv: <INITIALIZATION VECTOR>
* }
*/
encrypt: function WCW_encrypt(aSessionkey, aPublicKey)
{
if (!aSessionkey && !aPublicKey) {
throw new Error("Missing Arguments: aSessionkey and aPublicKey are required");
}
try {
var encryptedSessionkey = WeaveCrypto.encrypt(aSessionkey, aPublicKey);
return encryptedSessionkey;
}
catch (ex) {
log(ex);
log(ex.stack);
throw ex;
}
},
/**
* decrypt
*
* Decrypt encrypted data with a private key
*
* @param string aSessionkey
* The base64 encrypted session key
* @param string aPrivateKey
* The base64 encoded private key string
* @returns string
* The decrypted message in base64
*/
decrypt: function WCW_decrypt(aSessionkey, aPrivateKey)
{
try {
var decrypted = WeaveCrypto.decrypt(aSessionkey, aPrivateKey);
return decrypted;<|fim▁hole|> log(ex.stack);
throw(ex);
}
},
/**
* Cryptographically sign a message
*
* @param string aHash
* A base64 signature data hash of the message
* @param string aPrivateKey
* The sender's base64 DER encoded private key
* @param string aPublicKey
* The sender's base64 DER encoded public key
*/
sign: function WCW_sign(aHash, aPrivateKey, aPublicKey)
{
var signature;
try {
signature = WeaveCrypto.sign(aPrivateKey, aPublicKey, aHash);
return signature;
}
catch (ex) {
log(ex);
log(ex.stack);
throw ex;
}
},
/**
* Verify a signature was created by the sender
*
* @param string aData
* A base64 signature data
* @param string aSignature
* A base64 encoded signature string
* @param string aPublicKey
* The sender's base 64 DER encoded public key
* @returns boolean
*/
verify: function WCW_verify(aData, aSignature, aPublicKey)
{
try {
let results = WeaveCrypto.verify(aPublicKey, aSignature, aData);
if (results)
return true;
return false;
}
catch (ex) {
log(ex);
log(ex.stack);
throw ex;
}
},
};
/**
* The WeaveCrypto changes I have made are minimal:
* 1. Removed any calls into Cc/Ci/Cr, etc.
* 2. added WeaveCrypto.sign() (PK11_Sign)
* 3. added WeaveCrypto.verify() (PK11_Verify)
*
* WeaveCrypto (js-ctypes iteration) was coded and reviewed in this bug:
* https://bugzilla.mozilla.org/show_bug.cgi?id=513798
*
*/
// http://mxr.mozilla.org/mozilla-central/source/security/nss/lib/util/secoidt.h#318
// recommended EC algs: http://www.nsa.gov/business/programs/elliptic_curve.shtml
// http://mxr.mozilla.org/mozilla-central/source/security/nss/lib/util/secoidt.h#346
var WeaveCrypto = {
debugEnabled : false,
nss : null,
nss_t : null,
log : function (message) {
if (!this.debugEnabled)
return;
dump("WeaveCrypto: " + message + "\n");
},
shutdown : function WC_shutdown() {
this.log("closing nsslib");
this.nsslib.close();
},
fullPathToLib: null,
initNSS : function WC_initNSS(aNSSPath, debugEnabled) {
// Open the NSS library.
this.fullPathToLib = aNSSPath;
this.debugEnabled = debugEnabled || false;
// XXX really want to be able to pass specific dlopen flags here.
var nsslib = ctypes.open(this.fullPathToLib);
this.nsslib = nsslib;
this.log("Initializing NSS types and function declarations...");
this.nss = {};
this.nss_t = {};
// nsprpub/pr/include/prtypes.h#435
// typedef PRIntn PRBool; --> int
this.nss_t.PRBool = ctypes.int;
// security/nss/lib/util/seccomon.h#91
// typedef enum
this.nss_t.SECStatus = ctypes.int;
// security/nss/lib/softoken/secmodt.h#59
// typedef struct PK11SlotInfoStr PK11SlotInfo; (defined in secmodti.h)
this.nss_t.PK11SlotInfo = ctypes.void_t;
// security/nss/lib/util/pkcs11t.h
this.nss_t.CK_MECHANISM_TYPE = ctypes.unsigned_long;
this.nss_t.CK_ATTRIBUTE_TYPE = ctypes.unsigned_long;
this.nss_t.CK_KEY_TYPE = ctypes.unsigned_long;
this.nss_t.CK_OBJECT_HANDLE = ctypes.unsigned_long;
// security/nss/lib/util/seccomon.h#64
// typedef enum
this.nss_t.SECItemType = ctypes.int;
// SECItemType enum values...
this.nss.SIBUFFER = 0;
// Needed for SECKEYPrivateKey struct def'n, but I don't think we need to actually access it.
this.nss_t.PLArenaPool = ctypes.void_t;
// security/nss/lib/cryptohi/keythi.h#45
// typedef enum
this.nss_t.KeyType = ctypes.int;
// security/nss/lib/softoken/secmodt.h#201
// typedef PRUint32 PK11AttrFlags;
this.nss_t.PK11AttrFlags = ctypes.unsigned_int;
// security/nss/lib/util/seccomon.h#83
// typedef struct SECItemStr SECItem; --> SECItemStr defined right below it
this.nss_t.SECItem = ctypes.StructType(
"SECItem", [{ type: this.nss_t.SECItemType },
{ data: ctypes.unsigned_char.ptr },
{ len : ctypes.int }]);
// security/nss/lib/softoken/secmodt.h#65
// typedef struct PK11RSAGenParamsStr --> def'n on line 139
this.nss_t.PK11RSAGenParams = ctypes.StructType(
"PK11RSAGenParams", [{ keySizeInBits: ctypes.int },
{ pe : ctypes.unsigned_long }]);
// security/nss/lib/softoken/secmodt.h#65
// typedef struct PK11RSAGenParamsStr --> def'n on line 132
// struct SECKEYDHParamsStr {
// PLArenaPool * arena;
// SECItem prime; /* p */
// SECItem base; /* g */
// };
this.nss_t.SECKEYDHParams = ctypes.StructType(
"SECKEYDHParams", [{ arena: this.nss_t.PLArenaPool.ptr },
{ prime: this.nss_t.SECItem },
{ base: this.nss_t.SECItem },]);
// security/nss/lib/cryptohi/keythi.h#233
// typedef struct SECKEYPrivateKeyStr SECKEYPrivateKey; --> def'n right above it
this.nss_t.SECKEYPrivateKey = ctypes.StructType(
"SECKEYPrivateKey", [{ arena: this.nss_t.PLArenaPool.ptr },
{ keyType: this.nss_t.KeyType },
{ pkcs11Slot: this.nss_t.PK11SlotInfo.ptr },
{ pkcs11ID: this.nss_t.CK_OBJECT_HANDLE },
{ pkcs11IsTemp: this.nss_t.PRBool },
{ wincx: ctypes.voidptr_t },
{ staticflags: ctypes.unsigned_int }]);
// security/nss/lib/cryptohi/keythi.h#78
// typedef struct SECKEYRSAPublicKeyStr --> def'n right above it
this.nss_t.SECKEYRSAPublicKey = ctypes.StructType(
"SECKEYRSAPublicKey", [{ arena: this.nss_t.PLArenaPool.ptr },
{ modulus: this.nss_t.SECItem },
{ publicExponent: this.nss_t.SECItem }]);
// security/nss/lib/cryptohi/keythi.h#189
// typedef struct SECKEYPublicKeyStr SECKEYPublicKey; --> def'n right above it
this.nss_t.SECKEYPublicKey = ctypes.StructType(
"SECKEYPublicKey", [{ arena: this.nss_t.PLArenaPool.ptr },
{ keyType: this.nss_t.KeyType },
{ pkcs11Slot: this.nss_t.PK11SlotInfo.ptr },
{ pkcs11ID: this.nss_t.CK_OBJECT_HANDLE },
{ rsa: this.nss_t.SECKEYRSAPublicKey } ]);
// security/nss/lib/util/secoidt.h#52
// typedef struct SECAlgorithmIDStr --> def'n right below it
this.nss_t.SECAlgorithmID = ctypes.StructType(
"SECAlgorithmID", [{ algorithm: this.nss_t.SECItem },
{ parameters: this.nss_t.SECItem }]);
// security/nss/lib/certdb/certt.h#98
// typedef struct CERTSubjectPublicKeyInfoStrA --> def'n on line 160
this.nss_t.CERTSubjectPublicKeyInfo = ctypes.StructType(
"CERTSubjectPublicKeyInfo", [{ arena: this.nss_t.PLArenaPool.ptr },
{ algorithm: this.nss_t.SECAlgorithmID },
{ subjectPublicKey: this.nss_t.SECItem }]);
this.nss_t.PQGParams = ctypes.StructType(
"PQGParams", [{ arena: this.nss_t.PLArenaPool.ptr },
{ prime: this.nss_t.SECItem },
{ subPrime: this.nss_t.SECItem },
{ base: this.nss_t.SECItem },]);
this.nss_t.PQGVerify = ctypes.StructType(
"PQGVerify", [{ arena: this.nss_t.PLArenaPool.ptr },
{ counter: ctypes.unsigned_int},
{ seed: this.nss_t.SECItem },
{ h: this.nss_t.SECItem }]);
/* XXX chrisk: this needs to be expanded to hold j and validationParms (RFC2459 7.3.2) */
// security/nss/lib/util/pkcs11t.h
this.nss.CKM_RSA_PKCS_KEY_PAIR_GEN = 0x0000;
this.nss.CKM_DH_PKCS_KEY_PAIR_GEN = 0x0020;
this.nss.CKM_DSA_KEY_PAIR_GEN = 0x0010;
// security/nss/lib/softoken/secmodt.h
this.nss.PK11_ATTR_SESSION = 0x02;
this.nss.PK11_ATTR_PUBLIC = 0x08;
this.nss.PK11_ATTR_SENSITIVE = 0x40;
this.nss.PK11_ATTR_INSENSITIVE = 0x80;
// security/nss/lib/pk11wrap/pk11pub.h#286
// SECStatus PK11_GenerateRandom(unsigned char *data,int len);
this.nss.PK11_GenerateRandom = nsslib.declare("PK11_GenerateRandom",
ctypes.default_abi, this.nss_t.SECStatus,
ctypes.unsigned_char.ptr, ctypes.int);
// security/nss/lib/pk11wrap/pk11pub.h#74
// PK11SlotInfo *PK11_GetInternalSlot(void);
this.nss.PK11_GetInternalSlot = nsslib.declare("PK11_GetInternalSlot",
ctypes.default_abi, this.nss_t.PK11SlotInfo.ptr);
// security/nss/lib/pk11wrap/pk11pub.h#73
// PK11SlotInfo *PK11_GetInternalKeySlot(void);
this.nss.PK11_GetInternalKeySlot = nsslib.declare("PK11_GetInternalKeySlot",
ctypes.default_abi, this.nss_t.PK11SlotInfo.ptr);
this.nss.PK11_PrivDecryptPKCS1 = nsslib.declare("PK11_PrivDecryptPKCS1",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECKEYPrivateKey.ptr,
ctypes.unsigned_char.ptr, ctypes.unsigned_int.ptr,
ctypes.unsigned_int, ctypes.unsigned_char.ptr,
ctypes.unsigned_int);
/* The encrypt function that complements the above decrypt function. */
this.nss.PK11_PubEncryptPKCS1 = nsslib.declare(
"PK11_PubEncryptPKCS1",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECKEYPublicKey.ptr,
ctypes.unsigned_char.ptr, ctypes.unsigned_char.ptr,
ctypes.unsigned_int, ctypes.voidptr_t
);
/* Generate PQGParams and PQGVerify structs.
* Length of seed and length of h both equal length of P.
* All lengths are specified by "j", according to the table above.
*/
this.nss.PK11_PQG_ParamGen = nsslib.declare(
"PK11_PQG_ParamGen",
ctypes.default_abi, this.nss_t.SECStatus,
ctypes.unsigned_int,
this.nss_t.PQGParams.ptr.ptr,
this.nss_t.PQGVerify.ptr.ptr
);
// extern SECStatus PK11_PQG_GetPrimeFromParams(const PQGParams *params,
// SECItem * prime);
this.nss.PK11_PQG_GetPrimeFromParams = nsslib.declare(
"PK11_PQG_GetPrimeFromParams",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.PQGParams.ptr,
this.nss_t.SECItem.ptr
);
this.nss.PK11_PubDecryptRaw = nsslib.declare(
"PK11_PubDecryptRaw",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECKEYPrivateKey.ptr,
ctypes.unsigned_char.ptr, ctypes.unsigned_int.ptr,
ctypes.unsigned_int, ctypes.unsigned_char.ptr,
ctypes.unsigned_int
);
this.nss.PK11_ImportDERPrivateKeyInfoAndReturnKey = nsslib.declare("PK11_ImportDERPrivateKeyInfoAndReturnKey",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.PK11SlotInfo.ptr, this.nss_t.SECItem.ptr,
this.nss_t.SECItem.ptr, this.nss_t.SECItem.ptr,
this.nss_t.PRBool, this.nss_t.PRBool, ctypes.int,
this.nss_t.SECKEYPrivateKey.ptr.ptr
);
// SIGNING API //////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// security/nss/pk11wrap/pk11pub.h#682
// int PK11_SignatureLength(SECKEYPrivateKey *key);
this.nss.PK11_SignatureLen = nsslib.declare("PK11_SignatureLen",
ctypes.default_abi,
ctypes.int,
this.nss_t.SECKEYPrivateKey.ptr);
// security/nss/pk11wrap/pk11pub.h#684
// SECStatus PK11_Sign(SECKEYPrivateKey *key, SECItem *sig, SECItem *hash);
this.nss.PK11_Sign = nsslib.declare("PK11_Sign",
ctypes.default_abi,
this.nss_t.SECStatus,
this.nss_t.SECKEYPrivateKey.ptr,
this.nss_t.SECItem.ptr,
this.nss_t.SECItem.ptr);
// security/nss/pk11wrap/pk11pub.h#687
// SECStatus PK11_Verify(SECKEYPublicKey *key, SECItem *sig, SECItem *hash, void *wincx);
this.nss.PK11_Verify = nsslib.declare("PK11_Verify",
ctypes.default_abi,
this.nss_t.SECStatus,
this.nss_t.SECKEYPublicKey.ptr,
this.nss_t.SECItem.ptr,
this.nss_t.SECItem.ptr,
ctypes.voidptr_t);
// END SIGNING API
//////////////////////////////////////////////////////////////////////////
// security/nss/lib/pk11wrap/pk11pub.h#507
// SECKEYPrivateKey *PK11_GenerateKeyPairWithFlags(PK11SlotInfo *slot,
// CK_MECHANISM_TYPE type, void *param, SECKEYPublicKey **pubk,
// PK11AttrFlags attrFlags, void *wincx);
this.nss.PK11_GenerateKeyPairWithFlags = nsslib.declare("PK11_GenerateKeyPairWithFlags",
ctypes.default_abi, this.nss_t.SECKEYPrivateKey.ptr,
this.nss_t.PK11SlotInfo.ptr, this.nss_t.CK_MECHANISM_TYPE, ctypes.voidptr_t,
this.nss_t.SECKEYPublicKey.ptr.ptr, this.nss_t.PK11AttrFlags, ctypes.voidptr_t);
// security/nss/lib/pk11wrap/pk11pub.h#466
// SECStatus PK11_SetPrivateKeyNickname(SECKEYPrivateKey *privKey, const char *nickname);
this.nss.PK11_SetPrivateKeyNickname = nsslib.declare("PK11_SetPrivateKeyNickname",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECKEYPrivateKey.ptr, ctypes.char.ptr);
// security/nss/lib/cryptohi/keyhi.h#159
// SECItem* SECKEY_EncodeDERSubjectPublicKeyInfo(SECKEYPublicKey *pubk);
this.nss.SECKEY_EncodeDERSubjectPublicKeyInfo = nsslib.declare("SECKEY_EncodeDERSubjectPublicKeyInfo",
ctypes.default_abi, this.nss_t.SECItem.ptr,
this.nss_t.SECKEYPublicKey.ptr);
// security/nss/lib/cryptohi/keyhi.h#165
// CERTSubjectPublicKeyInfo * SECKEY_DecodeDERSubjectPublicKeyInfo(SECItem *spkider);
this.nss.SECKEY_DecodeDERSubjectPublicKeyInfo = nsslib.declare("SECKEY_DecodeDERSubjectPublicKeyInfo",
ctypes.default_abi, this.nss_t.CERTSubjectPublicKeyInfo.ptr,
this.nss_t.SECItem.ptr);
// security/nss/lib/cryptohi/keyhi.h#179
// SECKEYPublicKey * SECKEY_ExtractPublicKey(CERTSubjectPublicKeyInfo *);
this.nss.SECKEY_ExtractPublicKey = nsslib.declare("SECKEY_ExtractPublicKey",
ctypes.default_abi, this.nss_t.SECKEYPublicKey.ptr,
this.nss_t.CERTSubjectPublicKeyInfo.ptr);
// security/nss/lib/pk11wrap/pk11pub.h#70
// void PK11_FreeSlot(PK11SlotInfo *slot);
this.nss.PK11_FreeSlot = nsslib.declare("PK11_FreeSlot",
ctypes.default_abi, ctypes.void_t,
this.nss_t.PK11SlotInfo.ptr);
// security/nss/lib/cryptohi/keyhi.h#193
// extern void SECKEY_DestroyPublicKey(SECKEYPublicKey *key);
this.nss.SECKEY_DestroyPublicKey = nsslib.declare("SECKEY_DestroyPublicKey",
ctypes.default_abi, ctypes.void_t,
this.nss_t.SECKEYPublicKey.ptr);
// security/nss/lib/cryptohi/keyhi.h#186
// extern void SECKEY_DestroyPrivateKey(SECKEYPrivateKey *key);
this.nss.SECKEY_DestroyPrivateKey = nsslib.declare("SECKEY_DestroyPrivateKey",
ctypes.default_abi, ctypes.void_t,
this.nss_t.SECKEYPrivateKey.ptr);
/*
* Creates a PublicKey from its DER encoding.
* Currently only supports RSA and DSA keys.
*/
this.nss.SECKEY_PublicKeyStrengthInBits = nsslib.declare("SECKEY_PublicKeyStrengthInBits",
ctypes.default_abi, ctypes.unsigned_int,
this.nss_t.SECKEYPublicKey.ptr);
// security/nss/lib/cryptohi/keyhi.h#58
// extern void SECKEY_DestroySubjectPublicKeyInfo(CERTSubjectPublicKeyInfo *spki);
this.nss.SECKEY_DestroySubjectPublicKeyInfo = nsslib.declare("SECKEY_DestroySubjectPublicKeyInfo",
ctypes.default_abi, ctypes.void_t,
this.nss_t.CERTSubjectPublicKeyInfo.ptr);
// SECStatus PK11_ReadRawAttribute(PK11ObjectType type, void *object,
// CK_ATTRIBUTE_TYPE attr, SECItem *item);
this.nss.PK11_ReadRawAttribute = nsslib.declare("PK11_ReadRawAttribute",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECStatus, ctypes.voidptr_t,
this.nss_t.PK11AttrFlags, this.nss_t.SECItem.ptr);
},
sign : function _sign(aDerPrivKey, aDerPubKey, aHash) {
this.log("sign() called");
let privKey, slot, hash, sig;
slot = this.nss.PK11_GetInternalSlot();
if (slot.isNull())
throw new Error("couldn't get internal slot");
let derPrivKey = this.makeSECItem(aDerPrivKey, true);
let derPubKey = this.makeSECItem(aDerPubKey, true);
privKey = new this.nss_t.SECKEYPrivateKey.ptr();
hash = this.makeSECItem(aHash, true);
sig = this.makeSECItem("", false);
var rv = this.nss.PK11_ImportDERPrivateKeyInfoAndReturnKey(slot,
derPrivKey.address(), null, derPubKey.address(), false,
true, (0x7fffffff >>> 0), privKey.address());
if (privKey.isNull())
throw new Error("sign error: Could not import DER private key");
let sigLen = this.nss.PK11_SignatureLen(privKey);
sig.len = sigLen;
sig.data = new ctypes.ArrayType(ctypes.unsigned_char, sigLen)();
let status = this.nss.PK11_Sign(privKey, sig.address(), hash.address());
if (status == -1)
throw new Error("Could not sign message");
return this.encodeBase64(sig.data, sig.len);
},
verify : function _verify(aDerPubKey, aSignature, aHash) {
this.log("verify() called");
let derPubKey = this.makeSECItem(aDerPubKey, true);
let pubKeyInfo = this.nss.SECKEY_DecodeDERSubjectPublicKeyInfo(derPubKey.address());
if (pubKeyInfo.isNull())
throw new Error("SECKEY_DecodeDERSubjectPublicKeyInfo failed");
let pubKey = this.nss.SECKEY_ExtractPublicKey(pubKeyInfo);
if (pubKey.isNull())
throw new Error("SECKEY_ExtractPublicKey failed");
let sig = this.makeSECItem(aSignature, false);
let hash = this.makeSECItem(aHash, false);
let status =
this.nss.PK11_Verify(pubKey, sig.address(), hash.address(), null);
this.log("verify return " + status);
if (status == -1) {
return false;
}
return true;
},
generateKeypair : function(keyType, keypairBits, out_fields) {
this.log("generateKeypair() called. keytype("+ keyType + ") keybits("+ keypairBits + ")");
let pubKey, privKey, slot;
try {
// Attributes for the private key. We're just going to wrap and extract the
// value, so they're not critical. The _PUBLIC attribute just indicates the
// object can be accessed without being logged into the token.
let params, genType, rc;
switch(keyType) {
case PUB_ALGO.RSA:
let rsaParams = new this.nss_t.PK11RSAGenParams();
rsaParams.keySizeInBits = keypairBits; // 1024, 2048, etc.
rsaParams.pe = 65537; // public exponent.
params = rsaParams.address();
genType = this.nss.CKM_RSA_PKCS_KEY_PAIR_GEN;
break;
case PUB_ALGO.DSA:
var pqgparams = new this.nss_t.PQGParams.ptr();
var pqgverify = new this.nss_t.PQGVerify.ptr();
rc = this.nss.PK11_PQG_ParamGen(8, pqgparams.address(), pqgverify.address());
params = pqgparams;
genType = this.nss.CKM_DSA_KEY_PAIR_GEN;
break;
case PUB_ALGO.ELGAMAL_E:
var dhParams = new this.nss_t.SECKEYDHParams();
var pqgparams = new this.nss_t.PQGParams.ptr();
var pqgverify = new this.nss_t.PQGVerify.ptr();
rc = this.nss.PK11_PQG_ParamGen(8, pqgparams.address(), pqgverify.address());
var prime = this.makeSECItem("", false);
rc = this.nss.PK11_PQG_GetPrimeFromParams(pqgparams, prime.address());
dhParams.base = this.makeSECItem(String.fromCharCode(5), false);
dhParams.prime = prime;
params = dhParams.address();
genType = this.nss.CKM_DH_PKCS_KEY_PAIR_GEN;
break;
default:
throw new Error("Unkown key type algo: " + keyType);
}
slot = this.nss.PK11_GetInternalSlot();
if (slot.isNull())
throw new Error("couldn't get internal slot");
let attrFlags = (this.nss.PK11_ATTR_SESSION | this.nss.PK11_ATTR_PUBLIC | this.nss.PK11_ATTR_INSENSITIVE);
pubKey = new this.nss_t.SECKEYPublicKey.ptr();
// Generate the keypair.
privKey = this.nss.PK11_GenerateKeyPairWithFlags(slot,
genType,
params,
pubKey.address(),
attrFlags, null);
if (privKey.isNull())
throw new Error("keypair generation failed");
let s = this.nss.PK11_SetPrivateKeyNickname(privKey, "Weave User PrivKey");
if (s)
throw new Error("key nickname failed");
try {
// Use a buffer to hold the wrapped key. NSS says about 1200 bytes for
// a 2048-bit RSA key, so a 4096 byte buffer should be plenty.
var CKA_MODULUS = 0x00000120;
var CKA_MODULUS_BITS = 0x00000121;
var CKA_PUBLIC_EXPONENT = 0x00000122;
var CKA_PRIVATE_EXPONENT = 0x00000123;
var CKA_PRIME_1 = 0x00000124;
var CKA_PRIME_2 = 0x00000125;
var CKA_EXPONENT_1 = 0x00000126;
var CKA_EXPONENT_2 = 0x00000127;
var CKA_COEFFICIENT = 0x00000128;
var CKA_PRIME = 0x00000130;
var CKA_SUBPRIME = 0x00000131;
var CKA_BASE = 0x00000132;
var CKA_VALUE = 0x00000011;
var CKA_DERIVE = 0x0000010C;
var CKA_NETSCAPE_DB = 0xD5A0DB00;
function getAttribute(self, privKey, attrtype) {
// Use a buffer to hold the wrapped key. NSS says about 1200 bytes for
// a 2048-bit RSA key, so a 4096 byte buffer should be plenty.
let keyData = new ctypes.ArrayType(ctypes.unsigned_char, 4096)();
let outData = new self.nss_t.SECItem(self.nss.SIBUFFER, keyData, keyData.length);
let rc = self.nss.PK11_ReadRawAttribute(1, privKey, attrtype, outData.address());
let intData = ctypes.cast(outData.data, ctypes.uint8_t.array(outData.len).ptr).contents;
let expanded ="";
for (let i = 0; i < outData.len; i++)
expanded += String.fromCharCode(intData[i]);
return btoa(expanded);
}
switch(keyType) {
case PUB_ALGO.RSA:
out_fields.n = getAttribute(this, privKey, CKA_MODULUS);
out_fields.e = getAttribute(this, privKey, CKA_PUBLIC_EXPONENT);
out_fields.d = getAttribute(this, privKey, CKA_PRIVATE_EXPONENT);
out_fields.q = getAttribute(this, privKey, CKA_PRIME_1)
out_fields.p = getAttribute(this, privKey, CKA_PRIME_2)
out_fields.u = getAttribute(this, privKey, CKA_COEFFICIENT)
break;
case PUB_ALGO.ELGAMAL_E: //D-H
out_fields.p = getAttribute(this, privKey, CKA_PRIME);
out_fields.x = getAttribute(this, privKey, CKA_VALUE);
out_fields.g = getAttribute(this, privKey, CKA_BASE);
out_fields.y = getAttribute(this, privKey, CKA_NETSCAPE_DB);
break;
case PUB_ALGO.DSA:
out_fields.p = getAttribute(this, privKey, CKA_PRIME);
out_fields.q = getAttribute(this, privKey, CKA_SUBPRIME);
out_fields.g = getAttribute(this, privKey, CKA_BASE);
out_fields.x = getAttribute(this, privKey, CKA_VALUE);
out_fields.y = getAttribute(this, privKey, CKA_NETSCAPE_DB);
break;
default:
throw new Error("Unkown key type algo: " + keyType);
break;
}
} catch (e) {
this.log("generateKeypair: failed: " + e + e.lineNumber);
throw e;
} finally {
if (pubKey && !pubKey.isNull())
this.nss.SECKEY_DestroyPublicKey(pubKey);
if (privKey && !privKey.isNull())
this.nss.SECKEY_DestroyPrivateKey(privKey);
if (slot && !slot.isNull())
this.nss.PK11_FreeSlot(slot);
}
} catch (e) {
dump(e);
}
},
generateRandomBytes : function(byteCount) {
this.log("generateRandomBytes() called");
// Temporary buffer to hold the generated data.
let scratch = new ctypes.ArrayType(ctypes.unsigned_char, byteCount)();
if (this.nss.PK11_GenerateRandom(scratch, byteCount))
throw new Error("PK11_GenrateRandom failed");
return this.encodeBase64(scratch.address(), scratch.length);
},
encrypt : function(aHash, aDerPubKey) {
this.log("encrypt() called");
// Step 1. Get rid of the base64 encoding on the inputs.
let derPubKey = this.makeSECItem(aDerPubKey, true);
let hash = atob(aHash);
let slot, pubKeyInfo, pubKey;
try {
slot = this.nss.PK11_GetInternalSlot();
if (slot.isNull())
throw new Error("couldn't get internal slot");
pubKeyInfo = this.nss.SECKEY_DecodeDERSubjectPublicKeyInfo(derPubKey.address());
if (pubKeyInfo.isNull())
throw new Error("SECKEY_DecodeDERSubjectPublicKeyInfo failed");
pubKey = this.nss.SECKEY_ExtractPublicKey(pubKeyInfo);
if (pubKey.isNull())
throw new Error("SECKEY_ExtractPublicKey failed");
let byteLen = this.nss.SECKEY_PublicKeyStrengthInBits(pubKey) / 8;
let inputData = new ctypes.ArrayType(ctypes.unsigned_char, hash.length)();
this.byteCompress(hash, inputData);
let outputData = new ctypes.ArrayType(ctypes.unsigned_char, byteLen)();
let s = this.nss.PK11_PubEncryptPKCS1(pubKey, outputData, inputData, hash.length, null);
if (s)
throw new Error("PK11_PubEncryptPKCS1 failed");
return this.encodeBase64(outputData.address(), outputData.length);
} catch (e) {
this.log("encrypt: failed: " + e);
throw e;
} finally {
if (pubKey && !pubKey.isNull())
this.nss.SECKEY_DestroyPublicKey(pubKey);
if (pubKeyInfo && !pubKeyInfo.isNull())
this.nss.SECKEY_DestroySubjectPublicKeyInfo(pubKeyInfo);
if (slot && !slot.isNull())
this.nss.PK11_FreeSlot(slot);
}
},
decrypt : function(aHash, aDerPrivKey) {
this.log("decrypt() called");
// Step 1. Get rid of the base64 encoding on the inputs.
let derPrivKey = this.makeSECItem(aDerPrivKey, true);
let slot, privKey;
try {
slot = this.nss.PK11_GetInternalSlot();
if (slot.isNull())
throw new Error("couldn't get internal slot");
let privKey = new this.nss_t.SECKEYPrivateKey.ptr();
var rv = this.nss.PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, derPrivKey.address(),
null, null, false, true,
(0x7fffffff >>> 0), privKey.address());
if (privKey.isNull())
throw new Error("Import DER private key failed");
let input = atob(aHash);
let byteLen = input.length;
let inputData = new ctypes.ArrayType(ctypes.unsigned_char, byteLen)(); this.byteCompress(input, inputData);
let outputData = new ctypes.ArrayType(ctypes.unsigned_char, byteLen)();
let outputLen = new ctypes.unsigned;
rv = this.nss.PK11_PrivDecryptPKCS1(privKey, outputData,
outputLen.address(), byteLen,
inputData, byteLen);
return this.encodeBase64(outputData.address(), outputData.length);
} catch (e) {
this.log("decrypt: failed: " + e);
throw e;
} finally {
if (privKey && !privKey.isNull())
this.nss.SECKEY_DestroyPrivateKey(privKey);
if (slot && !slot.isNull())
this.nss.PK11_FreeSlot(slot);
}
},
//
// Utility functions
//
// Compress a JS string (2-byte chars) into a normal C string (1-byte chars)
// EG, for "ABC", 0x0041, 0x0042, 0x0043 --> 0x41, 0x42, 0x43
byteCompress : function (jsString, charArray) {
let intArray = ctypes.cast(charArray, ctypes.uint8_t.array(charArray.length));
for (let i = 0; i < jsString.length; i++) {
intArray[i] = jsString.charCodeAt(i) % 256; // convert to bytes
}
},
// Expand a normal C string (1-byte chars) into a JS string (2-byte chars)
// EG, for "ABC", 0x41, 0x42, 0x43 --> 0x0041, 0x0042, 0x0043
byteExpand : function (charArray) {
let expanded = "";
let len = charArray.length;
let intData = ctypes.cast(charArray, ctypes.uint8_t.array(len));
for (let i = 0; i < len; i++)
expanded += String.fromCharCode(intData[i]);
return expanded;
},
encodeBase64 : function (data, len) {
// Byte-expand the buffer, so we can treat it as a UCS-2 string
// consisting of u0000 - u00FF.
let expanded = "";
let intData = ctypes.cast(data, ctypes.uint8_t.array(len).ptr).contents;
for (let i = 0; i < len; i++)
expanded += String.fromCharCode(intData[i]);
return btoa(expanded);
},
makeSECItem : function(input, isEncoded) {
if (isEncoded)
input = atob(input);
let outputData = new ctypes.ArrayType(ctypes.unsigned_char, input.length)();
this.byteCompress(input, outputData);
return new this.nss_t.SECItem(this.nss.SIBUFFER, outputData, outputData.length);
},
};<|fim▁end|> | }
catch (ex) {
log(ex); |
<|file_name|>BookCaseViewService.java<|end_file_name|><|fim▁begin|>/**
* (c) raptor_MVK, 2015. All rights reserved.
*/
package ru.mvk.biblioGuide.service;
import org.jetbrains.annotations.NotNull;
import ru.mvk.biblioGuide.dao.BookCaseDao;
import ru.mvk.biblioGuide.model.BookCase;
import ru.mvk.iluvatar.descriptor.ListViewInfo;
import ru.mvk.iluvatar.descriptor.ListViewInfoImpl;
import ru.mvk.iluvatar.descriptor.ViewInfo;
import ru.mvk.iluvatar.descriptor.ViewInfoImpl;
import ru.mvk.iluvatar.descriptor.column.NumColumnInfo;
import ru.mvk.iluvatar.descriptor.column.StringColumnInfo;
import ru.mvk.iluvatar.descriptor.field.NaturalFieldInfo;
import ru.mvk.iluvatar.descriptor.field.TextFieldInfo;
import ru.mvk.iluvatar.module.db.HibernateAdapter;
import ru.mvk.iluvatar.service.ViewServiceDescriptor;
import ru.mvk.iluvatar.service.ViewServiceImpl;
import ru.mvk.iluvatar.view.Layout;
public class BookCaseViewService extends ViewServiceImpl<BookCase> {
public BookCaseViewService(@NotNull HibernateAdapter hibernateAdapter,
@NotNull Layout layout) {
super(new ViewServiceDescriptor<>(new BookCaseDao(hibernateAdapter),
prepareBookCaseViewInfo(), prepareAuthorListViewInfo()), layout, "Шкафы");<|fim▁hole|> @NotNull
private static ViewInfo<BookCase> prepareBookCaseViewInfo() {
@NotNull ViewInfo<BookCase> viewInfo = new ViewInfoImpl<>(BookCase.class);
viewInfo.addFieldInfo("name", new TextFieldInfo("Название", 20));
viewInfo.addFieldInfo("shelfCount", new NaturalFieldInfo<>(Byte.class,
"Кол-во полок", 2));
return viewInfo;
}
@NotNull
private static ListViewInfo<BookCase> prepareAuthorListViewInfo() {
@NotNull ListViewInfo<BookCase> listViewInfo = new ListViewInfoImpl<>(BookCase.class);
listViewInfo.addColumnInfo("lowerName", new StringColumnInfo("Название", 20));
listViewInfo.addColumnInfo("lowerInitials", new NumColumnInfo("Полок", 5));
return listViewInfo;
}
}<|fim▁end|> | }
|
<|file_name|>mochaTest.js<|end_file_name|><|fim▁begin|>module.exports = {
test: {
src: [
'test/vendor/assert.js',
'test/test-adapter.js',
'transpiled/tests.cjs.js'
],<|fim▁hole|> reporter: 'spec'
}
}
};<|fim▁end|> | options: { |
<|file_name|>etcd.go<|end_file_name|><|fim▁begin|>// Copyright 2018 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package etcd
import (
"context"
"crypto/tls"
"fmt"
"path"
"strings"
"time"
"github.com/pingcap/errors"
clientv3 "go.etcd.io/etcd/client/v3"
)
// Node organizes the ectd query result as a Trie tree
type Node struct {
Value []byte
Childs map[string]*Node
}
// OpType is operation's type in etcd
type OpType string
var (
// CreateOp is create operation type
CreateOp OpType = "create"
// UpdateOp is update operation type
UpdateOp OpType = "update"
// DeleteOp is delete operation type
DeleteOp OpType = "delete"
)
// Operation represents an operation in etcd, include create, update and delete.
type Operation struct {
Tp OpType
Key string
Value string
TTL int64
WithPrefix bool
Opts []clientv3.OpOption
}
// String implements Stringer interface.
func (o *Operation) String() string {
return fmt.Sprintf("{Tp: %s, Key: %s, Value: %s, TTL: %d, WithPrefix: %v, Opts: %v}", o.Tp, o.Key, o.Value, o.TTL, o.WithPrefix, o.Opts)
}
// Client is a wrapped etcd client that support some simple method
type Client struct {
client *clientv3.Client
rootPath string
}
// NewClient returns a wrapped etcd client
func NewClient(cli *clientv3.Client, root string) *Client {
return &Client{
client: cli,
rootPath: root,
}
}
// NewClientFromCfg returns a wrapped etcd client
func NewClientFromCfg(endpoints []string, dialTimeout time.Duration, root string, security *tls.Config) (*Client, error) {
cli, err := clientv3.New(clientv3.Config{
Endpoints: endpoints,
DialTimeout: dialTimeout,
TLS: security,
})
if err != nil {
return nil, errors.Trace(err)
}
return &Client{
client: cli,
rootPath: root,
}, nil
}
// Close shutdowns the connection to etcd<|fim▁hole|> return nil
}
// GetClient returns client
func (e *Client) GetClient() *clientv3.Client {
return e.client
}
// Create guarantees to set a key = value with some options(like ttl)
func (e *Client) Create(ctx context.Context, key string, val string, opts []clientv3.OpOption) (int64, error) {
key = keyWithPrefix(e.rootPath, key)
txnResp, err := e.client.KV.Txn(ctx).If(
clientv3.Compare(clientv3.ModRevision(key), "=", 0),
).Then(
clientv3.OpPut(key, val, opts...),
).Commit()
if err != nil {
return 0, errors.Trace(err)
}
if !txnResp.Succeeded {
return 0, errors.AlreadyExistsf("key %s in etcd", key)
}
if txnResp.Header != nil {
return txnResp.Header.Revision, nil
}
// impossible to happen
return 0, errors.New("revision is unknown")
}
// Get returns a key/value matchs the given key
func (e *Client) Get(ctx context.Context, key string) (value []byte, revision int64, err error) {
key = keyWithPrefix(e.rootPath, key)
resp, err := e.client.KV.Get(ctx, key)
if err != nil {
return nil, -1, errors.Trace(err)
}
if len(resp.Kvs) == 0 {
return nil, -1, errors.NotFoundf("key %s in etcd", key)
}
return resp.Kvs[0].Value, resp.Header.Revision, nil
}
// Update updates a key/value.
// set ttl 0 to disable the Lease ttl feature
func (e *Client) Update(ctx context.Context, key string, val string, ttl int64) error {
key = keyWithPrefix(e.rootPath, key)
var opts []clientv3.OpOption
if ttl > 0 {
lcr, err := e.client.Lease.Grant(ctx, ttl)
if err != nil {
return errors.Trace(err)
}
opts = []clientv3.OpOption{clientv3.WithLease(lcr.ID)}
}
txnResp, err := e.client.KV.Txn(ctx).If(
clientv3.Compare(clientv3.ModRevision(key), ">", 0),
).Then(
clientv3.OpPut(key, val, opts...),
).Commit()
if err != nil {
return errors.Trace(err)
}
if !txnResp.Succeeded {
return errors.NotFoundf("key %s in etcd", key)
}
return nil
}
// UpdateOrCreate updates a key/value, if the key does not exist then create, or update
func (e *Client) UpdateOrCreate(ctx context.Context, key string, val string, ttl int64) error {
key = keyWithPrefix(e.rootPath, key)
var opts []clientv3.OpOption
if ttl > 0 {
lcr, err := e.client.Lease.Grant(ctx, ttl)
if err != nil {
return errors.Trace(err)
}
opts = []clientv3.OpOption{clientv3.WithLease(lcr.ID)}
}
_, err := e.client.KV.Do(ctx, clientv3.OpPut(key, val, opts...))
if err != nil {
return errors.Trace(err)
}
return nil
}
// List returns the trie struct that constructed by the key/value with same prefix
func (e *Client) List(ctx context.Context, key string) (node *Node, revision int64, err error) {
key = keyWithPrefix(e.rootPath, key)
if !strings.HasSuffix(key, "/") {
key += "/"
}
resp, err := e.client.KV.Get(ctx, key, clientv3.WithPrefix())
if err != nil {
return nil, -1, errors.Trace(err)
}
root := new(Node)
length := len(key)
for _, kv := range resp.Kvs {
key := string(kv.Key)
if len(key) <= length {
continue
}
keyTail := key[length:]
tailNode := parseToDirTree(root, keyTail)
tailNode.Value = kv.Value
}
return root, resp.Header.Revision, nil
}
// Delete deletes the key/values with matching prefix or key
func (e *Client) Delete(ctx context.Context, key string, withPrefix bool) error {
key = keyWithPrefix(e.rootPath, key)
var opts []clientv3.OpOption
if withPrefix {
opts = []clientv3.OpOption{clientv3.WithPrefix()}
}
_, err := e.client.KV.Delete(ctx, key, opts...)
if err != nil {
return errors.Trace(err)
}
return nil
}
// Watch watchs the events of key with prefix.
func (e *Client) Watch(ctx context.Context, prefix string, revision int64) clientv3.WatchChan {
if revision > 0 {
return e.client.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithRev(revision))
}
return e.client.Watch(ctx, prefix, clientv3.WithPrefix())
}
// DoTxn does some operation in one transaction.
// Note: should only have one opereration for one key, otherwise will get duplicate key error.
func (e *Client) DoTxn(ctx context.Context, operations []*Operation) (int64, error) {
cmps := make([]clientv3.Cmp, 0, len(operations))
ops := make([]clientv3.Op, 0, len(operations))
for _, operation := range operations {
operation.Key = keyWithPrefix(e.rootPath, operation.Key)
if operation.TTL > 0 {
if operation.Tp == DeleteOp {
return 0, errors.Errorf("unexpected TTL in delete operation")
}
lcr, err := e.client.Lease.Grant(ctx, operation.TTL)
if err != nil {
return 0, errors.Trace(err)
}
operation.Opts = append(operation.Opts, clientv3.WithLease(lcr.ID))
}
if operation.WithPrefix {
operation.Opts = append(operation.Opts, clientv3.WithPrefix())
}
switch operation.Tp {
case CreateOp:
cmps = append(cmps, clientv3.Compare(clientv3.ModRevision(operation.Key), "=", 0))
ops = append(ops, clientv3.OpPut(operation.Key, operation.Value, operation.Opts...))
case UpdateOp:
cmps = append(cmps, clientv3.Compare(clientv3.ModRevision(operation.Key), ">", 0))
ops = append(ops, clientv3.OpPut(operation.Key, operation.Value, operation.Opts...))
case DeleteOp:
ops = append(ops, clientv3.OpDelete(operation.Key, operation.Opts...))
default:
return 0, errors.Errorf("unknown operation type %s", operation.Tp)
}
}
txnResp, err := e.client.KV.Txn(ctx).If(
cmps...,
).Then(
ops...,
).Commit()
if err != nil {
return 0, errors.Trace(err)
}
if !txnResp.Succeeded {
return 0, errors.Errorf("do transaction failed, operations: %+v", operations)
}
return txnResp.Header.Revision, nil
}
func parseToDirTree(root *Node, path string) *Node {
pathDirs := strings.Split(path, "/")
current := root
var next *Node
var ok bool
for _, dir := range pathDirs {
if current.Childs == nil {
current.Childs = make(map[string]*Node)
}
next, ok = current.Childs[dir]
if !ok {
current.Childs[dir] = new(Node)
next = current.Childs[dir]
}
current = next
}
return current
}
func keyWithPrefix(prefix, key string) string {
if strings.HasPrefix(key, prefix) {
return key
}
return path.Join(prefix, key)
}<|fim▁end|> | func (e *Client) Close() error {
if err := e.client.Close(); err != nil {
return errors.Trace(err)
} |
<|file_name|>p77_combinations.py<|end_file_name|><|fim▁begin|># author: Fei Gao
#
# Combinations
#
# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
# For example,
# If n = 4 and k = 2, a solution is:
# [<|fim▁hole|># [1,3],
# [1,4],
# ]
import itertools
class Solution:
# @return a list of lists of integers
def combine(self, n, k):
return [list(p) for p in itertools.combinations(range(1, n + 1), k)]
def main():
solver = Solution()
print(solver.combine(4, 2))
pass
if __name__ == '__main__':
main()
pass<|fim▁end|> | # [2,4],
# [3,4],
# [2,3],
# [1,2], |
<|file_name|>interfacewebservice.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from tg.configuration import AppConfig, config
from tg import request
from pollandsurvey import model
from tgext.pyutilservice import Utility
import logging
log = logging.getLogger(__name__)
from tgext.pylogservice import LogDBHandler
class InterfaceWebService(object):
def __init__(self):
self.modules ='INTERFACESERVICE.WEBSERVICE'
dh = LogDBHandler( config=config,request=request)
log.addHandler(dh)
self.utility = Utility()
def mapVoterUser(self, voter):
"""
Check Voter and User in table sur_member_user is Empty will create again.
if not will pass.
Keyword arguments:
voter -- Object Voter
"""
self.memberUser = model.MemberUser();
try:
if voter:
user = model.User.by_email_address(voter.email)
if user :
self.memberUser = model.MemberUser.getByUserIdandVoter(user.user_id, voter.id_voter)
if self.memberUser is None:
self.memberUser = model.MemberUser();
self.memberUser.user_id = user.user_id<|fim▁hole|> except Exception as e:
log.error("mapVoterUser : %s" %e, extra=extraLog(modules=self.modules));
return self.memberUser;<|fim▁end|> | self.memberUser.id_voter = voter.id_voter
self.memberUser.save()
del user |
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)<|fim▁hole|>
class PyEpydoc(PythonPackage):
"""Epydoc is a tool for generating API documentation documentation for
Python modules, based on their docstrings."""
pypi = "epydoc/epydoc-3.0.1.tar.gz"
version('3.0.1', sha256='c81469b853fab06ec42b39e35dd7cccbe9938dfddef324683d89c1e5176e48f2')<|fim▁end|> |
from spack import * |
<|file_name|>BitWiseTrie2.hpp<|end_file_name|><|fim▁begin|>//
// BitWiseTrie.hpp
// Scissum
//
// Created by Marten van de Sanden on 12/1/15.
// Copyright © 2015 MVDS. All rights reserved.
//
#ifndef BitWiseTrie_hpp
#define BitWiseTrie_hpp
#include <vector>
//#include <iostream>
#include <cstring>
#define __SCISSUM_BITWISE_TRIE_USE_ZERO_TABLE 1
namespace scissum {
/// TODO: Add cache locality and allocation efficiency by pre allocating an array of nodes!!!!!
template <class _Key, class _Value>
class BitWiseTrie
{
public:
struct Node {
size_t childs[2];
_Value value;
Node()
{
childs[0] = 0;
childs[1] = 0;
}
};
BitWiseTrie()
{
d_nodes.resize(sizeof(_Key)*8+1);
for (size_t i = 0; i < sizeof(_Key)*8+1; ++i) {
d_zeroTable[i] = i;
}
}
Node const *node(size_t index) const
{
return &d_nodes[index];
}
Node const *roots(size_t lz) const
{
return &d_nodes[d_zeroTable[lz]];
}
Node *insert(_Key key)
{
int z = (key != 0?__builtin_clz(key):(sizeof(_Key) * 8));
size_t root = d_zeroTable[z];
int c = (sizeof(_Key) * 8) - z;
while (c-- > 0) {
//std::cout << "A " << c << " = " << !!(key & (1 << c)) << ".\n";
size_t n = d_nodes[root].childs[!!(key & (1 << c))];
if (n == 0) {
break;
}<|fim▁hole|> root = n;
}
while (c > 0) {
//std::cout << "B " << c << " = " << !!(key & (1 << c)) << ".\n";
size_t n = d_nodes.size();
d_nodes.push_back(Node());
d_nodes[root].childs[!!(key & (1 << c--))] = n;
root = n;
}
if (c == 0) {
//std::cout << "C = " << !!(key & 1) << ".\n";
size_t n = d_nodes.size();
d_nodes.push_back(Node());
d_nodes[root].childs[!!(key & 1)] = n;
return &d_nodes[n];
}
return &d_nodes[root];
}
private:
std::vector<Node> d_nodes;
size_t d_zeroTable[sizeof(_Key)*8+1];
};
}
#endif /* BitWiseTrie_hpp */<|fim▁end|> | |
<|file_name|>test_unsubscribe_from_list.py<|end_file_name|><|fim▁begin|># Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo.tests import HttpCase, tagged
from odoo.addons.mail.tests.common import MockEmail
@tagged("-at_install", "post_install")
class WebsiteSaleHttpCase(HttpCase, MockEmail):
def setUp(self):
super().setUp()
self.env = self.env(context=dict(self.env.context, tracking_disable=True))
self.mailing_list = self.env.ref("mass_mailing.mailing_list_data")
self.mailing_contact = self.env["mailing.contact"].create(
{
"name": "John Doe",
"email": "[email protected]",
}
)
<|fim▁hole|> # Create subscription
with self.mock_mail_gateway():
subs = self.env["mailing.contact.subscription"].create(
{
"contact_id": self.mailing_contact.id,
"list_id": self.mailing_list.id,
}
)
body = self._new_mails._send_prepare_values()["body"]
root = etree.fromstring(body, etree.HTMLParser())
anchor = root.xpath("//a[@href]")[0]
unsubscribe_url = anchor.attrib["href"]
web_base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url")
self.url_open(unsubscribe_url.replace(web_base_url, ""))
subs.invalidate_cache()
self.assertEqual(subs.opt_out, True)<|fim▁end|> | def test_subscription_email_unsubscribe_from_list(self): |
<|file_name|>MavenArtifactExclusion.java<|end_file_name|><|fim▁begin|>/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* MavenArtifactExclusion.java
* Copyright (C) 2021 University of Waikato, Hamilton, NZ
*/
package adams.core.base;
/**
* Encapsulates Maven artifact exclusions.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
*/
public class MavenArtifactExclusion
extends AbstractBaseString {
private static final long serialVersionUID = 1516586362049381050L;
public final static String SEPARATOR = ":";
/**
* Initializes the string with length 0.
*/
public MavenArtifactExclusion() {
this("");
}
/**
* Initializes the object with the string to parse.
*
* @param s the string to parse
*/
public MavenArtifactExclusion(String s) {
super(s);
}
/**
* Initializes the object with the artifact coordinates.
*
* @param groupId the group ID
* @param artifactId the artifact ID
*/
public MavenArtifactExclusion(String groupId, String artifactId) {
super(groupId + SEPARATOR + artifactId);
}
/**
* Checks whether the string value is a valid presentation for this class.
*
* @param value the string value to check
* @return true if non-null
*/
@Override<|fim▁hole|> return (value != null) && (value.split(SEPARATOR).length == 2);
}
/**
* Returns the specified part of the coordinate triplet.
*
* @param index the index from the triplet to return
* @return the value or empty string if invalid string or index
*/
protected String getPart(int index) {
String[] parts;
if (isEmpty())
return "";
parts = getValue().split(SEPARATOR);
if (parts.length != 2)
return "";
return parts[index];
}
/**
* Returns the group ID part, if possible.
*
* @return the group ID
*/
public String groupIdValue() {
return getPart(0);
}
/**
* Returns the artifact ID part, if possible.
*
* @return the artifact ID
*/
public String artifactIdValue() {
return getPart(1);
}
/**
* Returns a tool tip for the GUI editor (ignored if null is returned).
*
* @return the tool tip
*/
@Override
public String getTipText() {
return "The two coordinates of a Maven artifact exclusion: groupId:artifactId";
}
}<|fim▁end|> | public boolean isValid(String value) { |
<|file_name|>LoginInfoReqParam.java<|end_file_name|><|fim▁begin|>package com.vk.libs.appcommontest.gankio.mvp.data.requestbody;
/**
* Created by VK on 2017/2/8.<br/>
* - 登录
*/
public class LoginInfoReqParam {
/*
URL: /user/login.action
param:
{
account: ‘admin’,
password: ‘admin123’
}
*/
// {"j_mobile_mid":"864895022552002","j_pic_code":"4725",
// "j_password":"841e5c1f5a8a9ebc34a723f66affb38787b9364f",
// "j_app_version":"2.4.1_52_20170810","j_os_name":"samsung",
// "j_mobile_type":"ZTE U795","j_os_sdk":"17",
// "j_os_version":"Android4.2.2_JDQ39E","j_username":"leileima","salt":"b208cb62a85edb65d30f99ec3d08c434"}
private String j_mobile_mid = "864895022552002";
private String j_pic_code ;
private String j_password = "841e5c1f5a8a9ebc34a723f66affb38787b9364f";
private String j_app_version ="2.4.1_52_20170810";
private String j_os_name = "samsung";
private String j_mobile_type = "ZTE U795";
private String j_os_sdk = "17";
private String j_os_version = "Android4.2.2_JDQ39E";
private String j_username;
private String salt;
public LoginInfoReqParam(String account,String pwd,String picCode,String salt){
j_username = account;
this.salt = salt;
j_pic_code = picCode;
}
public String getJ_mobile_mid() {
return j_mobile_mid;
}
public void setJ_mobile_mid(String j_mobile_mid) {
this.j_mobile_mid = j_mobile_mid;
}
public String getJ_pic_code() {
return j_pic_code;
}
public void setJ_pic_code(String j_pic_code) {
this.j_pic_code = j_pic_code;
}
public String getJ_password() {
return j_password;
}
public void setJ_password(String j_password) {
this.j_password = j_password;
}
public String getJ_app_version() {
return j_app_version;
}
public void setJ_app_version(String j_app_version) {
this.j_app_version = j_app_version;
}
public String getJ_os_name() {
return j_os_name;
}
public void setJ_os_name(String j_os_name) {
this.j_os_name = j_os_name;
}
public String getJ_mobile_type() {
return j_mobile_type;
}
public void setJ_mobile_type(String j_mobile_type) {
this.j_mobile_type = j_mobile_type;
}
public String getJ_os_sdk() {
return j_os_sdk;
}
public void setJ_os_sdk(String j_os_sdk) {
this.j_os_sdk = j_os_sdk;
}
public String getJ_os_version() {
return j_os_version;
}
<|fim▁hole|> public String getJ_username() {
return j_username;
}
public void setJ_username(String j_username) {
this.j_username = j_username;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}<|fim▁end|> | public void setJ_os_version(String j_os_version) {
this.j_os_version = j_os_version;
}
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2022 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================<|fim▁hole|>from keras.engine.functional import Functional
from keras.engine.sequential import Sequential
from keras.engine.training import Model
from keras.models.cloning import clone_and_build_model
from keras.models.cloning import clone_model
from keras.models.cloning import share_weights
from keras.models.sharpness_aware_minimization import SharpnessAwareMinimization
from keras.saving.model_config import model_from_config
from keras.saving.model_config import model_from_json
from keras.saving.model_config import model_from_yaml
from keras.saving.save import load_model
from keras.saving.save import save_model
# Private symbols that are used in tests.
# TODO(b/221261361): Clean up private symbols usage and remove these imports.
from keras.models.cloning import _clone_functional_model
from keras.models.cloning import _clone_layer
from keras.models.cloning import _clone_layers_and_model_config
from keras.models.cloning import _clone_sequential_model<|fim▁end|> | """Keras models API."""
# pylint: disable=g-bad-import-order
|
<|file_name|>str-idx.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn main() {<|fim▁hole|> let c: u8 = s[4];
println!("{:?}", c);
assert_eq!(c, 0x6f as u8);
}<|fim▁end|> | let s = "hello".to_owned(); |
<|file_name|>IsSubsequence.py<|end_file_name|><|fim▁begin|>__source__ = 'https://leetcode.com/problems/is-subsequence/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/is-subsequence.py
# Time: O(n)
# Space: O(1)
#
# Description: Leetcode # 392. Is Subsequence
#
# Given a string s and a string t, check if s is subsequence of t.
#
# You may assume that there is only lower case English letters in both s and t.
# t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
#
# A subsequence of a string is a new string which is formed from
# the original string by deleting some (can be none) of the characters
# without disturbing the relative positions of the remaining characters.
# (ie, "ace" is a subsequence of "abcde" while "aec" is not).
#
# Example 1:
# s = "abc", t = "ahbgdc"
#
# Return true.
#
# Example 2:
# s = "axc", t = "ahbgdc"
#
# Return false.
#
# Follow up:
# If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B,
# and you want to check one by one to see if T has its subsequence.
# In this scenario, how would you change your code?
#
# Companies
# Pinterest
# Related Topics
# Binary Search Dynamic Programming Greedy
#
import unittest
# Greedy solution.
# 128ms 75.77%
class Solution(object):
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if not s:
return True
i = 0
for c in t:
if c == s[i]:
i += 1
if i == len(s):
break
return i == len(s)
def isSubsequence2(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
t = iter(t)
return all(c in t for c in s)
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought:
# two pointers:
# 17ms 77.84%<|fim▁hole|> public boolean isSubsequence(String s, String t) {
if (s.length() == 0) return true;
int indexS = 0, indexT = 0;
while (indexT < t.length()) {
if (t.charAt(indexT) == s.charAt(indexS)) {
indexS++;
if (indexS == s.length()) return true;
}
indexT++;
}
return false;
}
}
# 1ms 100%
class Solution {
public boolean isSubsequence(String s, String t) {
if (s.length() == 0) return true;
int prev = t.indexOf(s.charAt(0));
if (prev == -1) return false;
for (int i = 1; i < s.length(); i++) {
prev = t.indexOf(s.charAt(i), prev + 1);
if (prev == -1) return false;
}
return true;
}
}
# 1ms 100%
class Solution {
public boolean isSubsequence(String s, String t) {
int[] a = new int[s.length() + 1];
a[0] = -1;
for (int i = 0; i < s.length(); i++) {
int index = t.indexOf(s.charAt(i), a[i] + 1);
if (index == -1) {
return false;
}
a[i + 1] = index;
}
return true;
}
}
# quick examples fro java Collections.binarySearch(list, key)
# http://www.geeksforgeeks.org/collections-binarysearch-java-examples/
// Returns index of key in sorted list sorted in
// ascending order
public static int binarySearch(List slist, T key)
// Returns index of key in sorted list sorted in
// order defined by Comparator c.
public static int binarySearch(List slist, T key, Comparator c)
If key is not present, the it returns "(-(insertion point) - 1)".
The insertion point is defined as the point at which the key
would be inserted into the list.
public static void main(String[] args)
{
List al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(10);
al.add(20);
// 10 is present at index 3.
int index = Collections.binarySearch(al, 10);
System.out.println(index);
// 13 is not present. 13 would have been inserted
// at position 4. So the function returns (-4-1)
// which is -5.
index = Collections.binarySearch(al, 15);
System.out.println(index);
}
Binary search solution for follow-up with detailed comments
Re: Java binary search using TreeSet got TLE
I think the Map and TreeSet could be simplified by Array and binarySearch.
Since we scan T from beginning to the end (index itself is in increasing order),
List will be sufficient. Then we can use binarySearch to replace with TreeSet
ability which is a little overkill for this problem. Here is my solution.
// Follow-up: O(N) time for pre-processing, O(Mlog?) for each S.
// Eg-1. s="abc", t="bahbgdca"
// idx=[a={1,7}, b={0,3}, c={6}]
// i=0 ('a'): prev=1
// i=1 ('b'): prev=3
// i=2 ('c'): prev=6 (return true)
// Eg-2. s="abc", t="bahgdcb"
// idx=[a={1}, b={0,6}, c={5}]
// i=0 ('a'): prev=1
// i=1 ('b'): prev=6
// i=2 ('c'): prev=? (return false)
# 49ms 18.85%
class Solution {
public boolean isSubsequence(String s, String t) {
List<Integer>[] idx = new List[256]; // Just for clarity
for (int i = 0; i < t.length(); i++) {
if (idx[t.charAt(i)] == null)
idx[t.charAt(i)] = new ArrayList<>();
idx[t.charAt(i)].add(i);
}
int prev = 0;
for (int i = 0; i < s.length(); i++) {
if (idx[s.charAt(i)] == null) return false; // Note: char of S does NOT exist in T causing NPE
int j = Collections.binarySearch(idx[s.charAt(i)], prev);
if (j < 0) j = -j - 1;
if (j == idx[s.charAt(i)].size()) return false;
prev = idx[s.charAt(i)].get(j) + 1;
}
return true;
}
}
'''<|fim▁end|> | class Solution { |
<|file_name|>issue_2316_b.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unused_imports)]
#![feature(globs)]
extern crate issue_2316_a;
pub mod cloth {<|fim▁hole|>
pub enum fabric {
gingham, flannel, calico
}
}<|fim▁end|> | use issue_2316_a::*; |
<|file_name|>ifThereIsALotOfLight.js<|end_file_name|><|fim▁begin|>/*global require */
'use strict';
var _ = require('lodash'),
utils = require('./../build-utils'),
StatementInputBloq = require('./../statementInputBloq');
/**
* Bloq name: mbot-ifthereisalotoflight
*
* Bloq type: Statement-Input
*
* Description:
*
* Return type: none
*/
var bloqMBotIfThereIsALotOfLight = _.merge(_.clone(StatementInputBloq, true), {
name: 'mBotIfThereIsALotOfLight',
bloqClass: 'bloq-mbot-ifthereisalotoflight',
content: [
[{
alias: 'text',
value: 'if'
}, {
id: 'OPERATION',
alias: 'staticDropdown',
options: [{
label: 'bloq-mbot-ifthereisalotoflight-alot',
value: '+'
}, {
label: 'bloq-mbot-ifthereisalotoflight-low',
value: '-'
}, {
label: 'bloq-mbot-ifthereisalotoflight-operation-nodetect',
value: '*'
}]
}, {
alias: 'text',
value: 'with-the'
}, {
id: 'LIGHTSENSOR',
alias: 'dynamicDropdown',
options: 'mkb_lightsensor'
}]
],
code: '',
arduino: {
conditional: {
aliasId: 'OPERATION',
code: {
'+': 'if(¬{LIGHTSENSOR.readSensor} > 200){{STATEMENTS}}',
'-': 'if((¬{LIGHTSENSOR.readSensor} > 0) && (¬{LIGHTSENSOR.readSensor} <= 200)){{STATEMENTS}}',
'*': 'if(¬{LIGHTSENSOR.readSensor} <= 0){{STATEMENTS}}'
}
}
}
});<|fim▁hole|>bloqMBotIfThereIsALotOfLight.connectors[1].acceptedAliases = ['all', 'ifDown'];
module.exports = bloqMBotIfThereIsALotOfLight;<|fim▁end|> |
utils.preprocessBloq(bloqMBotIfThereIsALotOfLight); |
<|file_name|>transport.js<|end_file_name|><|fim▁begin|>/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <[email protected]>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var parser = require('./parser');
/**
* Expose the constructor.
*/
exports = module.exports = Transport;
/**
* Transport constructor.
*
* @api public
*/
function Transport (mng, data, req) {
this.manager = mng;
this.id = data.id;
this.disconnected = false;
this.drained = true;
this.handleRequest(req);
};
/**
* Access the logger.
*
* @api public
*/
Transport.prototype.__defineGetter__('log', function () {
return this.manager.log;
});
/**
* Access the store.
*
* @api public
*/
Transport.prototype.__defineGetter__('store', function () {
return this.manager.store;
});
/**
* Handles a request when it's set.
*
* @api private
*/
Transport.prototype.handleRequest = function (req) {
this.log.debug('setting request', req.method, req.url);
this.req = req;
if (req.method == 'GET') {
this.socket = req.socket;
this.open = true;
this.drained = true;
this.setHeartbeatInterval();
this.setHandlers();
this.onSocketConnect();
}
};
/**
* Called when a connection is first set.
*
* @api private
*/
Transport.prototype.onSocketConnect = function () { };
/**
* Sets transport handlers
*
* @api private
*/
Transport.prototype.setHandlers = function () {
var self = this;
this.bound = {
end: this.onSocketEnd.bind(this)
, close: this.onSocketClose.bind(this)
, error: this.onSocketError.bind(this)
, drain: this.onSocketDrain.bind(this)
};
this.socket.on('end', this.bound.end);
this.socket.on('close', this.bound.close);
this.socket.on('error', this.bound.error);
this.socket.on('drain', this.bound.drain);
this.handlersSet = true;
};
/**
* Removes transport handlers
*
* @api private
*/
Transport.prototype.clearHandlers = function () {
if (this.handlersSet) {
this.socket.removeListener('end', this.bound.end);
this.socket.removeListener('close', this.bound.close);
this.socket.removeListener('error', this.bound.error);
this.socket.removeListener('drain', this.bound.drain);
}
};
/**
* Called when the connection dies
*
* @api private
*/
Transport.prototype.onSocketEnd = function () {
this.end('socket end');
};
/**
* Called when the connection dies
*
* @api private
*/
Transport.prototype.onSocketClose = function (error) {
this.end(error ? 'socket error' : 'socket close');
};
/**
* Called when the connection has an error.
*
* @api private
*/
Transport.prototype.onSocketError = function (err) {
if (this.open) {
this.socket.destroy();
this.onClose();
}
this.log.info('socket error ' + err.stack);
};
/**
* Called when the connection is drained.
*
* @api private
*/
Transport.prototype.onSocketDrain = function () {
this.drained = true;
};
/**
* Called upon receiving a heartbeat packet.
*
* @api private
*/
Transport.prototype.onHeartbeatClear = function () {
this.clearHeartbeatTimeout();
this.setHeartbeatInterval();
};
/**
* Called upon a forced disconnection.
*
* @api private
*/
Transport.prototype.onForcedDisconnect = function () {
if (!this.disconnected) {
this.log.info('transport end by forced client disconnection');
if (this.open) {
this.packet({ type: 'disconnect' });
}
this.end('booted');
}
};
/**
* Dispatches a packet.
*
* @api private
*/
Transport.prototype.onDispatch = function (packet, volatile) {
if (volatile) {
this.writeVolatile(packet);
} else {
this.write(packet);
}
};
/**
* Sets the close timeout.
*/
Transport.prototype.setCloseTimeout = function () {
if (!this.closeTimeout) {
var self = this;
this.closeTimeout = setTimeout(function () {
self.log.debug('fired close timeout for client', self.id);
self.closeTimeout = null;
self.end('close timeout');
}, this.manager.get('close timeout') * 1000);
this.log.debug('set close timeout for client', this.id);
}
};
/**
* Clears the close timeout.
*/
Transport.prototype.clearCloseTimeout = function () {
if (this.closeTimeout) {
clearTimeout(this.closeTimeout);
this.closeTimeout = null;
this.log.debug('cleared close timeout for client', this.id);
}
};
/**
* Sets the heartbeat timeout
*/
Transport.prototype.setHeartbeatTimeout = function () {
if (!this.heartbeatTimeout && this.manager.enabled('heartbeats')) {
var self = this;
this.heartbeatTimeout = setTimeout(function () {
self.log.debug('fired heartbeat timeout for client', self.id);
self.heartbeatTimeout = null;
self.end('heartbeat timeout');
}, this.manager.get('heartbeat timeout') * 1000);
this.log.debug('set heartbeat timeout for client', this.id);
}
};
/**
* Clears the heartbeat timeout
*
* @param text
*/
Transport.prototype.clearHeartbeatTimeout = function () {
if (this.heartbeatTimeout && this.manager.enabled('heartbeats')) {
clearTimeout(this.heartbeatTimeout);
this.heartbeatTimeout = null;
this.log.debug('cleared heartbeat timeout for client', this.id);
}
};
/**
* Sets the heartbeat interval. To be called when a connection opens and when
* a heartbeat is received.
*
* @api private
*/
Transport.prototype.setHeartbeatInterval = function () {
if (!this.heartbeatInterval && this.manager.enabled('heartbeats')) {
var self = this;
this.heartbeatInterval = setTimeout(function () {
self.heartbeat();
self.heartbeatInterval = null;
}, this.manager.get('heartbeat interval') * 1000);
this.log.debug('set heartbeat interval for client', this.id);
}
};
/**
* Clears all timeouts.
*
* @api private
*/
Transport.prototype.clearTimeouts = function () {
this.clearCloseTimeout();
this.clearHeartbeatTimeout();
this.clearHeartbeatInterval();
};
/**
* Sends a heartbeat
*
* @api private
*/
Transport.prototype.heartbeat = function () {
if (this.open) {<|fim▁hole|> this.log.debug('emitting heartbeat for client', this.id);
this.packet({ type: 'heartbeat' });
this.setHeartbeatTimeout();
}
return this;
};
/**
* Handles a message.
*
* @param {Object} packet object
* @api private
*/
Transport.prototype.onMessage = function (packet) {
var current = this.manager.transports[this.id];
if ('heartbeat' == packet.type) {
this.log.debug('got heartbeat packet');
if (current && current.open) {
current.onHeartbeatClear();
} else {
this.store.publish('heartbeat-clear', this.id);
}
} else {
if ('disconnect' == packet.type && packet.endpoint == '') {
this.log.debug('got disconnection packet');
if (current) {
current.onForcedDisconnect();
} else {
this.store.publish('disconnect-force', this.id);
}
return;
}
if (packet.id && packet.ack != 'data') {
this.log.debug('acknowledging packet automatically');
var ack = parser.encodePacket({
type: 'ack'
, ackId: packet.id
, endpoint: packet.endpoint || ''
});
if (current && current.open) {
current.onDispatch(ack);
} else {
this.manager.onClientDispatch(this.id, ack);
this.store.publish('dispatch-remote', this.id, ack);
}
}
// handle packet locally or publish it
if (current) {
this.manager.onClientMessage(this.id, packet);
} else {
this.store.publish('message-remote', this.id, packet);
}
}
};
/**
* Clears the heartbeat interval
*
* @api private
*/
Transport.prototype.clearHeartbeatInterval = function () {
if (this.heartbeatInterval && this.manager.enabled('heartbeats')) {
clearTimeout(this.heartbeatInterval);
this.heartbeatInterval = null;
this.log.debug('cleared heartbeat interval for client', this.id);
}
};
/**
* Finishes the connection and makes sure client doesn't reopen
*
* @api private
*/
Transport.prototype.disconnect = function (reason) {
this.packet({ type: 'disconnect' });
this.end(reason);
return this;
};
/**
* Closes the connection.
*
* @api private
*/
Transport.prototype.close = function () {
if (this.open) {
this.doClose();
this.onClose();
}
};
/**
* Called upon a connection close.
*
* @api private
*/
Transport.prototype.onClose = function () {
if (this.open) {
this.setCloseTimeout();
this.clearHandlers();
this.open = false;
this.manager.onClose(this.id);
this.store.publish('close', this.id);
}
};
/**
* Cleans up the connection, considers the client disconnected.
*
* @api private
*/
Transport.prototype.end = function (reason) {
if (!this.disconnected) {
this.log.info('transport end (' + reason + ')');
var local = this.manager.transports[this.id];
this.close();
this.clearTimeouts();
this.disconnected = true;
if (local) {
this.manager.onClientDisconnect(this.id, reason);
}
this.store.publish('disconnect-remote', this.id, reason);
}
};
/**
* Signals that the transport should pause and buffer data.
*
* @api public
*/
Transport.prototype.discard = function () {
this.log.debug('discarding transport');
this.discarded = true;
this.clearTimeouts();
this.clearHandlers();
return this;
};
/**
* Writes an error packet with the specified reason and advice.
*
* @param {Number} advice
* @param {Number} reason
* @api public
*/
Transport.prototype.error = function (reason, advice) {
this.packet({
type: 'error'
, reason: reason
, advice: advice
});
this.log.warn(reason, advice ? ('client should ' + advice) : '');
this.end('error');
};
/**
* Write a packet.
*
* @api public
*/
Transport.prototype.packet = function (obj) {
return this.write(parser.encodePacket(obj));
};
/**
* Writes a volatile message.
*
* @api private
*/
Transport.prototype.writeVolatile = function (msg) {
if (this.open) {
if (this.drained) {
this.write(msg);
} else {
this.log.debug('ignoring volatile packet, buffer not drained');
}
} else {
this.log.debug('ignoring volatile packet, transport not open');
}
};<|fim▁end|> | |
<|file_name|>two_sum.py<|end_file_name|><|fim▁begin|>class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
inspected_dict = {}
for i, num in enumerate(nums):
try:
j = inspected_dict[num]
<|fim▁hole|> inspected_dict[target-num] = i<|fim▁end|> | return j+1, i+1
except KeyError:
|
<|file_name|>bitcoin_fr_CA.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="fr_CA" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About LogiCoin</source>
<translation>Au sujet de LogiCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>LogiCoin</b> version</source>
<translation>Version de <b>LogiCoin</b></translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The LogiCoin developers</source>
<translation>Copyright © 2009-2014 Les développeurs Bitcoin
Copyright © 2012-2014 Les développeurs NovaCoin
Copyright © 2014 Les développeurs LogiCoin</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Ce logiciel est expérimental.
Distribué sous licence logicielle MIT/X11, voir le fichier COPYING joint ou http://www.opensource.org/licenses/mit-license.php.
Ce produit comprend des logiciels développés par le projet OpenSSL afin d'être utilisés dans la boîte à outils OpenSSL (http://www.openssl.org/), un logiciel de chiffrement écrit par Eric Young ([email protected]), et un logiciel UPnP développé par Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Répertoire d'adresses</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Double cliquer afin de modifier l'adresse ou l'étiquette</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Créer une nouvelle adresse</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copier l'adresse sélectionnée vers le presse-papier système</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nouvelle adresse</translation>
</message>
<message>
<location line="-46"/>
<source>These are your LogiCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Ce sont vos adresses pour recevoir vos paiements. Vous pouvez utiliser une adresse différente pour chaque réception afin d'identifier facilement le payeur.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Copier l'adresse</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Montrer le &QR Code</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a LogiCoin address</source>
<translation>Signer un message afin de valider l'identité de votre adresse LogiCoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signer le &message</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Effacer l'adresse actuellement sélectionnée de la liste</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified LogiCoin address</source>
<translation>Vérifier un message pour s'assurer qu'il vient d'un adresse LogiCoin spécifique.</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Vérifier un message</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Supprimer</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Copier l'&Étiquette</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Modifier</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Exporter votre répertoire d'adresses</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Fichier de valeurs séparées par des virgules (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Erreur lors de l'export</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Impossible d'écrire dans le fichier %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialogue de phrase de passe</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Saisir la phrase de passe</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nouvelle phrase de passe</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Répéter la phrase de passe</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>Sert à désactiver les transactions sortantes si votre compte de système d'exploitation est compromis. Ne procure pas de réelle sécurité.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Pour "staking" seulement</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Saisir la nouvelle phrase de passe pour le portefeuille. <br/>Veuillez utiliser une phrase de passe de <b>10 caractères aléatoires ou plus</b>, ou de <b>huit mots ou plus</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Crypter le portefeuille</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour déverrouiller le portefeuille.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Déverrouiller le portefeuille</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour déchiffrer le portefeuille.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Déchiffrer le portefeuille</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Changer la phrase de passe</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Saisir l’ancienne et la nouvelle phrase de passe du portefeuille</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirmer le cryptage du portefeuille</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>ATTENTION : Si vous cryptez votre portefeuille et perdez votre passphrase, vous ne pourrez plus accéder à vos LogiCoins</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Êtes-vous sûr de vouloir crypter votre portefeuille ?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANT : Toute sauvegarde précédente de votre fichier de portefeuille devrait être remplacée par le nouveau fichier de portefeuille crypté. Pour des raisons de sécurité, les sauvegardes précédentes de votre fichier de portefeuille non crypté deviendront inutilisables dès lors que vous commencerez à utiliser le nouveau portefeuille crypté.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Attention : la touche Verr. Maj. est activée !</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Portefeuille crypté</translation>
</message>
<message>
<location line="-58"/>
<source>LogiCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>L'application LogiCoin va désormais se terminer afin de finaliser le processus de cryptage. Merci de noter que le cryptage du portefeuille ne garantit pas de se prémunir du vol via l'utilisation de malware, qui auraient pu infecter votre ordinateur. </translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Le cryptage du portefeuille a échoué</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Le cryptage du portefeuille a échoué en raison d'une erreur interne. Votre portefeuille n'a pas été crypté.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Les phrases de passe saisies ne correspondent pas.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Le déverrouillage du portefeuille a échoué</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La phrase de passe saisie pour décrypter le portefeuille était incorrecte.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Le décryptage du portefeuille a échoué</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>La phrase de passe du portefeuille a été modifiée avec succès.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>Signer le &message...</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>Synchronisation avec le réseau en cours…</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>&Vue d'ensemble</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Afficher une vue d’ensemble du portefeuille</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transactions</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Parcourir l'historique des transactions</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>Carnet d'adresses</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Éditer la liste d'adresses et libellés</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>&Recevoir des monnaies</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Montrer la liste d'adresses de réception des paiements</translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>&Envoyer des monnaies</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>Q&uitter</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Quitter l’application</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about LogiCoin</source>
<translation>Afficher des informations au sujet du LogiCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>À propos de &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Afficher des informations sur Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Options…</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Crypter le portefeuille...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Sauvegarder le &portefeuille...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Changer la phrase de passe...</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation><numerusform>~%n blocks restants</numerusform><numerusform>~%n blocs restants</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>Téléchargement des blocks de l'historique des transactions : 1% sur 2% (%3% effectués).</translation>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation>&Export...</translation>
</message>
<message>
<location line="-64"/>
<source>Send coins to a LogiCoin address</source>
<translation>Envoyer des monnaies vers une adresse LogiCoin</translation>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for LogiCoin</source>
<translation>Modification des options de configuration de LogiCoin</translation>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation>Export des données de l'onglet courant vers un fichier</translation>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation>Crypter ou décrypter le portefeuille</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Sauvegarder le portefeuille vers un autre emplacement</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Modifier la phrase de passe utilisée pour le cryptage du portefeuille</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Fenêtre de débogage</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Ouvrir une console de débogage et de diagnostic</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Vérifier un message...</translation>
</message>
<message>
<location line="-202"/>
<source>LogiCoin</source>
<translation>LogiCoin</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Portefeuille</translation>
</message>
<message>
<location line="+180"/>
<source>&About LogiCoin</source>
<translation>A propos de LogiCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Afficher / Cacher</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation>Déverrouiller le portefeuille</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>&Verrouiller le portefeuille</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Verrouiller le portefeuille</translation>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Fichier</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Réglages</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Aide</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>Barre d'outils des onglets</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation>Barre d'actions</translation>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>LogiCoin client</source>
<translation>Client LogiCoin</translation>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to LogiCoin network</source>
<translation><numerusform>%n connexion active au réseau LogiCoin</numerusform><numerusform>%n connexions actives au réseau LogiCoin</numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Téléchargement de blocs de l'historique de transactions : 1% blocks</translation>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Staking.<br>Votre poids est de %1<br>Le poids du réseau est de %2<br>Temps estimé avant récompense %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Ne stack pas, votre portefeuilles est verouillé</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Ne stack pas, votre portefeuilles est hors ligne</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Ne stack pas, votre portefeuille est en cours de synchronisation</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Ne stack pas, vos monnaies ne sont pas encore matures</translation>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation><numerusform>il y a %n seconde</numerusform><numerusform>il y a %n secondes</numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About LogiCoin card</source>
<translation>Au sujet de la carte LogiCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about LogiCoin card</source>
<translation>Informations sur la carte LogiCoin</translation>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation>&Déverrouiller le portefeuille</translation>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation><numerusform>il y a %n minute</numerusform><numerusform>il y a %n minutes</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation><numerusform>il y a %n heure</numerusform><numerusform>il y a %n heures</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation><numerusform>il y a %n jour</numerusform><numerusform>il y a %n jours</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>À jour</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Rattrapage en cours…</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation>Le dernier block reçu à été généré %1.</translation>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Cette transaction dépasse la limite autorisée. Vous pouvez tout de même effectuer cette opération, moyennant %1 de frais, qui seront envoyés aux noeuds qui valideront cette transaction, et dont l'objectif vise à supporter le réseau. Etes-vous d'accord pour payer ces frais ?</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation>Confirmer le Paiement des frais de transaction</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Transaction envoyée</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Transaction entrante</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Date : %1
Montant : %2
Type : %3
Adresse : %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>Prise en charge de l'URL</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid LogiCoin address or malformed URI parameters.</source>
<translation>L'adresse du portefeuille LogiCoin n'as pas pu être correctement identifiée, car invalide ou malformée.</translation>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Le portefeuille est <b>crypté</b> et est actuellement <b>déverrouillé</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Le portefeuille est <b>crypté</b> et actuellement <b>verrouillé</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation>Sauvegarder le portefeuille</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Données liées au portefeuille (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Echec de la sauvegarde</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Une erreur a été rencontrée lors de la tentative de sauvegarde du portefeuille vers la nouvelle destination.</translation>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation><numerusform>%n seconde</numerusform><numerusform>%n secondes</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n minute</numerusform><numerusform>%n minutes</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n heure</numerusform><numerusform>%n heures</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n jour</numerusform><numerusform>%n jours</numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation>Pas de stacking</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. LogiCoin can no longer continue safely and will quit.</source>
<translation>Une erreur fatale a été rencontrée. L'application LogiCoin ne peut plus être s'exécuter de façon correcte et doit se terminer.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Alerte réseau</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Fonctions de contrôle des monnaies</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Quantité :</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Octets :</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Montant :</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Priorité :</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Frais :</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Sortie faible :</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>non</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Après les frais :</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Monnaie :</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>Tout (dé)sélectionner</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Mode arborescence</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Mode liste</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Intitulé</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmations</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmée</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Priorité</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Copier l’adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copier l’étiquette</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copier le montant</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copier l'ID de la transaction</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Copier la quantité</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Copier les frais</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copier le montant après les frais</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copier les octets</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copier la priorité</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copier la sortie faible</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copier la monnaie</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>la plus élevée</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>élevée</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>moyennement-élevée</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>moyenne</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>moyennement-basse</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>basse</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>la plus basse</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation>DUST</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>oui</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>Cet intitulé passe au rouge, si la taille de la transaction est supérieure à 10000 bytes.
Cela implique que des frais à hauteur d'au moins %1 par kb seront nécessaires.
Ceux-ci Peuvent varier de +/- 1 Byte par entrée.</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>Les transactions avec une priorité haute ont plus de chances d'être traitées en un block.
Rouge si votre priorité est plus petite que "moyenne".
Cela veut dire que des frais d'un minimum de %1 par kb sont requis</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Ce label passe au rouge, Lorsqu'un destinataire reçoit un montant inférieur à %1.
Cela implique que des frais à hauteur de %2 seront nécessaire
Les montants inférieurs à 0.546 fois les frais minimum de relais apparaissent en tant que DUST.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Ce label passe au rouge, lorsque la différence est inférieure à %1.
Cela implique que des frais à hauteur d'au moins %2 seront nécessaires.</translation>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>monnaie de %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(monnaie)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Modifier l'adresse</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Étiquette</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>L'intitulé associé à cette entrée du carnet d'adresse</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>L'intitulé associé à cette entrée du carnet d'adresse. Seules les adresses d'envoi peuvent être modifiées.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Nouvelle adresse de réception</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nouvelle adresse d’envoi</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Modifier l’adresse de réception</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Modifier l’adresse d'envoi</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>L’adresse fournie « %1 » est déjà présente dans le carnet d'adresses.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid LogiCoin address.</source>
<translation>L'adresse "%1" renseignée n'est pas une adresse LogiCoin valide.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Impossible de déverrouiller le portefeuille.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Échec de génération de la nouvelle clef.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>LogiCoin-Qt</source>
<translation>LogiCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Utilisation:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>Options de ligne de commande</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Options graphiques</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Définir la langue, par exemple « fr_FR » (par défaut : la langue du système)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Démarrer en mode réduit</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Affichage de l'écran de démarrage (défaut: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Options</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>Réglages &principaux</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Frais de transaction optionnels par kB afin d'assurer la rapidité de traitement de votre transaction. La plupart des transactions sont de 1 kB. Frais de 0.01 recommandés.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Payer des &frais de transaction</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>Montant réservé qui ne "stake" pas est reste utilisable pour réalisés des envois à tout moment.</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Réserve</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start LogiCoin after logging in to the system.</source>
<translation>Démarrage automatique du client LogiCoin lors de la connexion au système</translation>
</message>
<message>
<location line="+3"/>
<source>&Start LogiCoin on system login</source>
<translation>&Démarrage du client LogiCoin à la connexion au système</translation>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation>Détacher la base des block et adresses à la fermeture. Vous pourrez les utiliser dans un autre dossier mais cela ralenti la fermeture. Le portefeuille est lui toujours détaché.</translation>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation>&Détacher la base de données à la fermeture</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Réseau</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the LogiCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Ouverture automatique du port client de LogiCoin sur le routeur. Ceci ne fonctionne que dans le cas où le support UPnP sur votre routeur existe et est actif.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapper le port avec l'&UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the LogiCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Connexion au réseau LogiCoin à travers un proxy SOCKS (e.g. Connexion via le réseau Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Connexion à travers du proxy SOCKS:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP du serveur mandataire :</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Addresse IP du proxy (e.g. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port :</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port du serveur mandataire (par ex. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Version SOCKS :</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Version SOCKS du serveur mandataire (par ex. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Fenêtre</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Afficher uniquement une icône système après minimisation.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimiser dans la barre système au lieu de la barre des tâches</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimiser au lieu de quitter l'application lorsque la fenêtre est fermée. Si cette option est activée, l'application ne pourra être fermée qu'en sélectionnant Quitter dans le menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimiser lors de la fermeture</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Affichage</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Langue de l'interface utilisateur :</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting LogiCoin.</source>
<translation>La langue d'interface de de l'utilisateur peut être définie ici. Ces modification seront effectives après redémarrage de l'application LogiCoin</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unité d'affichage des montants :</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Choisissez la sous-unité par défaut pour l'affichage dans l'interface et lors de l'envoi de pièces.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show LogiCoin addresses in the transaction list or not.</source>
<translation>Afficher les adresses LogiCoin au sein de la liste de transactions</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Afficher les adresses sur la liste des transactions</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Afficher ou non les fonctions de contrôle des pièces.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Afficher les options de monnaie & contrôle (mode expert)</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Annuler</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Exécuter</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>par défaut</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation>Avertissement</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting LogiCoin.</source>
<translation>Les paramètres prendront effet après redémarrage du client LogiCoin</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>L'adresse de serveur mandataire -proxy- fournie est invalide.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulaire</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the LogiCoin network after a connection is established, but this process has not completed yet.</source>
<translation>Les informations affichées peuvent être obsolètes. Votre portefeuille se synchronise automatiquement avec le réseau LogiCoin mais ce processus n'est pas encore terminé.</translation>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation>Stake:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Non confirmé:</translation>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Portefeuille</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Disponible pour dépense:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Votre solde actuel pouvant être dépensé</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Immature :</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Le solde généré n'est pas encore mature</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Total :</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Votre solde total actuel</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Transactions récentes</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Montant total des transactions nécessitant confirmation, et ne figurant pas encore dans la balance actuelle</translation>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Montant total des transactions en "staking" et ne figurant pas encore dans la balance actuelle</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>désynchronisé</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Boîte de dialogue QR Code</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Demander un paiement</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Montant :</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Intitulé:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Message:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Enregistrer sous...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Erreur d'encodage de l'URI en code QR.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Le montant indiqué est invalide, veuillez vérifier.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>L'URI résultant est trop long, essayez de réduire le texte d'étiquette / de message.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Sauvegarder le QR Code</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Images PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nom du client</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>N.D.</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Version du client</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informations</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Version d'OpenSSL utilisée</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Heure de démarrage</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Réseau</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Nombre de connexions</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Sur testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Chaîne de blocks</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nombre actuel de blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Nombre total estimé de blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Horodatage du dernier block</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Ouvrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Options de ligne de commande</translation>
</message>
<message>
<location line="+7"/>
<source>Show the LogiCoin-Qt help message to get a list with possible LogiCoin command-line options.</source>
<translation>Afficher le message d'aide LogiCoin-Qt afin d'obtenir la liste des options de de L'outil en ligne de commande LogiCoin</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Afficher</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Date de compilation</translation>
</message>
<message>
<location line="-104"/>
<source>LogiCoin - Debug window</source>
<translation>LogiCoin - Fenêtre de déboggage</translation>
</message>
<message>
<location line="+25"/>
<source>LogiCoin Core</source>
<translation>LogiCoin Core</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Journal de débogage</translation>
</message>
<message>
<location line="+7"/>
<source>Open the LogiCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Ouvrir le fichier journal de debug LogiCoin au sein du répertoire courant. Cette opération peut prendre quelques secondes dans le cas de fichiers journaux volumineux.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Nettoyer la console</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the LogiCoin RPC console.</source>
<translation>Bienvenue sur la console LogiCoin RPC.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Utiliser les touches de curseur pour naviguer dans l'historique et <b>Ctrl-L</b> pour effacer l'écran.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Taper <b>help</b> pour afficher une vue générale des commandes disponibles.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Envoyer des monnaies</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Fonctions de contrôle des monnaies</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Entrants...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>choisi automatiquement</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Fonds insuffisants !</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Quantité :</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Octets :</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Montant :</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 LOGIC</source>
<translation>123.456 LOGIC {0.00 ?}</translation>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Priorité :</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>medium</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Frais :</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Sortie faible</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>non</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Après les frais :</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>Monnaie :</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>adresse de change personnalisée</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Envoyer à plusieurs destinataires à la fois</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Ajouter un &destinataire</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Réinitialiser tous les champs liés à la transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Tout nettoyer</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Solde :</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 LOGIC</source>
<translation>123.456 LOGIC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirmer l’action d'envoi</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>E&nvoyer</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a LogiCoin address (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</source>
<translation>Entrer une adresse LogiCoin (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Copier la quantité</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copier le montant</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Copier les frais</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copier le montant après les frais</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copier les octets</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copier la priorité</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copier la sortie faible</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copier la monnaie</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmer l’envoi des pièces</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Etes-vous sûr de vouloir envoyer %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>et</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>L'adresse du destinataire n’est pas valide, veuillez la vérifier.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Le montant à payer doit être supérieur à 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Le montant dépasse votre solde.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Le montant dépasse votre solde lorsque les frais de transaction de %1 sont inclus.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Adresse indentique trouvée, il n'est possible d'envoyer qu'une fois à chaque adresse par opération d'envoi.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation>Erreur: Echec lors de la création de la transaction</translation>
</message>
<message>
<location line="+5"/>
<source>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.</source>
<translation>Erreur: La transaction a été rejetée. Cela peut se produire si une quantité d'argent de votre portefeuille a déjà été dépensée, comme dans le cas où une copie du fichier wallet.dat aurait été utilisée afin d'effectuer des dépenses, à la place du fichier courant.</translation>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid LogiCoin address</source>
<translation>AVERTISSEMENT: Adresse LogiCoin Invalide</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(pas d'étiquette)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>AVERTISSEMET: Adresse LogiCoin Invalide</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message><|fim▁hole|> </message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Montant :</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Payer à :</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Saisir une étiquette pour cette adresse afin de l’ajouter à votre carnet d’adresses</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Étiquette :</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</source>
<translation>Adresse destinataire du paiement ( ex : MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>Choisir une adresse du carnet d'adresse</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Coller l'adresse depuis le presse-papier</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Supprimer ce destinataire</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a LogiCoin address (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</source>
<translation>Entrer une adresse LogiCoin (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signatures - Signer / Vérifier un message</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Signer un message</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Vous pouvez signer des messages avec vos adresses pour prouver que vous les détenez. Faites attention de ne rien signer de suspect car des attaques d'hameçonnage peuvent essayer d'usurper votre identité par votre signature. Ne signez que des déclarations entièrement détaillées et avec lesquelles vous serez d'accord.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</source>
<translation>Entrer une adresse LogiCoin (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Choisir une adresse du carnet d'adresse</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Coller une adresse depuis le presse-papier</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Saisir ici le message que vous désirez signer</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copier la signature actuelle dans le presse-papier</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this LogiCoin address</source>
<translation>Signer le message afin de prouver l'identité de votre adresse LogiCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Réinitialiser tous les champs de signature de message</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Tout nettoyer</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Vérifier un message</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Saisir ci-dessous l'adresse de signature, le message (assurez-vous d'avoir copié exactement les retours à la ligne, les espaces, tabulations etc...) et la signature pour vérifier le message. Faire attention à ne pas déduire davantage de la signature que ce qui est contenu dans le message signé lui-même pour éviter d'être trompé par une attaque d'homme du milieu.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</source>
<translation>L'adresse avec laquelle le message à été signé (ex: MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified LogiCoin address</source>
<translation>Vérifier un message pour s'assurer qu'il vient d'un adresse LogiCoin spécifique.</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Réinitialiser tous les champs de vérification de message</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a LogiCoin address (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</source>
<translation>Entrer une adresse LogiCoin (e.g. MN8fd1QR5TXecqnFJhBY959CMKGy8t37oU)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Cliquez sur « Signer le message » pour générer la signature</translation>
</message>
<message>
<location line="+3"/>
<source>Enter LogiCoin signature</source>
<translation>Entrer une signature LogiCoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>L'adresse saisie est invalide.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Veuillez vérifier l'adresse et réessayer.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>L'adresse saisie ne fait pas référence à une clef.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Le déverrouillage du portefeuille a été annulé.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>La clef privée pour l'adresse indiquée n'est pas disponible.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>La signature du message a échoué.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Le message a été signé.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>La signature n'a pu être décodée.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Veuillez vérifier la signature et réessayer.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>La signature ne correspond pas à l'empreinte du message.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Échec de la vérification du message.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Message vérifié.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Ouvert pour %n bloc</numerusform><numerusform>Ouvert pour %n blocks</numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation>en conflit</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/hors ligne</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/non confirmée</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>État</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, diffusée à travers %n nœud</numerusform><numerusform>, diffusée à travers %n nœuds</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Généré</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>À</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>votre propre adresse</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>étiquette</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Crédit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>arrive à maturité dans %n bloc de plus</numerusform><numerusform>arrive à maturité dans %n blocks supplémentaires</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>refusé</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Débit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Frais de transaction</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Montant net</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Commentaire</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID de la transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Les pièces de monnaie générées nécessitent une maturation de 510 blocks avant de pouvoir être utilisées. Lors de la génération d'un blokc, celui-ci est diffusé sur le réseau afin d'être ajouté à la chaîne de blocks. En cas d'échec, son état passera en "non accepté" et celui-ci ne pourra pas être dépensé. Cela peut occasionnellement se produire, lorsqu'un noeud différent génère un block à quelques secondes d'intervalle du vôtre.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informations de débogage</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Entrants</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>vrai</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>faux</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, n’a pas encore été diffusée avec succès</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>inconnu</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Détails de la transaction</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ce panneau affiche une description détaillée de la transaction</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmée (%1 confirmations)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ouvert pour %n bloc de plus</numerusform><numerusform>Ouvert pour %n blocs de plus</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Hors ligne</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Non confirmé</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Confirmation (%1 sur %2 confirmations recommandées)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>En conflit</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Immature (%1 confirmations, sera disponible après %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ce bloc n’a été reçu par aucun autre nœud et ne sera probablement pas accepté !</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Généré mais pas accepté</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Reçue avec</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Reçue de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Envoyée à</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Paiement à vous-même</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Extrait</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n.d)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>État de la transaction. Laissez le pointeur de la souris sur ce champ pour voir le nombre de confirmations.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Date et heure de réception de la transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type de transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>L’adresse de destination de la transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Montant ajouté ou enlevé au solde.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Toutes</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Aujourd’hui</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Cette semaine</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Ce mois-ci</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Le mois dernier</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Cette année</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervalle…</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Reçue avec</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Envoyée à</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>À vous-même</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Extrait</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Autres</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Saisir une adresse ou une étiquette à rechercher</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Montant min.</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copier l’adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copier l’étiquette</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copier le montant</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copier l'ID de la transaction</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Modifier l’étiquette</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Afficher les détails de la transaction</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>Exporter les données de la transaction</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Valeurs séparées par des virgules (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmée</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Erreur lors de l'export</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Impossible d'écrire dans le fichier %1</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Intervalle :</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>à</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation>Envoi...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>LogiCoin version</source>
<translation>Version LogiCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Utilisation :</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or logicoind</source>
<translation>Envoyer commande à -server ou logicoind</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Lister les commandes</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Obtenir de l’aide pour une commande</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Options :</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: logicoin.conf)</source>
<translation>Spécifier le fichier de configuration (defaut: logicoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: logicoind.pid)</source>
<translation>Spécifier le fichier pid (defaut: logicoind.pid)
</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Spécifiez le fichier de portefeuille (dans le répertoire de données)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Spécifier le répertoire de données</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Définir la taille du tampon en mégaoctets (par défaut : 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Définir la taille du tampon en mégaoctets (par défaut : 100)</translation>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation>Écouter les connexions sur le <port> (default: 15714 or testnet: 25714)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Garder au plus <n> connexions avec les pairs (par défaut : 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Se connecter à un nœud pour obtenir des adresses de pairs puis se déconnecter</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Spécifier votre propre adresse publique</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Connexion à l'adresse fournie. Utiliser la notation [machine]:port pour les adresses IPv6</translation>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation>Stacker vos monnaies afin de soutenir le réseau et d'obtenir des intérêts (default: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Seuil de déconnexion des pairs de mauvaise qualité (par défaut : 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Délai en secondes de refus de reconnexion aux pairs de mauvaise qualité (par défaut : 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Une erreur est survenue lors du réglage du port RPC %u pour écouter sur IPv4 : %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>Détacher la base de donnée des blocks et adresses. Augmente le temps de fermeture (default: 0)</translation>
</message>
<message>
<location line="+109"/>
<source>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.</source>
<translation>Erreur: La transaction a été rejetée. Cela peut se produire si une quantité d'argent de votre portefeuille a déjà été dépensée, comme dans le cas où une copie du fichier wallet.dat aurait été utilisée afin d'effectuer des dépenses, à la place du fichier courant.</translation>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>Erreur: Cette transaction requière des frais minimum de %s a cause de son montant, de sa complexité ou de l'utilisation de fonds récemment reçus.</translation>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation>Écouter les connexions JSON-RPC sur le <port> (default: 15715 or testnet: 25715)</translation>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accepter les commandes de JSON-RPC et de la ligne de commande</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>Erreur: La création de cette transaction à échouée</translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Erreur: Portefeuille verrouillé, impossible d'effectuer cette transaction</translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>Importation du fichier blockchain</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation>Importation du fichier blockchain</translation>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Fonctionner en arrière-plan en tant que démon et accepter les commandes</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Utiliser le réseau de test</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accepter les connexions entrantes (par défaut : 1 si aucun -proxy ou -connect )</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Une erreur est survenue lors du réglage du port RPC %u pour écouter sur IPv6, retour à IPv4 : %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation>Erreur lors de l'initialisation de l'environnement de base de données %s! Afin de procéder à la récupération, une SAUVEGARDE DE CE REPERTOIRE est nécessaire, puis, supprimez le contenu entier de ce répertoire, à l'exception du fichier wallet.dat </translation>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Fixer la taille maximale d'un block en bytes (default: 27000)</translation>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Attention : -paytxfee est réglée sur un montant très élevé ! Il s'agit des frais de transaction que vous payerez si vous envoyez une transaction.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong LogiCoin will not work properly.</source>
<translation>Avertissement: Veuillez vérifier la date et l'heure de votre ordinateur. LogiCoin ne pourra pas fonctionner correctement si l'horloge est réglée de façon incorrecte</translation>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Avertissement : une erreur est survenue lors de la lecture de wallet.dat ! Toutes les clefs ont été lues correctement mais les données de transaction ou les entrées du carnet d'adresses sont peut-être incorrectes ou manquantes.</translation>
</message>
<message>
<location line="-18"/>
<source>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.</source>
<translation>Avertissement : wallet.dat corrompu, données récupérées ! Le fichier wallet.dat original a été enregistré en tant que wallet.{timestamp}.bak dans %s ; si votre solde ou transactions sont incorrects vous devriez effectuer une restauration depuis une sauvegarde.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Tenter de récupérer les clefs privées d'un wallet.dat corrompu</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Options de création de bloc :</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Ne se connecter qu'au(x) nœud(s) spécifié(s)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Découvrir sa propre adresse IP (par défaut : 1 lors de l'écoute et si aucun -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Échec de l'écoute sur un port quelconque. Utilisez -listen=0 si vous voulez ceci.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>Trouvez des peers utilisant DNS lookup (default: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation>Politique de synchronisation des checkpoints (default: strict)</translation>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation>Adresse -tor invalide: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>Montant incorrect pour -reservebalance=<montant></translation>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Tampon maximal de réception par « -connection » <n>*1 000 octets (par défaut : 5 000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Tampon maximal d'envoi par « -connection », <n>*1 000 octets (par défaut : 1 000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Se connecter uniquement aux nœuds du réseau <net> (IPv4, IPv6 ou Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Voir les autres informations de débogage. Implique toutes les autres options -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Voir les autres informations de débogage du réseau</translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation>Horodater les messages de debug</translation>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Options SSL : (voir le Wiki de Bitcoin pour les instructions de configuration du SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Sélectionner la version du proxy socks à utiliser (4-5, par défaut: 5)</translation>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Envoyer les informations de débogage/trace à la console au lieu du fichier debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Envoyer les informations de débogage/trace à la console au lieu du fichier debug.log</translation>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Fixer la taille maximale d'un block en bytes (default: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Définir la taille minimale de bloc en octets (par défaut : 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Réduire le fichier debug.log lors du démarrage du client (par défaut : 1 lorsque -debug n'est pas présent)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Spécifier le délai d'expiration de la connexion en millisecondes (par défaut : 5 000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation>Impossible de "signer" le checkpoint, mauvaise clef de checkpoint?
</translation>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Utiliser l'UPnP pour rediriger le port d'écoute (par défaut : 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Utiliser l'UPnP pour rediriger le port d'écoute (par défaut : 1 lors de l'écoute)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Utiliser un proxy pour atteindre les services cachés (défaut: équivalent à -proxy)</translation>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Nom d'utilisateur pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation>Vérification d'intégrité de la base de données...</translation>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation>ATTENTION : violation du checkpoint de synchronisation, mais ignorée!</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>Avertissement: Espace disque faible!</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Avertissement : cette version est obsolète, une mise à niveau est nécessaire !</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrompu, la récupération a échoué</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Mot de passe pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=logicoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "LogiCoin Alert" [email protected]
</source>
<translation>%s, vous devez définir un mot de passe rpc 'rpcpassword' au sein du fichier de configuration:
%s
Il est recommandé d'utiliser le mot de passe aléatoire suivant:
rpcuser=logicoinrpc
rpcpassword=%s
(il n'est pas nécessaire de retenir ce mot de passe)
Le nom d'utilisateur et le mot de passe doivent IMPERATIVEMENT être différents.
Si le fichier n'existe pas, il est nécessaire de le créer, avec les droit de lecture au propriétaire seulement.
Il est également recommandé d'utiliser l'option alertnotify afin d'être notifié des problèmes;
par exemple: alertnotify=echo %%s | mail -s "Alerte LogiCoin" [email protected]
</translation>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>Find peers using internet relay chat (default: 1) {0)?}</translation>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Synchronisation de l'horloge avec d'autres noeuds. Désactiver si votre serveur est déjà synchronisé avec le protocole NTP (défaut: 1)</translation>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>Lors de la création de transactions, ignore les entrées dont la valeur sont inférieures (défaut: 0.01)</translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Autoriser les connexions JSON-RPC depuis l'adresse IP spécifiée</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Envoyer des commandes au nœud fonctionnant sur <ip> (par défaut : 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Exécuter la commande lorsque le meilleur bloc change (%s dans cmd est remplacé par le hachage du bloc)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Exécuter la commande lorsqu'une transaction de portefeuille change (%s dans la commande est remplacée par TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Nécessite a confirmations pour modification (défaut: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation>Force les scripts de transaction à utiliser des opérateurs PUSH canoniques (défaut: 1)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Exécute une commande lorsqu'une alerte correspondante est reçue (%s dans la commande est remplacé par message)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Mettre à niveau le portefeuille vers le format le plus récent</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Régler la taille de la réserve de clefs sur <n> (par défaut : 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Réanalyser la chaîne de blocs pour les transactions de portefeuille manquantes</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Nombre de blocs à vérifier loes du démarrage (défaut: 2500, 0 = tous)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Niveau d'approfondissement de la vérification des blocs (0-6, default: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Importe les blocs d'un fichier externe blk000?.dat</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Utiliser OpenSSL (https) pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Fichier de certificat serveur (par défaut : server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clef privée du serveur (par défaut : server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Algorithmes de chiffrements acceptés (défaut: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Erreur: Portefeuille déverrouillé uniquement pour "stacking" , impossible d'effectuer cette transaction</translation>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation>AVERTISSEMENT: point de contrôle invalide! Les transactions affichées peuvent être incorrectes! Il est peut-être nécessaire d'effectuer une mise à jour, ou d'avertir les développeurs du projet.</translation>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Ce message d'aide</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Le portefeuille %s réside en dehors répertoire de données %s</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. LogiCoin is probably already running.</source>
<translation>Echec lors de la tentative de verrouillage des données du répertoire %s. L'application LogiCoin est probablement déjà en cours d'exécution</translation>
</message>
<message>
<location line="-98"/>
<source>LogiCoin</source>
<translation>LogiCoin</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Impossible de se lier à %s sur cet ordinateur (bind a retourné l'erreur %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation>Se connecter à travers un proxy socks</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Autoriser les recherches DNS pour -addnode, -seednode et -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Chargement des adresses…</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>Erreur de chargement du fichier blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Erreur lors du chargement de wallet.dat : portefeuille corrompu</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of LogiCoin</source>
<translation>Erreur de chargement du fichier wallet.dat: le portefeuille nécessite une version plus récente de l'application LogiCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart LogiCoin to complete</source>
<translation>le portefeuille nécessite d'être réédité : Merci de relancer l'application LogiCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Erreur lors du chargement de wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Adresse -proxy invalide : « %s »</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Réseau inconnu spécifié sur -onlynet : « %s »</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Version inconnue de serveur mandataire -socks demandée : %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Impossible de résoudre l'adresse -bind : « %s »</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Impossible de résoudre l'adresse -externalip : « %s »</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Montant invalide pour -paytxfee=<montant> : « %s »</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation>Erreur: Impossible de démarrer le noeud</translation>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>Envoi...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Montant invalide</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fonds insuffisants</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Chargement de l’index des blocs…</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Ajouter un nœud auquel se connecter et tenter de garder la connexion ouverte</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. LogiCoin is probably already running.</source>
<translation>Connexion au port %s impossible. L'application LogiCoin est probablement déjà en cours d'exécution</translation>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Frais par KB à ajouter à vos transactions sortantes</translation>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>Montant invalide pour -mininput=<amount>: '%s'</translation>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Chargement du portefeuille…</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Impossible de revenir à une version inférieure du portefeuille</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation>Impossible d'initialiser la "keypool"</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Impossible d'écrire l'adresse par défaut</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Nouvelle analyse…</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Chargement terminé</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Pour utiliser l'option %s</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Erreur</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Vous devez ajouter la ligne rpcpassword=<mot-de-passe> au fichier de configuration :
%s
Si le fichier n'existe pas, créez-le avec les droits de lecture seule accordés au propriétaire.</translation>
</message>
</context>
</TS><|fim▁end|> | <location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Formulaire</translation> |
<|file_name|>Item.java<|end_file_name|><|fim▁begin|>package com.github.messenger4j.send.message.template.receipt;
import static java.util.Optional.empty;
import java.net.URL;
import java.util.Optional;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.ToString;
/**
* @author Max Grabenhorst
* @since 1.0.0
*/<|fim▁hole|> private final String title;
private final float price;
private final Optional<String> subtitle;
private final Optional<Integer> quantity;
private final Optional<String> currency;
private final Optional<URL> imageUrl;
private Item(
String title,
float price,
Optional<String> subtitle,
Optional<Integer> quantity,
Optional<String> currency,
Optional<URL> imageUrl) {
this.title = title;
this.price = price;
this.subtitle = subtitle;
this.quantity = quantity;
this.currency = currency;
this.imageUrl = imageUrl;
}
public static Item create(@NonNull String title, float price) {
return create(title, price, empty(), empty(), empty(), empty());
}
public static Item create(
@NonNull String title,
float price,
@NonNull Optional<String> subtitle,
@NonNull Optional<Integer> quantity,
@NonNull Optional<String> currency,
@NonNull Optional<URL> imageUrl) {
return new Item(title, price, subtitle, quantity, currency, imageUrl);
}
public String title() {
return title;
}
public float price() {
return price;
}
public Optional<String> subtitle() {
return subtitle;
}
public Optional<Integer> quantity() {
return quantity;
}
public Optional<String> currency() {
return currency;
}
public Optional<URL> imageUrl() {
return imageUrl;
}
}<|fim▁end|> | @ToString
@EqualsAndHashCode
public final class Item {
|
<|file_name|>set.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This is pretty much entirely stolen from TreeSet, since BTreeMap has an identical interface
// to TreeMap
use core::prelude::*;
use core::cmp::Ordering::{self, Less, Greater, Equal};
use core::fmt::Debug;
use core::fmt;
use core::iter::{Peekable, Map, FromIterator};
use core::ops::{BitOr, BitAnd, BitXor, Sub};
use borrow::Borrow;
use btree_map::{BTreeMap, Keys};
use Bound;
// FIXME(conventions): implement bounded iterators
/// A set based on a B-Tree.
///
/// See BTreeMap's documentation for a detailed discussion of this collection's performance
/// benefits and drawbacks.
///
/// It is a logic error for an item to be modified in such a way that the item's ordering relative
/// to any other item, as determined by the `Ord` trait, changes while it is in the set. This is
/// normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
#[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct BTreeSet<T>{
map: BTreeMap<T, ()>,
}
/// An iterator over a BTreeSet's items.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Iter<'a, T: 'a> {
iter: Keys<'a, T, ()>
}
/// An owning iterator over a BTreeSet's items.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct IntoIter<T> {
iter: Map<::btree_map::IntoIter<T, ()>, fn((T, ())) -> T>
}
/// An iterator over a sub-range of BTreeSet's items.
pub struct Range<'a, T: 'a> {
iter: Map<::btree_map::Range<'a, T, ()>, fn((&'a T, &'a ())) -> &'a T>
}
/// A lazy iterator producing elements in the set difference (in-order).
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Difference<'a, T:'a> {
a: Peekable<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
/// A lazy iterator producing elements in the set symmetric difference (in-order).
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SymmetricDifference<'a, T:'a> {
a: Peekable<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
/// A lazy iterator producing elements in the set intersection (in-order).
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Intersection<'a, T:'a> {
a: Peekable<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
/// A lazy iterator producing elements in the set union (in-order).
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Union<'a, T:'a> {
a: Peekable<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
impl<T: Ord> BTreeSet<T> {
/// Makes a new BTreeSet with a reasonable choice of B.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut set: BTreeSet<i32> = BTreeSet::new();
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> BTreeSet<T> {
BTreeSet { map: BTreeMap::new() }
}
/// Makes a new BTreeSet with the given B.
///
/// B cannot be less than 2.
#[unstable(feature = "collections",
reason = "probably want this to be on the type, eventually")]
pub fn with_b(b: usize) -> BTreeSet<T> {
BTreeSet { map: BTreeMap::with_b(b) }
}
}
impl<T> BTreeSet<T> {
/// Gets an iterator over the BTreeSet's contents.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
///
/// for x in set.iter() {
/// println!("{}", x);
/// }
///
/// let v: Vec<_> = set.iter().cloned().collect();
/// assert_eq!(v, [1, 2, 3, 4]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter(&self) -> Iter<T> {
Iter { iter: self.map.keys() }
}
}
impl<T: Ord> BTreeSet<T> {
/// Constructs a double-ended iterator over a sub-range of elements in the set, starting
/// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
/// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
/// Thus range(Unbounded, Unbounded) will yield the whole collection.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BTreeSet;
/// use std::collections::Bound::{Included, Unbounded};
///
/// let mut set = BTreeSet::new();
/// set.insert(3);
/// set.insert(5);
/// set.insert(8);
/// for &elem in set.range(Included(&4), Included(&8)) {
/// println!("{}", elem);
/// }
/// assert_eq!(Some(&5), set.range(Included(&4), Unbounded).next());
/// ```
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn range<'a>(&'a self, min: Bound<&T>, max: Bound<&T>) -> Range<'a, T> {
fn first<A, B>((a, _): (A, B)) -> A { a }
let first: fn((&'a T, &'a ())) -> &'a T = first; // coerce to fn pointer
Range { iter: self.map.range(min, max).map(first) }
}
}
impl<T: Ord> BTreeSet<T> {
/// Visits the values representing the difference, in ascending order.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut a = BTreeSet::new();
/// a.insert(1);
/// a.insert(2);
///
/// let mut b = BTreeSet::new();
/// b.insert(2);
/// b.insert(3);
///
/// let diff: Vec<_> = a.difference(&b).cloned().collect();
/// assert_eq!(diff, [1]);
/// ```<|fim▁hole|> }
/// Visits the values representing the symmetric difference, in ascending order.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut a = BTreeSet::new();
/// a.insert(1);
/// a.insert(2);
///
/// let mut b = BTreeSet::new();
/// b.insert(2);
/// b.insert(3);
///
/// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
/// assert_eq!(sym_diff, [1, 3]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>)
-> SymmetricDifference<'a, T> {
SymmetricDifference{a: self.iter().peekable(), b: other.iter().peekable()}
}
/// Visits the values representing the intersection, in ascending order.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut a = BTreeSet::new();
/// a.insert(1);
/// a.insert(2);
///
/// let mut b = BTreeSet::new();
/// b.insert(2);
/// b.insert(3);
///
/// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
/// assert_eq!(intersection, [2]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>)
-> Intersection<'a, T> {
Intersection{a: self.iter().peekable(), b: other.iter().peekable()}
}
/// Visits the values representing the union, in ascending order.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut a = BTreeSet::new();
/// a.insert(1);
///
/// let mut b = BTreeSet::new();
/// b.insert(2);
///
/// let union: Vec<_> = a.union(&b).cloned().collect();
/// assert_eq!(union, [1, 2]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
Union{a: self.iter().peekable(), b: other.iter().peekable()}
}
/// Returns the number of elements in the set.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut v = BTreeSet::new();
/// assert_eq!(v.len(), 0);
/// v.insert(1);
/// assert_eq!(v.len(), 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn len(&self) -> usize { self.map.len() }
/// Returns true if the set contains no elements.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut v = BTreeSet::new();
/// assert!(v.is_empty());
/// v.insert(1);
/// assert!(!v.is_empty());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Clears the set, removing all values.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut v = BTreeSet::new();
/// v.insert(1);
/// v.clear();
/// assert!(v.is_empty());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn clear(&mut self) {
self.map.clear()
}
/// Returns `true` if the set contains a value.
///
/// The value may be any borrowed form of the set's value type,
/// but the ordering on the borrowed form *must* match the
/// ordering on the value type.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
/// assert_eq!(set.contains(&1), true);
/// assert_eq!(set.contains(&4), false);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
self.map.contains_key(value)
}
/// Returns `true` if the set has no elements in common with `other`.
/// This is equivalent to checking for an empty intersection.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
/// let mut b = BTreeSet::new();
///
/// assert_eq!(a.is_disjoint(&b), true);
/// b.insert(4);
/// assert_eq!(a.is_disjoint(&b), true);
/// b.insert(1);
/// assert_eq!(a.is_disjoint(&b), false);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
self.intersection(other).next().is_none()
}
/// Returns `true` if the set is a subset of another.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
/// let mut set = BTreeSet::new();
///
/// assert_eq!(set.is_subset(&sup), true);
/// set.insert(2);
/// assert_eq!(set.is_subset(&sup), true);
/// set.insert(4);
/// assert_eq!(set.is_subset(&sup), false);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
// Stolen from TreeMap
let mut x = self.iter();
let mut y = other.iter();
let mut a = x.next();
let mut b = y.next();
while a.is_some() {
if b.is_none() {
return false;
}
let a1 = a.unwrap();
let b1 = b.unwrap();
match b1.cmp(a1) {
Less => (),
Greater => return false,
Equal => a = x.next(),
}
b = y.next();
}
true
}
/// Returns `true` if the set is a superset of another.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
/// let mut set = BTreeSet::new();
///
/// assert_eq!(set.is_superset(&sub), false);
///
/// set.insert(0);
/// set.insert(1);
/// assert_eq!(set.is_superset(&sub), false);
///
/// set.insert(2);
/// assert_eq!(set.is_superset(&sub), true);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
other.is_subset(self)
}
/// Adds a value to the set. Returns `true` if the value was not already
/// present in the set.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut set = BTreeSet::new();
///
/// assert_eq!(set.insert(2), true);
/// assert_eq!(set.insert(2), false);
/// assert_eq!(set.len(), 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn insert(&mut self, value: T) -> bool {
self.map.insert(value, ()).is_none()
}
/// Removes a value from the set. Returns `true` if the value was
/// present in the set.
///
/// The value may be any borrowed form of the set's value type,
/// but the ordering on the borrowed form *must* match the
/// ordering on the value type.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let mut set = BTreeSet::new();
///
/// set.insert(2);
/// assert_eq!(set.remove(&2), true);
/// assert_eq!(set.remove(&2), false);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
self.map.remove(value).is_some()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> FromIterator<T> for BTreeSet<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BTreeSet<T> {
let mut set = BTreeSet::new();
set.extend(iter);
set
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> IntoIterator for BTreeSet<T> {
type Item = T;
type IntoIter = IntoIter<T>;
/// Gets an iterator for moving out the BtreeSet's contents.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
///
/// let v: Vec<_> = set.into_iter().collect();
/// assert_eq!(v, [1, 2, 3, 4]);
/// ```
fn into_iter(self) -> IntoIter<T> {
fn first<A, B>((a, _): (A, B)) -> A { a }
let first: fn((T, ())) -> T = first; // coerce to fn pointer
IntoIter { iter: self.map.into_iter().map(first) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> IntoIterator for &'a BTreeSet<T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Extend<T> for BTreeSet<T> {
#[inline]
fn extend<Iter: IntoIterator<Item=T>>(&mut self, iter: Iter) {
for elem in iter {
self.insert(elem);
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Default for BTreeSet<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> BTreeSet<T> {
BTreeSet::new()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
type Output = BTreeSet<T>;
/// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
/// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
///
/// let result = &a - &b;
/// let result_vec: Vec<_> = result.into_iter().collect();
/// assert_eq!(result_vec, [1, 2]);
/// ```
fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
self.difference(rhs).cloned().collect()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
type Output = BTreeSet<T>;
/// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
/// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
///
/// let result = &a ^ &b;
/// let result_vec: Vec<_> = result.into_iter().collect();
/// assert_eq!(result_vec, [1, 4]);
/// ```
fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
self.symmetric_difference(rhs).cloned().collect()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
type Output = BTreeSet<T>;
/// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
/// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
///
/// let result = &a & &b;
/// let result_vec: Vec<_> = result.into_iter().collect();
/// assert_eq!(result_vec, [2, 3]);
/// ```
fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
self.intersection(rhs).cloned().collect()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
type Output = BTreeSet<T>;
/// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
/// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
///
/// let result = &a | &b;
/// let result_vec: Vec<_> = result.into_iter().collect();
/// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
/// ```
fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
self.union(rhs).cloned().collect()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Debug> Debug for BTreeSet<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
impl<'a, T> Clone for Iter<'a, T> {
fn clone(&self) -> Iter<'a, T> { Iter { iter: self.iter.clone() } }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> DoubleEndedIterator for IntoIter<T> {
fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ExactSizeIterator for IntoIter<T> {}
impl<'a, T> Clone for Range<'a, T> {
fn clone(&self) -> Range<'a, T> { Range { iter: self.iter.clone() } }
}
impl<'a, T> Iterator for Range<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> { self.iter.next() }
}
impl<'a, T> DoubleEndedIterator for Range<'a, T> {
fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
}
/// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>,
short: Ordering, long: Ordering) -> Ordering {
match (x, y) {
(None , _ ) => short,
(_ , None ) => long,
(Some(x1), Some(y1)) => x1.cmp(y1),
}
}
impl<'a, T> Clone for Difference<'a, T> {
fn clone(&self) -> Difference<'a, T> {
Difference { a: self.a.clone(), b: self.b.clone() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: Ord> Iterator for Difference<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
loop {
match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
Less => return self.a.next(),
Equal => { self.a.next(); self.b.next(); }
Greater => { self.b.next(); }
}
}
}
}
impl<'a, T> Clone for SymmetricDifference<'a, T> {
fn clone(&self) -> SymmetricDifference<'a, T> {
SymmetricDifference { a: self.a.clone(), b: self.b.clone() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
loop {
match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
Less => return self.a.next(),
Equal => { self.a.next(); self.b.next(); }
Greater => return self.b.next(),
}
}
}
}
impl<'a, T> Clone for Intersection<'a, T> {
fn clone(&self) -> Intersection<'a, T> {
Intersection { a: self.a.clone(), b: self.b.clone() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: Ord> Iterator for Intersection<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
loop {
let o_cmp = match (self.a.peek(), self.b.peek()) {
(None , _ ) => None,
(_ , None ) => None,
(Some(a1), Some(b1)) => Some(a1.cmp(b1)),
};
match o_cmp {
None => return None,
Some(Less) => { self.a.next(); }
Some(Equal) => { self.b.next(); return self.a.next() }
Some(Greater) => { self.b.next(); }
}
}
}
}
impl<'a, T> Clone for Union<'a, T> {
fn clone(&self) -> Union<'a, T> {
Union { a: self.a.clone(), b: self.b.clone() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: Ord> Iterator for Union<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
loop {
match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
Less => return self.a.next(),
Equal => { self.b.next(); return self.a.next() }
Greater => return self.b.next(),
}
}
}
}<|fim▁end|> | #[stable(feature = "rust1", since = "1.0.0")]
pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
Difference{a: self.iter().peekable(), b: other.iter().peekable()} |
<|file_name|>path.py<|end_file_name|><|fim▁begin|>"""A zigzag path, a sequence of points."""
import collections
from .defuzz import Defuzzer
from .euclid import collinear, Point, Line, Segment, Bounds, EmptyBounds
from .postulates import adjacent_pairs, triples
class Path:
def __init__(self, points):
self.points = tuple(points)
def __repr__(self):
return f"<Path {list(self.points)}>"
def __eq__(self, other):
return self.points == other.points
def __hash__(self):
return hash(self.points)
def __lt__(self, other):
return self.points < other.points
def __len__(self):
return len(self.points)
def __iter__(self):
return iter(self.points)
def __getitem__(self, idx):
# Lots of code tries to get the endpoints by index. Allow that but
# nothing else.
assert idx in [0, -1]
return self.points[idx]
@property
def closed(self):
"""Does the path loop? Start and end are the same points."""
return self.points[0] == self.points[-1]
def length(self):
"""The euclidean distance along the path."""
return sum(p1.distance(p2) for p1, p2 in adjacent_pairs(self.points))
def ends(self):
yield self.points[0]
yield self.points[-1]
def bounds(self):
"""What is the `Bounds` for this path?"""
return Bounds.points(self.points)
def segments(self):
for p1, p2 in adjacent_pairs(self.points):
yield Segment(tuple(p1), tuple(p2))
def transform(self, xform):
"""Transform the Path through the affine `xform`."""
return Path(pt.transform(xform) for pt in self)
def any_collinear(self):
"""Are any of the parts of this path collinear?"""
return any(collinear(*them) for them in triples(self.points))
def clean(self):
"""Remove unneeded points from a path."""
if len(self.points) <= 2:
return self
# Points are unneeded if they are collinear with their neighbors.
new_points = []
if not self.closed:
new_points.append(self.points[0])
for a, b, c in triples(self.points):
if not collinear(a, b, c):
new_points.append(b)
if self.closed:
new_points.append(new_points[0])
else:
new_points.append(self.points[-1])
return Path(new_points)
def reversed(self):
return Path(self.points[::-1])
def draw(self, ctx, append=False, reverse=False):
points = self.points
if reverse:
points = points[::-1]
(ctx.line_to if append else ctx.move_to)(*points[0])
for pt in points[1:-1]:
ctx.line_to(*pt)
if self.closed:
ctx.close_path()
else:
ctx.line_to(*points[-1])
def offset_path(self, offset):
lines = []
for p1, p2 in adjacent_pairs(self.points):
lines.append(Line(p1, p2).offset(offset))
points = []
if self.closed:
p0 = lines[-1].intersect(lines[0])
points.append(p0)
else:
points.append(lines[0].p1)
for l1, l2 in adjacent_pairs(lines):
points.append(l1.intersect(l2))
if self.closed:
points.append(p0)
else:
points.append(lines[-1].p2)
return Path(points)
def defuzz(self, defuzz):
return Path([Point(*defuzz(pt)) for pt in self.points])
def perturb(self, jitter):
"""Jostle around all the points in the path."""
pts = self.points
if self.closed:
pts = pts[:-1]
pts = [pt.perturb(jitter) for pt in pts]
if self.closed:
pts.append(pts[0])
return Path(pts)
def penultimate(self, point):
"""The second-to-last point from whichever end ends with `point`."""
if self.points[0] == point:
return self.points[1]
else:
assert self.points[-1] == point
return self.points[-2]
def join(self, p2):
"""Join `self` and `p2` together by their common endpoint."""
p1 = self.points
p2 = p2.points
# Find the ends that are the same point. Rearrange p1 and p2 so that p1+p2
# is the join we need, and remove the duplicate point at p2[0].
if p1[-1] == p2[0]:
p2 = p2[1:]
elif p1[-1] == p2[-1]:
p2 = p2[-2::-1]
elif p1[0] == p2[-1]:
p1, p2 = p2, p1[1:]
elif p1[0] == p2[0]:
p1, p2 = p1[::-1], p2[1:]
else:
return None
# If the join would have a redundant point because of three collinear
# points in a row, then remove the middle point.
if collinear(p1[-2], p1[-1], p2[0]):
p1 = p1[:-1]
return Path(p1 + p2)
def trim(self, end, trimmers):
"""Trim one end of path where trimmers (paths) cross it."""
points = list(self.points)<|fim▁hole|> if end == 0:
points = [cuts[-1]] + points[1:]
else:
points = points[:-1] + [cuts[0]]
return Path(points)
else:
return self
def canonicalize(self):
"""Produce an equivalent canonical path."""
if self.closed:
points = list(self.points[:-1])
points = min((points[i:]+points[:i])[::s] for i in range(len(points)) for s in [1, -1])
points.append(points[0])
return Path(points)
else:
return Path(min(self.points, self.points[::-1]))
def defuzz_paths(paths):
defuzz = Defuzzer().defuzz
return [path.defuzz(defuzz) for path in paths]
def combine_paths(paths):
paths = defuzz_paths(paths)
pm = collections.defaultdict(list)
for path in paths:
for end in path.ends():
pm[end].append(path)
combined = []
used = set()
for path in paths:
if id(path) in used:
continue
for end in [0, -1]:
while True:
target = path[end]
possibilities = pm[target]
possibilities = [p for p in possibilities if id(p) not in used]
if not possibilities:
break
other = best_join(path, target, possibilities)
if other is not None:
used.add(id(path))
used.add(id(other))
path = path.join(other)
pm[path[0]].append(path)
pm[path[-1]].append(path)
else:
break
used.add(id(path))
combined.append(path.clean())
return combined
def draw_paths(paths, ctx):
for path in paths:
path.draw(ctx)
def best_join(path, join_point, possibilities):
others = [p for p in possibilities if p != path]
# If there's only one other path, then join to that one.
if len(others) == 1:
return others[0]
# If there's more than one, find one we are collinear with.
path_pen = path.penultimate(join_point)
for other in others:
other_pen = other.penultimate(join_point)
if collinear(path_pen, join_point, other_pen):
return other
return None
def show_path(path):
if path is None:
return "None"
return f"Path[{path[0]}..{len(path)}..{path[-1]}]@{id(path)}"
def show_paths(paths):
ret = "[\n"
for path in paths:
ret += f" {show_path(path)}\n"
ret += "]"
return ret
def paths_bounds(paths):
"""Return the `Bounds` of the paths."""
bounds = EmptyBounds()
for path in paths:
bounds |= path.bounds()
return bounds
def clip_paths(paths, bounds):
"""Return the paths that overlap the bounds."""
return [path for path in paths if path.bounds().overlap(bounds)]
def equal_path(path1, path2):
return path1.canonicalize() == path2.canonicalize()
def canonicalize_paths(paths):
"""Canonicalize a list of paths."""
paths = [p.canonicalize() for p in paths]
paths.sort()
return paths
def equal_paths(paths1, paths2):
"""Are the paths in paths1 and paths2 equivalent?"""
return canonicalize_paths(paths1) == canonicalize_paths(paths2)
def paths_length(paths):
return sum(path.length() for path in paths)
def seg_path_intersections(segment, path):
"""Return a list of all the points where segment and path intersect."""
for pseg in path.segments():
pt = segment.intersect(pseg)
if pt is not None:
yield pt
def perturb_paths(paths, jitter):
"""Perturb all of the points in all of the path."""
return [path.perturb(jitter) for path in paths]<|fim▁end|> | seg = Segment(*points[[None, -2][end]:[2, None][end]])
cuts = [pt for t in trimmers for pt in seg_path_intersections(seg, t)]
if cuts:
cuts = seg.sort_along(cuts) |
<|file_name|>routes.js<|end_file_name|><|fim▁begin|><|fim▁hole|>routes.$inject = ['$stateProvider', '$urlRouterProvider'];
export default function routes($stateProvider, $urlRouterProvider){
$stateProvider.state('main.item', {
url: '/:id/item',
template: template,
controllerAs: 'ctrl',
controller: controller
})
}<|fim▁end|> | import controller from './controller';
import template from './template.pug';
|
<|file_name|>abstractMethodDocStringIndentationPreserved.py<|end_file_name|><|fim▁begin|>class A:
pass
class B(A):<|fim▁hole|> """
Parameters:
x (int): number
"""
return x<|fim▁end|> | def m(self, x): |
<|file_name|>ccloud_lib.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Copyright 2020 Confluent Inc.
#
# 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.
#
# =============================================================================
#
# Helper module
#
# =============================================================================
import argparse, sys
from confluent_kafka import avro, KafkaError
from confluent_kafka.admin import AdminClient, NewTopic
from uuid import uuid4
#import certifi
name_schema = """
{
"namespace": "io.confluent.examples.clients.cloud",
"name": "Name",
"type": "record",
"fields": [
{"name": "name", "type": "string"}
]
}
"""
class Name(object):
"""
Name stores the deserialized Avro record for the Kafka key.
"""
# Use __slots__ to explicitly declare all data members.
__slots__ = ["name", "id"]
def __init__(self, name=None):
self.name = name
# Unique id used to track produce request success/failures.
# Do *not* include in the serialized object.
self.id = uuid4()
@staticmethod
def dict_to_name(obj, ctx):
return Name(obj['name'])
@staticmethod
def name_to_dict(name, ctx):
return Name.to_dict(name)
def to_dict(self):
"""
The Avro Python library does not support code generation.
For this reason we must provide a dict representation of our class for serialization.
"""
return dict(name=self.name)
# Schema used for serializing Count class, passed in as the Kafka value
count_schema = """
{
"namespace": "io.confluent.examples.clients.cloud",
"name": "Count",
"type": "record",
"fields": [
{"name": "count", "type": "int"}
]
}
"""
class Count(object):
"""
Count stores the deserialized Avro record for the Kafka value.
"""
# Use __slots__ to explicitly declare all data members.
__slots__ = ["count", "id"]
def __init__(self, count=None):
self.count = count
# Unique id used to track produce request success/failures.
# Do *not* include in the serialized object.
self.id = uuid4()
@staticmethod
def dict_to_count(obj, ctx):
return Count(obj['count'])
@staticmethod
def count_to_dict(count, ctx):
return Count.to_dict(count)
def to_dict(self):
"""
The Avro Python library does not support code generation.
For this reason we must provide a dict representation of our class for serialization.
"""
return dict(count=self.count)<|fim▁hole|>
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(
description="Confluent Python Client example to produce messages \
to Confluent Cloud")
parser._action_groups.pop()
required = parser.add_argument_group('required arguments')
required.add_argument('-f',
dest="config_file",
help="path to Confluent Cloud configuration file",
required=True)
required.add_argument('-t',
dest="topic",
help="topic name",
required=True)
args = parser.parse_args()
return args
def read_ccloud_config(config_file):
"""Read Confluent Cloud configuration for librdkafka clients"""
conf = {}
with open(config_file) as fh:
for line in fh:
line = line.strip()
if len(line) != 0 and line[0] != "#":
parameter, value = line.strip().split('=', 1)
conf[parameter] = value.strip()
#conf['ssl.ca.location'] = certifi.where()
return conf
def pop_schema_registry_params_from_config(conf):
"""Remove potential Schema Registry related configurations from dictionary"""
conf.pop('schema.registry.url', None)
conf.pop('basic.auth.user.info', None)
conf.pop('basic.auth.credentials.source', None)
return conf
def create_topic(conf, topic):
"""
Create a topic if needed
Examples of additional admin API functionality:
https://github.com/confluentinc/confluent-kafka-python/blob/master/examples/adminapi.py
"""
admin_client_conf = pop_schema_registry_params_from_config(conf.copy())
a = AdminClient(admin_client_conf)
fs = a.create_topics([NewTopic(
topic,
num_partitions=1,
replication_factor=3
)])
for topic, f in fs.items():
try:
f.result() # The result itself is None
print("Topic {} created".format(topic))
except Exception as e:
# Continue if error code TOPIC_ALREADY_EXISTS, which may be true
# Otherwise fail fast
if e.args[0].code() != KafkaError.TOPIC_ALREADY_EXISTS:
print("Failed to create topic {}: {}".format(topic, e))
sys.exit(1)<|fim▁end|> | |
<|file_name|>SMPPSessionState.java<|end_file_name|><|fim▁begin|>/*
* 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.
*
*/
package org.jsmpp.session.state;
import java.io.IOException;
import org.jsmpp.bean.Command;
import org.jsmpp.session.ResponseHandler;
import org.jsmpp.session.SMPPSessionContext;
/**
* This class provides the interface to response to every incoming SMPP Command.
* How the response behavior is, depends on its state, or the
* implementation of this class.
*
* @author uudashr
* @version 1.0
* @since 2.0
*/
public interface SMPPSessionState extends GenericSMPPSessionState {
SMPPSessionState OPEN = new SMPPSessionOpen();
SMPPSessionState BOUND_RX = new SMPPSessionBoundRX();
SMPPSessionState BOUND_TX = new SMPPSessionBoundTX();
SMPPSessionState BOUND_TRX = new SMPPSessionBoundTRX();
SMPPSessionState UNBOUND = new SMPPSessionUnbound();
SMPPSessionState CLOSED = new SMPPSessionClosed();
/**
* Process the bind response command.
*<|fim▁hole|> * @param responseHandler is the session handler.
* @throws IOException if an input or output error occurred.
*/
void processBindResp(SMPPSessionContext sessionContext, Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the submit short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the response handler.
* @throws IOException if there is an I/O error found.
*/
void processSubmitSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process a submit multiple message response.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the response handler.
* @throws IOException if there is an I/O error found.
*/
void processSubmitMultiResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the query short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processQuerySmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the deliver short message request command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processDeliverSm(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the cancel short message request command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processCancelSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the replace short message request command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processReplaceSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the alert notification request command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
*/
void processAlertNotification(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler);
/**
* Process the broadcast short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete broadcast_sm PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processBroadcastSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the cancel broadcast short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete cancel_broadcast_sm PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processCancelBroadcastSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the query broadcast short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete query_broadcast_sm PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processQueryBroadcastSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
}<|fim▁end|> | * @param sessionContext the session context.
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU. |
<|file_name|>GhostGlassPane.java<|end_file_name|><|fim▁begin|>package helper;
import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class GhostGlassPane extends JPanel
{
private AlphaComposite composite;
private BufferedImage dragged = null;
private Point location = new Point(0, 0);
<|fim▁hole|> public GhostGlassPane()
{
setOpaque(false);
composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
}
public void setImage(BufferedImage dragged)
{
this.dragged = dragged;
}
public void setPoint(Point location)
{
this.location = location;
}
public void paintComponent(Graphics g)
{
if (dragged == null)
return;
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(composite);
g2.drawImage(dragged,
(int) (location.getX() - (dragged.getWidth(this) / 2)),
(int) (location.getY() - (dragged.getHeight(this) / 2)),
null);
}
}<|fim▁end|> | |
<|file_name|>test_run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from preggy import expect
import click
from click.testing import CliRunner
from terrible.run import compile_template
from tests.base import TestCase
import os
class CompileTemplateTestCase(TestCase):
def test_compile_template(self):
base_dir = os.path.dirname(os.path.realpath(__file__)) + "/../"
template_path = "%stests_resources/" % base_dir
template = "ansible-inventory.j2"
tfstate = "%stests_resources/terraform.tfstate" % base_dir
inventory_output = "%stests_resources/test_output" % base_dir
# Empty any previous test output
open(inventory_output, 'w').close()
runner = CliRunner()
result = runner.invoke(compile_template, [
'--template-path', template_path,
'--template', template,
'--tfstate', tfstate,
'--inventory-output', inventory_output])
expect(hasattr(runner, 'exception')).to_equal(False)
expect(result.exit_code).to_equal(0)
output = open(inventory_output).read()
expect(output).to_include("1.2.3.4")
def test_missing_required_params(self):
base_dir = os.path.dirname(os.path.realpath(__file__)) + "/../"
template_path = "%stests_resources/" % base_dir
template = "ansible-inventory.j2"
tfstate = "%stests_resources/terraform.tfstate" % base_dir
inventory_output = "%stests_resources/test_output" % base_dir
runner = CliRunner()
# Missing --template-path arg<|fim▁hole|> '--tfstate', tfstate,
'--inventory-output', inventory_output])
expect(result.exit_code).to_be_greater_than(0)
# Missing --template arg
result = runner.invoke(compile_template, [
'--template-path', template_path,
'--tfstate', tfstate,
'--inventory-output', inventory_output])
expect(result.exit_code).to_be_greater_than(0)
# Missing --tfstate arg
result = runner.invoke(compile_template, [
'--template-path', template_path,
'--template', template,
'--inventory-output', inventory_output])
expect(result.exit_code).to_be_greater_than(0)
# Missing --inventory-output arg
result = runner.invoke(compile_template, [
'--template-path', template_path,
'--template', template,
'--tfstate', tfstate])
expect(result.exit_code).to_be_greater_than(0)
# Give a file instead of a directory for template path
result = runner.invoke(compile_template, [
'--template-path', tfstate])
expect(result.exit_code).to_be_greater_than(0)
# Give a path instead of an acutal template for --template
result = runner.invoke(compile_template, [
'--template-path', template_path,
'--template', template_path])
expect(result.exit_code).to_be_greater_than(0)
# Give an inviald path for tfstate
result = runner.invoke(compile_template, [
'--template-path', template_path,
'--template', template,
'--tfstate', tfstate + "blahblahdoesnotexist",
'--inventory-output', inventory_output])
expect(result.exit_code).to_be_greater_than(0)<|fim▁end|> | result = runner.invoke(compile_template, [
'--template', template, |
<|file_name|>server-selector.service.ts<|end_file_name|><|fim▁begin|>import { injectable, inject } from "inversify";
import { TYPES } from "../ioc/types";
const cacheKey = "AleksaDiscordServerSelection";
@injectable()
export class ServerSelectorService {
constructor(
@inject(TYPES.IConfig) private _config: IConfig,
@inject(TYPES.Logger) private _logger: ILogger,
@inject(TYPES.IBasicCache) private _cache: IBasicCache,
) { }
/**
* Change to the new server
* @param name
*/
public async changeServer(name: string): Promise<void> {
const servers: IServer[] = this._config.app.aleksa.discord.servers;
const matches = servers.filter(s => s.name.indexOf(name) > -1);
const selection = matches.length > 0
? matches[0]
: servers[0];
this._logger.info(`Changing server to ${name}`);
// Ensure never expired
this._cache.set(cacheKey, JSON.stringify(selection), 0);
}
/**
* Get the current selected server
*/
public async getServer(): Promise<IServer> {
if(await this._cache.has(cacheKey)) {
return JSON.parse(await this._cache.get(cacheKey)) as IServer;
}
return this._config.app.aleksa.discord.servers[0] as IServer;
}
}<|fim▁hole|> name: string;
guildId: string;
channelId: string;
userId: string;
}<|fim▁end|> |
export interface IServer { |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.