text stringlengths 2 1.04M | meta dict |
|---|---|
'use strict';
jest.autoMockOff();
var number = require('../number');
var pFalse = function() {
throw new Error('Promise must be rejected');
};
describe('validators / number / is()', function() {
pit('success with number (string)', function() {
var is = number.is();
return is('1234');
});
pit('success with number', function() {
var is = number.is();
return is(1234);
});
pit('success with empty', function() {
var is = number.is();
return is('');
});
pit('success with null', function() {
var is = number.is();
return is(null);
});
pit('success with undefined', function() {
var is = number.is();
return is(undefined);
});
pit('fail with char', function() {
var is = number.is();
return is('a').then(pFalse, function(err) {
expect(err.code).toBe('number.is');
});
});
pit('fail with mixed numbers and char', function() {
var is = number.is();
return is('12a').then(pFalse, function(err) {
expect(err.code).toBe('number.is');
});
});
pit('fail with spaces', function() {
var is = number.is();
return is('12 34').then(pFalse, function(err) {
expect(err.code).toBe('number.is');
});
});
});
describe('validators / number / max(limit)', function() {
pit('success with number (string)', function() {
var max = number.max(15);
return max('14');
});
pit('success with number', function() {
var max = number.max(15);
return max(14);
});
pit('success with empty', function() {
var max = number.max(15);
return max('');
});
pit('success with null', function() {
var max = number.max(15);
return max(null);
});
pit('success with undefined', function() {
var max = number.max(15);
return max(undefined);
});
it('fail when the limit is not a number', function() {
expect(function() {
number.max('char');
}).toThrow(new Error('limit must be a number'));
});
pit('fail with number too high (string)', function() {
var max = number.max(15);
return max('16').then(pFalse, function(err) {
expect(err.code).toBe('number.max');
});
});
pit('fail with number too high', function() {
var max = number.max(15);
return max(16).then(pFalse, function(err) {
expect(err.code).toBe('number.max');
});
});
});
describe('validators / number / min(limit)', function() {
pit('success with number (string)', function() {
var min = number.min(15);
return min('16');
});
pit('success with number', function() {
var min = number.min(15);
return min(16);
});
pit('success with empty', function() {
var min = number.min(15);
return min('');
});
pit('success with null', function() {
var min = number.min(15);
return min(null);
});
pit('success with undefined', function() {
var min = number.min(15);
return min(undefined);
});
it('fail when the limit is not a number', function() {
expect(function() {
number.min('char');
}).toThrow(new Error('limit must be a number'));
});
pit('fail with number too low (string)', function() {
var min = number.min(15);
return min('14').then(pFalse, function(err) {
expect(err.code).toBe('number.min');
});
});
pit('fail with number too low', function() {
var min = number.min(15);
return min(14).then(pFalse, function(err) {
expect(err.code).toBe('number.min');
});
});
});
describe('validators / number / equals(seed)', function() {
pit('success with number (string)', function() {
var equals = number.equals(15);
return equals('15');
});
pit('success with number', function() {
var equals = number.equals(15);
return equals(15);
});
pit('success with empty', function() {
var equals = number.equals(15);
return equals('');
});
pit('success with null', function() {
var equals = number.equals(15);
return equals(null);
});
pit('success with undefined', function() {
var equals = number.equals(15);
return equals(undefined);
});
it('fail when the seed is not a number', function() {
expect(function() {
number.equals('char');
}).toThrow(new Error('seed must be a number'));
});
pit('fail with number not equals (string)', function() {
var equals = number.equals(15);
return equals('14').then(pFalse, function(err) {
expect(err.code).toBe('number.equals');
});
});
pit('fail with number not equals', function() {
var equals = number.equals(15);
return equals(14).then(pFalse, function(err) {
expect(err.code).toBe('number.equals');
});
});
}); | {
"content_hash": "62cc68a810b95b4eb670c69479880226",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 60,
"avg_line_length": 25.584158415841586,
"alnum_prop": 0.5272832817337462,
"repo_name": "tsunammis/react-form-validator",
"id": "c87716c972f8c1ccb230b8822bb0ee95f866c03d",
"size": "5168",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/validators/__tests__/number-test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "76935"
},
{
"name": "Shell",
"bytes": "1441"
}
],
"symlink_target": ""
} |
FROM ubuntu:latest
MAINTAINER nealhardesty@yahoo.com
RUN apt-get update -y && apt-get install -y build-essential ruby ruby-dev libncurses5-dev && rm -rf /var/lib/apt/lists/*
ADD . /redsnow
WORKDIR /redsnow
RUN gem install bundler
RUN bundle install
CMD ./redsnow.rb
| {
"content_hash": "f2a658d2d77af03fb58a23bc2d7b69f3",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 120,
"avg_line_length": 29.666666666666668,
"alnum_prop": 0.7677902621722846,
"repo_name": "nealhardesty/redsnow",
"id": "f59424e65ad4a73e56d22929ae4cb02811b46b27",
"size": "267",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "3406"
},
{
"name": "Shell",
"bytes": "92"
}
],
"symlink_target": ""
} |
using namespace std;
QList<qint64> CoinControlDialog::payAmounts;
CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
CoinControlDialog::CoinControlDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::CoinControlDialog),
model(0)
{
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();
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);
QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this);
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(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority()));
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->labelCoinControlPriority->addAction(clipboardPriorityAction);
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()));
ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100);
ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170);
ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 290);
ui->treeWidget->setColumnWidth(COLUMN_DATE, 110);
ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100);
ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100);
ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64 in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_DATE_INT64, true); // store date int64 in this column, but dont show it
// default view is sorted by amount desc
sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder);
}
CoinControlDialog::~CoinControlDialog()
{
delete ui;
}
void CoinControlDialog::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel() && model->getAddressTableModel())
{
updateView();
updateLabelLocked();
CoinControlDialog::updateLabels(model, this);
}
}
// helper function str_pad
QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding)
{
while (s.length() < nPadLength)
s = sPadding + s;
return s;
}
// 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(uint256(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(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(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
updateLabelLocked();
}
// context menu action: unlock coin
void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256(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(" ")));
}
// copy label "After fee" to clipboard
void CoinControlDialog::clipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")));
}
// copy label "Bytes" to clipboard
void CoinControlDialog::clipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text());
}
// copy label "Priority" to clipboard
void CoinControlDialog::clipboardPriority()
{
GUIUtil::setClipboard(ui->labelCoinControlPriority->text());
}
// copy label "Low output" 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(" ")));
}
// treeview: sort
void CoinControlDialog::sortView(int column, Qt::SortOrder order)
{
sortColumn = column;
sortOrder = order;
ui->treeWidget->sortItems(column, order);
ui->treeWidget->header()->setSortIndicator(getMappedColumn(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(getMappedColumn(sortColumn), sortOrder);
}
else
{
logicalIndex = getMappedColumn(logicalIndex, false);
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(uint256(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: this is a temporary qt5 fix: when clicking a parent node in tree mode, the parent node
// including all childs are partially selected. But the parent node should be fully selected
// as well as the childs. Childs should never be partially selected in the first place.
// Please remove this ugly fix, once the bug is solved upstream.
#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
}
// return human readable label for priority number
QString CoinControlDialog::getPriorityLabel(double dPriority)
{
if (CTransaction::AllowFree(dPriority)) // at least medium
{
if (CTransaction::AllowFree(dPriority / 1000000)) return tr("highest");
else if (CTransaction::AllowFree(dPriority / 100000)) return tr("higher");
else if (CTransaction::AllowFree(dPriority / 10000)) return tr("high");
else if (CTransaction::AllowFree(dPriority / 1000)) return tr("medium-high");
else return tr("medium");
}
else
{
if (CTransaction::AllowFree(dPriority * 10)) return tr("low-medium");
else if (CTransaction::AllowFree(dPriority * 100)) return tr("low");
else if (CTransaction::AllowFree(dPriority * 1000)) return tr("lower");
else return tr("lowest");
}
}
// shows count of locked unspent outputs
void CoinControlDialog::updateLabelLocked()
{
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
qint64 nPayAmount = 0;
bool fLowOutput = false;
bool fDust = false;
unsigned int nQuantityDust = 0;
CTransaction txDummy;
foreach(const qint64 &amount, CoinControlDialog::payAmounts)
{
nPayAmount += amount;
if (amount > 0)
{
if (amount < CENT) {
fLowOutput = true;
nQuantityDust++;
}
CTxOut txout(amount, (CScript)vector<unsigned char>(24, 0));
txDummy.vout.push_back(txout);
if (txout.IsDust())
fDust = true;
}
}
QString sPriorityLabel = tr("none");
int64 nAmount = 0;
int64 nPayFee = 0;
int64 nAfterFee = 0;
int64 nChange = 0;
unsigned int nBytes = 0;
unsigned int nBytesInputs = 0;
double dPriority = 0;
double dPriorityInputs = 0;
unsigned int nQuantity = 0;
int nQuantityUncompressed = 0;
vector<COutPoint> vCoinControl;
vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
BOOST_FOREACH(const COutput& out, vOutputs)
{
// unselect already spent, very unlikely scenario, this could happen when selected are spent elsewhere, like rpc or another computer
if (out.tx->IsSpent(out.i))
{
uint256 txhash = out.tx->GetHash();
COutPoint outpt(txhash, out.i);
coinControl->UnSelect(outpt);
continue;
}
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->vout[out.i].nValue;
// Priority
dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1);
// Bytes
CTxDestination address;
if(ExtractDestination(out.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);
if (!pubkey.IsCompressed())
nQuantityUncompressed++;
}
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
// Priority
dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority)
sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority);
// Fee
int64 nFee = nTransactionFee * (1 + (int64)nBytes / 1000);
// Min Fee
int64 nMinFee = CTransaction::nMinTxFee * (1 + (int64)nBytes / 1000) + CTransaction::nMinTxFee * nQuantityDust;
if (CTransaction::AllowFree(dPriority) && nBytes < 5000)
nMinFee = 0;
nPayFee = max(nFee, nMinFee);
if (nPayAmount > 0)
{
nChange = nAmount - nPayFee - nPayAmount;
// if sub-cent change is required, the fee must be raised to at least CTransaction::nMinTxFee
if (nPayFee < CTransaction::nMinTxFee && nChange > 0 && nChange < CENT)
{
if (nChange < CTransaction::nMinTxFee) // change < 0.0001 => simply move all change to fees
{
nPayFee += nChange;
nChange = 0;
}
else
{
nChange = nChange + nPayFee - CTransaction::nMinTxFee;
nPayFee = CTransaction::nMinTxFee;
}
}
// Never create dust outputs; if we would, just add the dust to the fee.
if (nChange > 0 && nChange < CENT)
{
CTxOut txout(nChange, (CScript)vector<unsigned char>(24, 0));
if (txout.IsDust())
{
nPayFee += nChange;
nChange = 0;
}
}
if (nChange == 0)
nBytes -= 34;
}
// after fee
nAfterFee = nAmount - nPayFee;
if (nAfterFee < 0)
nAfterFee = 0;
}
// actually update labels
int nDisplayUnit = BitcoinUnits::UMO;
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 *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority");
QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput");
QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange");
// enable/disable "low output" 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) ? "~" : "") + QString::number(nBytes)); // Bytes
l6->setText(sPriorityLabel); // Priority
l7->setText((fLowOutput ? (fDust ? tr("Dust") : tr("yes")) : tr("no"))); // Low Output / Dust
l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change
// turn labels "red"
l5->setStyleSheet((nBytes >= 1000) ? "color:red;" : ""); // Bytes >= 1000
l6->setStyleSheet((dPriority > 0 && !CTransaction::AllowFree(dPriority)) ? "color:red;" : ""); // Priority < "medium"
l7->setStyleSheet((fLowOutput) ? "color:red;" : ""); // Low Output = "yes"
l8->setStyleSheet((nChange > 0 && nChange < CENT) ? "color:red;" : ""); // Change < 0.01UMO
// tool tips
QString toolTip1 = tr("This label turns red, if the transaction size is greater than 1000 bytes.") + "<br /><br />";
toolTip1 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CTransaction::nMinTxFee)) + "<br /><br />";
toolTip1 += tr("Can vary +/- 1 byte per input.");
QString toolTip2 = tr("Transactions with higher priority are more likely to get included into a block.") + "<br /><br />";
toolTip2 += tr("This label turns red, if the priority is smaller than \"medium\".") + "<br /><br />";
toolTip2 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CTransaction::nMinTxFee));
QString toolTip3 = tr("This label turns red, if any recipient receives an amount smaller than %1.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)) + "<br /><br />";
toolTip3 += tr("This means a fee of at least %1 is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CTransaction::nMinTxFee)) + "<br /><br />";
toolTip3 += tr("Amounts below 0.546 times the minimum relay fee are shown as dust.");
QString toolTip4 = tr("This label turns red, if the change is smaller than %1.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)) + "<br /><br />";
toolTip4 += tr("This means a fee of at least %1 is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CTransaction::nMinTxFee));
l5->setToolTip(toolTip1);
l6->setToolTip(toolTip2);
l7->setToolTip(toolTip3);
l8->setToolTip(toolTip4);
dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip());
dialog->findChild<QLabel *>("labelCoinControlPriorityText") ->setToolTip(l6->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();
map<QString, vector<COutput> > mapCoins;
model->listCoins(mapCoins);
BOOST_FOREACH(PAIRTYPE(QString, vector<COutput>) coins, mapCoins)
{
QTreeWidgetItem *itemWalletAddress = new QTreeWidgetItem();
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);
}
int64 nSum = 0;
double dPrioritySum = 0;
int nChildren = 0;
int nInputSum = 0;
BOOST_FOREACH(const COutput& out, coins.second)
{
int nInputSize = 0;
nSum += out.tx->vout[out.i].nValue;
nChildren++;
QTreeWidgetItem *itemOutput;
if (treeMode) itemOutput = new QTreeWidgetItem(itemWalletAddress);
else itemOutput = new QTreeWidgetItem(ui->treeWidget);
itemOutput->setFlags(flgCheckbox);
itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
// address
CTxDestination outputAddress;
QString sAddress = "";
if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress))
{
sAddress = CBitcoinAddress(outputAddress).ToString().c_str();
// 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);
CPubKey pubkey;
CKeyID *keyid = boost::get<CKeyID>(&outputAddress);
if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed())
nInputSize = 29; // 29 = 180 - 151 (public key is 180 bytes, priority free area is 151 bytes)
}
// 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->vout[out.i].nValue));
itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); // padding so that sorting works correctly
// date
itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setText(COLUMN_DATE_INT64, strPad(QString::number(out.tx->GetTxTime()), 20, " "));
// confirmations
itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " "));
// priority
double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10
itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority));
itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64)dPriority), 20, " "));
dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth+1);
nInputSum += nInputSize;
// transaction hash
uint256 txhash = out.tx->GetHash();
itemOutput->setText(COLUMN_TXHASH, txhash.GetHex().c_str());
// 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, QIcon(":/icons/lock_closed"));
}
// set checkbox
if (coinControl->IsSelected(txhash, out.i))
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
// amount
if (treeMode)
{
dPrioritySum = dPrioritySum / (nInputSum + 78);
itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " "));
itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum));
itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64)dPrioritySum), 20, " "));
}
}
// 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);
}
| {
"content_hash": "2ac765217051ed521a6207ae233e115e",
"timestamp": "",
"source": "github",
"line_count": 770,
"max_line_length": 210,
"avg_line_length": 41.66233766233766,
"alnum_prop": 0.6401496259351621,
"repo_name": "universalmol/universalmol",
"id": "79ea198974599590ab481fb8a68944ddfc113a64",
"size": "32810",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/qt/coincontroldialog.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "138271"
},
{
"name": "C++",
"bytes": "2389715"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50615"
},
{
"name": "Inno Setup",
"bytes": "4413"
},
{
"name": "Makefile",
"bytes": "13073"
},
{
"name": "NSIS",
"bytes": "5908"
},
{
"name": "Objective-C",
"bytes": "858"
},
{
"name": "Objective-C++",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "69704"
},
{
"name": "QMake",
"bytes": "15942"
},
{
"name": "Roff",
"bytes": "18284"
},
{
"name": "Shell",
"bytes": "16223"
}
],
"symlink_target": ""
} |
import urllib
from urllib import request
import json
import itertools
from multiprocessing.pool import ThreadPool
def get_html(url, retry=10):
try:
proxy = {'http': '60.167.135.146:808'}
proxy_support = request.ProxyHandler(proxy)
opener = request.build_opener(proxy_support)
opener.addheaders = [('User-Agent',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')]
request.install_opener(opener)
data = request.urlopen(url).read()
except Exception as e:
print(e)
if retry <= 0:
return None
return get_html(url, retry - 1)
return data.decode('utf8')
def get_domain_available(domain):
# url = "https://sg.godaddy.com/zh/domainsapi/v1/search/exact?q=%s" % domain #godaddy
url = "https://checkapi.aliyun.com/check/checkdomain?domain=%s" % domain + \
"&token=check-web-hichina-com%3Ao29tutf4w4fhfzhmvibxagd4odw3lew5&_=1497839736973" #token 需要更新
try:
j = json.loads(get_html(url))
return domain, j["module"][0]["avail"]
except Exception as e:
print(e)
return domain, 0
THREAD_NUMS = 2
def multi_thread_do_job(l, size=THREAD_NUMS): # 容易被办
p = ThreadPool(size)
tasks = []
for i, d in enumerate(l):
tasks.append(p.apply_async(get_domain_available, args=(d,)))
p.close()
results = []
for i, d in enumerate(tasks):
t = d.get()
if t[1] != 0:
results.append(t[0])
print(t)
print("\rprogress: %.2f" % (100 * i / len(l)), end="")
return results
def anti_robot(l):
results = []
for i, d in enumerate(l):
print("\rprogress: %.2f" % (100 * i / len(l)), end="")
t = get_domain_available(d)
if t[1] != 0:
results.append(t[0])
print(t)
return results
# ds = list(itertools.permutations('abcdefghijklmnopqrstuvwxyz', 3))
ds = list(itertools.permutations('abcdefghijklmnopqrstuvwxyz', 3))
ds = ["g" + "".join(d) + ".com" for d in ds]
print(len(ds))
print(anti_robot(ds))
| {
"content_hash": "b8d1c2c79b31f6cfe1306c09efb87c83",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 147,
"avg_line_length": 29.98611111111111,
"alnum_prop": 0.5919407132931913,
"repo_name": "winxos/python",
"id": "69821074a53fb5655e253405c6a4b41e6dd2d094",
"size": "2237",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "domain_checker.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "160"
},
{
"name": "Python",
"bytes": "351299"
}
],
"symlink_target": ""
} |
angular.module('modal.controllers')
.controller('ConceptsModalController', ['$scope', '$modalInstance', '$modal', 'Core',
function($scope, $modalInstance, $modal, Core) {
$scope.term = "";
$scope.ok = function () {
var newConcept = Core.postConceptByUserId(1, $scope.term);
if (newConcept) {
$modalInstance.close(newConcept);
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]); | {
"content_hash": "d8a8bd3b367b72fa060eb6a09e38f385",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 88,
"avg_line_length": 26,
"alnum_prop": 0.5961538461538461,
"repo_name": "tacitia/ThoughtFlow",
"id": "676d8d7e3aca32d26b6a03330ed3286faeecb6a8",
"size": "468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/js/angular/modal/controllers/modal-concepts.controllers.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "191013"
},
{
"name": "HTML",
"bytes": "47230"
},
{
"name": "JavaScript",
"bytes": "461204"
},
{
"name": "Perl",
"bytes": "57958"
},
{
"name": "Python",
"bytes": "205587"
},
{
"name": "Ruby",
"bytes": "813"
},
{
"name": "TeX",
"bytes": "1241"
}
],
"symlink_target": ""
} |
(function (o) {
"use strict";
var self = {},
_caf,
_lastTime = 0,
_prefixes = o.support.prefixes,
_raf;
if (window.requestAnimationFrame) {
_raf = window.requestAnimationFrame;
} else {
for(var i = 0; i < _prefixes.length && !self.requestAnimationFrame; i += 1) {
_raf = window[_prefixes[i] + "RequestAnimationFrame"];
_caf = window[_prefixes[i] + "CancelAnimationFrame"] ||
window[_prefixes[i] + "CancelRequestAnimationFrame"];
}
}
if (_caf) {
self.caf = function () {
_caf.apply(window, arguments);
};
} else {
self.caf = function(id) {
clearTimeout(id);
};
}
if (_raf) {
self.raf = function () {
_raf.apply(window, arguments);
};
} else {
self.raf = function (callback) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - _lastTime));
var id = window.setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
_lastTime = currTime + timeToCall;
return id;
};
}
o.core.extend(self);
}(oak));
| {
"content_hash": "e62a757eb61607a662068f3b73c48f91",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 81,
"avg_line_length": 23.5625,
"alnum_prop": 0.5526083112290009,
"repo_name": "wieden-kennedy/oak-support",
"id": "b33a19e0a21aebe557e2d61376bc322194d1ce8f",
"size": "1131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/raf.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "16388"
}
],
"symlink_target": ""
} |
namespace Google.Cloud.Dialogflow.V2.Snippets
{
// [START dialogflow_v2_generated_Agents_DeleteAgent_async_flattened]
using Google.Cloud.Dialogflow.V2;
using System.Threading.Tasks;
public sealed partial class GeneratedAgentsClientSnippets
{
/// <summary>Snippet for DeleteAgentAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task DeleteAgentAsync()
{
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
await agentsClient.DeleteAgentAsync(parent);
}
}
// [END dialogflow_v2_generated_Agents_DeleteAgent_async_flattened]
}
| {
"content_hash": "a265b7697580f50276e737ff5d8dfe9a",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 89,
"avg_line_length": 38.44,
"alnum_prop": 0.6534859521331946,
"repo_name": "jskeet/gcloud-dotnet",
"id": "c0cf9318c836e96624ea3e3153024c69a0193b44",
"size": "1583",
"binary": false,
"copies": "2",
"ref": "refs/heads/bq-migration",
"path": "apis/Google.Cloud.Dialogflow.V2/Google.Cloud.Dialogflow.V2.GeneratedSnippets/AgentsClient.DeleteAgentAsyncSnippet.g.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1725"
},
{
"name": "C#",
"bytes": "1829733"
}
],
"symlink_target": ""
} |
package com.jcwhatever.nucleus.internal.managed.scoreboards;
import com.jcwhatever.nucleus.managed.scoreboards.IScoreboard;
import com.jcwhatever.nucleus.managed.scoreboards.ITeam;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.text.TextUtils;
import org.bukkit.OfflinePlayer;
import org.bukkit.scoreboard.NameTagVisibility;
import org.bukkit.scoreboard.Team;
import java.util.Collection;
import java.util.Set;
/**
* Managed scoreboard team.
*/
class ManagedTeam implements ITeam {
private final IScoreboard _scoreboard;
private final Team _team;
ManagedTeam(IScoreboard scoreboard, Team team) {
_scoreboard = scoreboard;
_team = team;
}
@Override
public String getName() {
return _team.getName();
}
@Override
public String getDisplayName() {
return _team.getDisplayName();
}
@Override
public void setDisplayName(CharSequence displayName, Object... args) {
_team.setDisplayName(TextUtils.format(displayName, args).toString());
}
@Override
public String getPrefix() {
return _team.getPrefix();
}
@Override
public void setPrefix(CharSequence prefix, Object... args) {
_team.setPrefix(TextUtils.format(prefix, args).toString());
}
@Override
public String getSuffix() {
return _team.getSuffix();
}
@Override
public void setSuffix(CharSequence suffix, Object... args) {
_team.setSuffix(TextUtils.format(suffix, args).toString());
}
@Override
public boolean allowFriendlyFire() {
return _team.allowFriendlyFire();
}
@Override
public void setAllowFriendlyFire(boolean isAllowed) {
_team.setAllowFriendlyFire(isAllowed);
}
@Override
public boolean canSeeFriendlyInvisibles() {
return _team.canSeeFriendlyInvisibles();
}
@Override
public void setCanSeeFriendlyInvisibles(boolean canSee) {
_team.setCanSeeFriendlyInvisibles(canSee);
}
@Override
public NameTagVisibility getNameTagVisibility() {
return _team.getNameTagVisibility();
}
@Override
public void setNameTagVisibility(NameTagVisibility nameTagVisibility) {
_team.setNameTagVisibility(nameTagVisibility);
}
@Override
public Set<OfflinePlayer> getPlayers() {
return _team.getPlayers();
}
@Override
public <T extends Collection<OfflinePlayer>> T getPlayers(T output) {
PreCon.notNull(output);
output.addAll(_team.getPlayers());
return output;
}
@Override
public Set<String> getEntries() {
return _team.getEntries();
}
@Override
public <T extends Collection<String>> T getEntries(T output) {
PreCon.notNull(output);
output.addAll(_team.getEntries());
return output;
}
@Override
public int getSize() {
return _team.getSize();
}
@Override
public IScoreboard getScoreboard() {
return _scoreboard;
}
@Override
public void addPlayer(OfflinePlayer player) {
_team.addPlayer(player);
}
@Override
public void addEntry(CharSequence entry) {
_team.addEntry(entry.toString());
}
@Override
public boolean removePlayer(OfflinePlayer player) {
return _team.removePlayer(player);
}
@Override
public boolean removeEntry(CharSequence entry) {
return _team.removeEntry(entry.toString());
}
@Override
public void unregister() {
_team.unregister();
}
@Override
public boolean hasPlayer(OfflinePlayer player) {
return _team.hasPlayer(player);
}
@Override
public boolean hasEntry(CharSequence entry) {
return _team.hasEntry(entry.toString());
}
@Override
public int hashCode() {
return _team.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof ManagedTeam &&
((ManagedTeam) obj)._team.equals(_team);
}
}
| {
"content_hash": "c9aed8148bee0452fa170feccfca0c41",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 77,
"avg_line_length": 23.125,
"alnum_prop": 0.6533169533169533,
"repo_name": "JCThePants/NucleusFramework",
"id": "8c668b7aac67103490ee3f234fd69470b68884e6",
"size": "5294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/jcwhatever/nucleus/internal/managed/scoreboards/ManagedTeam.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26414"
},
{
"name": "HTML",
"bytes": "5069"
},
{
"name": "Java",
"bytes": "6510926"
}
],
"symlink_target": ""
} |
package com.searchbox.framework.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import com.searchbox.framework.model.UserEntity;
public interface UserRepository extends CrudRepository<UserEntity, Long> {
public UserEntity findByEmail(String email);
public UserEntity findByResetHash(String hash);
Page<UserEntity> findAll(Pageable pageable);
}
| {
"content_hash": "3119f5249dae94f5260e5ad18f2c6787",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 74,
"avg_line_length": 26.38888888888889,
"alnum_prop": 0.8252631578947368,
"repo_name": "eSCT/oppfin",
"id": "62a888e954fb2ace890fc38add14ed3ccfebf443",
"size": "1242",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/searchbox/framework/repository/UserRepository.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "29538"
},
{
"name": "Java",
"bytes": "1205886"
},
{
"name": "JavaScript",
"bytes": "16606"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisualShaderNode" inherits="Resource" category="Core" version="3.2">
<brief_description>
</brief_description>
<description>
</description>
<tutorials>
</tutorials>
<methods>
<method name="get_input_port_default_value" qualifiers="const">
<return type="Variant">
</return>
<argument index="0" name="port" type="int">
</argument>
<description>
</description>
</method>
<method name="set_input_port_default_value">
<return type="void">
</return>
<argument index="0" name="port" type="int">
</argument>
<argument index="1" name="value" type="Variant">
</argument>
<description>
</description>
</method>
</methods>
<members>
<member name="default_input_values" type="Array" setter="_set_default_input_values" getter="_get_default_input_values" default="[ 0, Vector3( 0, 0, 0 ) ]">
</member>
<member name="output_port_for_preview" type="int" setter="set_output_port_for_preview" getter="get_output_port_for_preview" default="-1">
</member>
</members>
<signals>
<signal name="editor_refresh_request">
<description>
</description>
</signal>
</signals>
<constants>
</constants>
</class>
| {
"content_hash": "a3333f2ff297dc92bfa7c7e8e0aee7b2",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 157,
"avg_line_length": 28.209302325581394,
"alnum_prop": 0.6619950535861501,
"repo_name": "neikeq/godot",
"id": "19495a88599eafeab833fc99f8dbdc2fd131f63b",
"size": "1213",
"binary": false,
"copies": "2",
"ref": "refs/heads/goshujinsama",
"path": "doc/classes/VisualShaderNode.xml",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import java.util.*;
public class NEpaths {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows apart: ");
int rows = sc.nextInt();
System.out.print("Enter columns apart: ");
int cols = sc.nextInt();
String path = "";
System.out.println("Number of paths = " + ne(rows, cols, path));
}
// To compute the number of NE paths as well as to display the paths
public static int ne(int rows, int cols, String path) {
if ( cols == 0 && rows == 0) {
System.out.println(path);
return 1;
} else {
if( rows == 0 && cols != 0) {
return ne( rows, cols-1, path.concat("E "));
} else if ( rows !=0 && cols == 0) {
path.concat("N ");
return ne(rows -1 , cols , path.concat("N "));
} else {
return ne(rows -1, cols, path.concat("N ")) + ne(rows, cols -1, path.concat("E "));
}
}
}
}
| {
"content_hash": "1b57cab1bcc138079fb00d28bebcd183",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 87,
"avg_line_length": 25.514285714285716,
"alnum_prop": 0.58006718924972,
"repo_name": "wentjun/Data-Structures-and-Algorithms-I-CS1020",
"id": "98b290adfd4bdd845704ddd27098a2f4e765a998",
"size": "893",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Practice Questions/NEpaths.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "113630"
}
],
"symlink_target": ""
} |
import { LoggerageObject } from '../loggerage-object';
import { Storage } from '../storage-interface';
import { Query } from './query';
export declare class WrapLocalStorage implements Storage {
private _storage;
constructor(localStorage: any);
getItem(app: string, query?: Query): LoggerageObject[];
setItem(app: string, value: LoggerageObject): void;
clear(): void;
}
| {
"content_hash": "90b221085eedc7c7173a9b46123b713d",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 59,
"avg_line_length": 39,
"alnum_prop": 0.7025641025641025,
"repo_name": "lmfresneda/LogStorage.js",
"id": "f1eb24bf4439a928925c6b18e97a3c85bf457756",
"size": "390",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "types/utils/wrap-localstorage.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "538"
},
{
"name": "JavaScript",
"bytes": "130803"
},
{
"name": "TypeScript",
"bytes": "9230"
}
],
"symlink_target": ""
} |
package com.google.apphosting.utils.config;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parsed queue.xml file.
*
* Any additions to this class should also be made to the YAML
* version in QueueYamlReader.java.
*
*/
// Following the format of CronXml.
public class QueueXml {
static final String RATE_REGEX = "([0-9]+(\\.[0-9]+)?)/([smhd])";
static final Pattern RATE_PATTERN = Pattern.compile(RATE_REGEX);
static final String TOTAL_STORAGE_LIMIT_REGEX = "^([0-9]+(\\.[0-9]*)?[BKMGT]?)";
static final Pattern TOTAL_STORAGE_LIMIT_PATTERN = Pattern.compile(TOTAL_STORAGE_LIMIT_REGEX);
// Keep these in sync with taskqueue.QueueConstants.
private static final int MAX_QUEUE_NAME_LENGTH = 100;
private static final String QUEUE_NAME_REGEX = "[a-zA-Z\\d-]{1," + MAX_QUEUE_NAME_LENGTH + "}";
private static final Pattern QUEUE_NAME_PATTERN = Pattern.compile(QUEUE_NAME_REGEX);
private static final String TASK_AGE_LIMIT_REGEX =
"([0-9]+(?:\\.?[0-9]*(?:[eE][\\-+]?[0-9]+)?)?)([smhd])";
private static final Pattern TASK_AGE_LIMIT_PATTERN = Pattern.compile(TASK_AGE_LIMIT_REGEX);
private static final String MODE_REGEX = "push|pull";
private static final Pattern MODE_PATTERN = Pattern.compile(MODE_REGEX);
private static final int MAX_TARGET_LENGTH = 100;
private static final String TARGET_REGEX = "[a-z\\d\\-\\.]{1," + MAX_TARGET_LENGTH + "}";
private static final Pattern TARGET_PATTERN = Pattern.compile(TARGET_REGEX);
/**
* The default queue name. Keep this in sync with
* {@link com.google.appengine.api.taskqueue.Queue#DEFAULT_QUEUE}.
*/
private static final String DEFAULT_QUEUE = "default";
/**
* Enumerates the allowed units for Queue rate.
*/
public enum RateUnit {
SECOND('s', 1),
MINUTE('m', SECOND.getSeconds() * 60),
HOUR('h', MINUTE.getSeconds() * 60),
DAY('d', HOUR.getSeconds() * 24);
final char ident;
final int seconds;
RateUnit(char ident, int seconds) {
this.ident = ident;
this.seconds = seconds;
}
static RateUnit valueOf(char unit) {
switch (unit) {
case 's' : return SECOND;
case 'm' : return MINUTE;
case 'h' : return HOUR;
case 'd' : return DAY;
}
throw new AppEngineConfigException("Invalid rate was specified.");
}
public char getIdent() {
return ident;
}
public int getSeconds() {
return seconds;
}
}
/**
* Access control list for a queue.
*/
public static class AclEntry {
private String userEmail;
private String writerEmail;
public AclEntry() {
userEmail = null;
writerEmail = null;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserEmail() {
return userEmail;
}
public void setWriterEmail(String writerEmail) {
this.writerEmail = writerEmail;
}
public String getWriterEmail() {
return writerEmail;
}
// Generated by eclipse.
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userEmail == null) ? 0 : userEmail.hashCode());
result = prime * result + ((writerEmail == null) ? 0 : writerEmail.hashCode());
return result;
}
// Generated by eclipse.
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
AclEntry other = (AclEntry) obj;
if (userEmail == null) {
if (other.userEmail != null) return false;
} else if (!userEmail.equals(other.userEmail)) return false;
if (writerEmail == null) {
if (other.writerEmail != null) return false;
} else if (!writerEmail.equals(other.writerEmail)) return false;
return true;
}
}
/**
* Describes a queue's optional retry parameters.
*/
public static class RetryParameters {
private Integer retryLimit;
private Integer ageLimitSec;
private Double minBackoffSec;
private Double maxBackoffSec;
private Integer maxDoublings;
public RetryParameters() {
retryLimit = null;
ageLimitSec = null;
minBackoffSec = null;
maxBackoffSec = null;
maxDoublings = null;
}
public Integer getRetryLimit() {
return retryLimit;
}
public void setRetryLimit(int retryLimit) {
this.retryLimit = retryLimit;
}
public void setRetryLimit(String retryLimit) {
this.retryLimit = Integer.valueOf(retryLimit);
}
public Integer getAgeLimitSec() {
return ageLimitSec;
}
public void setAgeLimitSec(String ageLimitString) {
Matcher matcher = TASK_AGE_LIMIT_PATTERN.matcher(ageLimitString);
if (!matcher.matches() || matcher.groupCount() != 2) {
throw new AppEngineConfigException("Invalid task age limit was specified.");
}
double rateUnitSec = RateUnit.valueOf(matcher.group(2).charAt(0)).getSeconds();
Double ageLimit = Double.parseDouble(matcher.group(1)) * rateUnitSec;
this.ageLimitSec = ageLimit.intValue();
}
public Double getMinBackoffSec() {
return minBackoffSec;
}
public void setMinBackoffSec(double minBackoffSec) {
this.minBackoffSec = minBackoffSec;
}
public void setMinBackoffSec(String minBackoffSec) {
this.minBackoffSec = Double.valueOf(minBackoffSec);
}
public Double getMaxBackoffSec() {
return maxBackoffSec;
}
public void setMaxBackoffSec(double maxBackoffSec) {
this.maxBackoffSec = maxBackoffSec;
}
public void setMaxBackoffSec(String maxBackoffSec) {
this.maxBackoffSec = Double.valueOf(maxBackoffSec);
}
public Integer getMaxDoublings() {
return maxDoublings;
}
public void setMaxDoublings(int maxDoublings) {
this.maxDoublings = maxDoublings;
}
public void setMaxDoublings(String maxDoublings) {
this.maxDoublings = Integer.valueOf(maxDoublings);
}
// Generated by Eclipse
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((ageLimitSec == null) ? 0 : ageLimitSec.hashCode());
result = prime * result + ((maxBackoffSec == null) ? 0 : maxBackoffSec.hashCode());
result = prime * result + ((maxDoublings == null) ? 0 : maxDoublings.hashCode());
result = prime * result + ((minBackoffSec == null) ? 0 : minBackoffSec.hashCode());
result = prime * result + ((retryLimit == null) ? 0 : retryLimit.hashCode());
return result;
}
// Generated by Eclipse
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
RetryParameters other = (RetryParameters) obj;
if (ageLimitSec == null) {
if (other.ageLimitSec != null) return false;
} else if (!ageLimitSec.equals(other.ageLimitSec)) return false;
if (maxBackoffSec == null) {
if (other.maxBackoffSec != null) return false;
} else if (!maxBackoffSec.equals(other.maxBackoffSec)) return false;
if (maxDoublings == null) {
if (other.maxDoublings != null) return false;
} else if (!maxDoublings.equals(other.maxDoublings)) return false;
if (minBackoffSec == null) {
if (other.minBackoffSec != null) return false;
} else if (!minBackoffSec.equals(other.minBackoffSec)) return false;
if (retryLimit == null) {
if (other.retryLimit != null) return false;
} else if (!retryLimit.equals(other.retryLimit)) return false;
return true;
}
}
/**
* Describes a single queue entry.
*/
public static class Entry {
private String name;
private Double rate;
private RateUnit rateUnit;
private Integer bucketSize;
private Integer maxConcurrentRequests;
private RetryParameters retryParameters;
private String target;
private String mode;
private List<AclEntry> acl;
/** Create an empty queue entry. */
public Entry() {
name = null;
rate = null;
rateUnit = RateUnit.SECOND;
bucketSize = null;
maxConcurrentRequests = null;
retryParameters = null;
target = null;
mode = null;
acl = null;
}
public Entry(String name, double rate, RateUnit rateUnit, int bucketSize,
Integer maxConcurrentRequests, String target) {
this.name = name;
this.rate = rate;
this.rateUnit = rateUnit;
this.bucketSize = bucketSize;
this.maxConcurrentRequests = maxConcurrentRequests;
this.target = target;
}
public String getName() {
return name;
}
public void setName(String queueName) {
if (queueName == null || queueName.length() == 0 ||
!QUEUE_NAME_PATTERN.matcher(queueName).matches()) {
throw new AppEngineConfigException(
"Queue name does not match expression " + QUEUE_NAME_PATTERN +
"; found '" + queueName + "'");
}
this.name = queueName;
}
public void setMode(String mode) {
if (mode == null || mode.length() == 0 ||
!MODE_PATTERN.matcher(mode).matches()) {
throw new AppEngineConfigException(
"mode must be either 'push' or 'pull'");
}
this.mode = mode;
}
public String getMode() {
return mode;
}
public List<AclEntry> getAcl() {
return acl;
}
public void setAcl(List<AclEntry> acl) {
this.acl = acl;
}
public void addAcl(AclEntry aclEntry) {
this.acl.add(aclEntry);
}
public Double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
/**
* Set rate and units based on a "number/unit" formatted string.
* @param rateString My be "0" or "number/unit" where unit is 's|m|h|d'.
*/
public void setRate(String rateString) {
if (rateString.equals("0")) {
rate = 0.0;
rateUnit = RateUnit.SECOND;
return;
}
Matcher matcher = RATE_PATTERN.matcher(rateString);
if (!matcher.matches()) {
throw new AppEngineConfigException("Invalid queue rate was specified.");
}
String digits = matcher.group(1);
rateUnit = RateUnit.valueOf(matcher.group(3).charAt(0));
rate = Double.valueOf(digits);
}
public RateUnit getRateUnit() {
return rateUnit;
}
public void setRateUnit(RateUnit rateUnit) {
this.rateUnit = rateUnit;
}
public Integer getBucketSize() {
return bucketSize;
}
public void setBucketSize(int bucketSize) {
this.bucketSize = bucketSize;
}
public void setBucketSize(String bucketSize) {
try {
this.bucketSize = Integer.valueOf(bucketSize);
} catch (NumberFormatException exception) {
throw new AppEngineConfigException("Invalid bucket-size was specified.", exception);
}
}
public Integer getMaxConcurrentRequests() {
return maxConcurrentRequests;
}
public void setMaxConcurrentRequests(int maxConcurrentRequests) {
this.maxConcurrentRequests = maxConcurrentRequests;
}
public void setMaxConcurrentRequests(String maxConcurrentRequests) {
try {
this.maxConcurrentRequests = Integer.valueOf(maxConcurrentRequests);
} catch (NumberFormatException exception) {
throw new AppEngineConfigException("Invalid max-concurrent-requests was specified: '" +
maxConcurrentRequests + "'", exception);
}
}
public RetryParameters getRetryParameters() {
return retryParameters;
}
public void setRetryParameters(RetryParameters retryParameters) {
this.retryParameters = retryParameters;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
Matcher matcher = TARGET_PATTERN.matcher(target);
if (!matcher.matches()) {
throw new AppEngineConfigException("Invalid queue target was specified. Target: '" +
target + "'");
}
this.target = target;
}
// Generated by Eclipse.
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((acl == null) ? 0 : acl.hashCode());
result = prime * result + ((bucketSize == null) ? 0 : bucketSize.hashCode());
result =
prime * result + ((maxConcurrentRequests == null) ? 0 : maxConcurrentRequests.hashCode());
result = prime * result + ((mode == null) ? 0 : mode.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((rate == null) ? 0 : rate.hashCode());
result = prime * result + ((rateUnit == null) ? 0 : rateUnit.hashCode());
result = prime * result + ((target == null) ? 0 : target.hashCode());
result = prime * result + ((retryParameters == null) ? 0 : retryParameters.hashCode());
return result;
}
// Generated by Eclipse
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Entry other = (Entry) obj;
if (acl == null) {
if (other.acl != null) return false;
} else if (!acl.equals(other.acl)) return false;
if (bucketSize == null) {
if (other.bucketSize != null) return false;
} else if (!bucketSize.equals(other.bucketSize)) return false;
if (maxConcurrentRequests == null) {
if (other.maxConcurrentRequests != null) return false;
} else if (!maxConcurrentRequests.equals(other.maxConcurrentRequests)) return false;
if (mode == null) {
if (other.mode != null) return false;
} else if (!mode.equals(other.mode)) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
if (rate == null) {
if (other.rate != null) return false;
} else if (!rate.equals(other.rate)) return false;
if (rateUnit == null) {
if (other.rateUnit != null) return false;
} else if (!rateUnit.equals(other.rateUnit)) return false;
if (target == null) {
if (other.target != null) return false;
} else if (!target.equals(other.target)) return false;
if (retryParameters == null) {
if (other.retryParameters != null) return false;
} else if (!retryParameters.equals(other.retryParameters)) return false;
return true;
}
}
private final LinkedHashMap<String, Entry> entries = new LinkedHashMap<String, Entry>();
private Entry lastEntry;
private String totalStorageLimit = "";
/**
* Return a new {@link Entry} describing the default queue.
*/
public static Entry defaultEntry() {
return new Entry(DEFAULT_QUEUE, 5, RateUnit.SECOND, 5, null, null);
}
/**
* Puts a new entry into the list defined by the queue.xml file.
*
* @throws AppEngineConfigException if the previously-last entry is still
* incomplete.
* @return the new entry
*/
public Entry addNewEntry() {
validateLastEntry();
lastEntry = new Entry();
return lastEntry;
}
public void addEntry(Entry entry) {
validateLastEntry();
lastEntry = entry;
validateLastEntry();
}
/**
* Get the entries.
*/
public Collection<Entry> getEntries() {
validateLastEntry();
return entries.values();
}
/**
* Check that the last entry defined is complete.
* @throws AppEngineConfigException if it is not.
*/
public void validateLastEntry() {
if (lastEntry == null) {
return;
}
if (lastEntry.getName() == null) {
throw new AppEngineConfigException("Queue entry must have a name.");
}
if (entries.containsKey(lastEntry.getName())) {
throw new AppEngineConfigException("Queue entry has duplicate name.");
}
if ("pull".equals(lastEntry.getMode())) {
if (lastEntry.getRate() != null) {
throw new AppEngineConfigException("Rate must not be specified for pull queue.");
}
if (lastEntry.getBucketSize() != null) {
throw new AppEngineConfigException("Bucket size must not be specified for pull queue.");
}
if (lastEntry.getMaxConcurrentRequests() != null) {
throw new AppEngineConfigException(
"MaxConcurrentRequests must not be specified for pull queue.");
}
RetryParameters retryParameters = lastEntry.getRetryParameters();
if (retryParameters != null) {
// Task retry limit is supported for pull queues, but no other retry parameters.
if (retryParameters.getAgeLimitSec() != null) {
throw new AppEngineConfigException(
"Age limit must not be specified for pull queue.");
}
if (retryParameters.getMinBackoffSec() != null) {
throw new AppEngineConfigException(
"Min backoff must not be specified for pull queue.");
}
if (retryParameters.getMaxBackoffSec() != null) {
throw new AppEngineConfigException(
"Max backoff must not be specified for pull queue.");
}
if (retryParameters.getMaxDoublings() != null) {
throw new AppEngineConfigException(
"Max doublings must not be specified for pull queue.");
}
}
} else {
if (lastEntry.getRate() == null) {
throw new AppEngineConfigException("A queue rate is required for push queue.");
}
}
entries.put(lastEntry.getName(), lastEntry);
lastEntry = null;
}
public void setTotalStorageLimit(String s) {
totalStorageLimit = s;
}
public String getTotalStorageLimit() {
return totalStorageLimit;
}
/**
* Get the YAML equivalent of this queue.xml file.
*
* @return contents of an equivalent {@code queue.yaml} file.
*/
public String toYaml() {
StringBuilder builder = new StringBuilder();
if (getTotalStorageLimit().length() > 0) {
builder.append("total_storage_limit: " + getTotalStorageLimit() + "\n\n");
}
builder.append("queue:\n");
for (Entry ent : getEntries()) {
builder.append("- name: " + ent.getName() + "\n");
Double rate = ent.getRate();
if (rate != null) {
builder.append(
" rate: " + rate + '/' + ent.getRateUnit().getIdent() + "\n");
}
Integer bucketSize = ent.getBucketSize();
if (bucketSize != null) {
builder.append(" bucket_size: " + bucketSize + "\n");
}
Integer maxConcurrentRequests = ent.getMaxConcurrentRequests();
if (maxConcurrentRequests != null) {
builder.append(" max_concurrent_requests: " + maxConcurrentRequests + "\n");
}
RetryParameters retryParameters = ent.getRetryParameters();
if (retryParameters != null) {
builder.append(" retry_parameters:\n");
if (retryParameters.getRetryLimit() != null) {
builder.append(" task_retry_limit: " + retryParameters.getRetryLimit() + "\n");
}
if (retryParameters.getAgeLimitSec() != null) {
builder.append(" task_age_limit: " + retryParameters.getAgeLimitSec() + "s\n");
}
if (retryParameters.getMinBackoffSec() != null) {
builder.append(" min_backoff_seconds: " + retryParameters.getMinBackoffSec() + "\n");
}
if (retryParameters.getMaxBackoffSec() != null) {
builder.append(" max_backoff_seconds: " + retryParameters.getMaxBackoffSec() + "\n");
}
if (retryParameters.getMaxDoublings() != null) {
builder.append(" max_doublings: " + retryParameters.getMaxDoublings() + "\n");
}
}
String target = ent.getTarget();
if (target != null) {
builder.append(" target: " + target + "\n");
}
String mode = ent.getMode();
if (mode != null) {
builder.append(" mode: " + mode + "\n");
}
List<AclEntry> acl = ent.getAcl();
if (acl != null) {
builder.append(" acl:\n");
for (AclEntry aclEntry : acl) {
if (aclEntry.getUserEmail() != null) {
builder.append(" - user_email: " + aclEntry.getUserEmail() + "\n");
} else if (aclEntry.getWriterEmail() != null) {
builder.append(" - writer_email: " + aclEntry.getWriterEmail() + "\n");
}
}
}
}
return builder.toString();
}
}
| {
"content_hash": "db3ae386b71d948d36f36b24c907638b",
"timestamp": "",
"source": "github",
"line_count": 648,
"max_line_length": 100,
"avg_line_length": 32.141975308641975,
"alnum_prop": 0.620318801613213,
"repo_name": "GoogleCloudPlatform/appengine-java-standard",
"id": "61c9dd55cc92098f2b1d32651198c4f59bc89e90",
"size": "21422",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "utils/src/main/java/com/google/apphosting/utils/config/QueueXml.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2237"
},
{
"name": "CSS",
"bytes": "15037"
},
{
"name": "FreeMarker",
"bytes": "2577"
},
{
"name": "GAP",
"bytes": "21948"
},
{
"name": "HTML",
"bytes": "1173"
},
{
"name": "Java",
"bytes": "9377837"
},
{
"name": "JavaScript",
"bytes": "9465"
},
{
"name": "Shell",
"bytes": "13619"
},
{
"name": "Starlark",
"bytes": "2612"
}
],
"symlink_target": ""
} |
import synapse.common as s_common
import synapse.lib.stormtypes as s_stormtypes
@s_stormtypes.registry.registerLib
class BackupLib(s_stormtypes.Lib):
'''
A Storm Library for interacting with the backup APIs in the Cortex.
'''
_storm_locals = (
{'name': 'run', 'desc': 'Run a Cortex backup.',
'type': {'type': 'function', '_funcname': '_runBackup',
'args': (
{'name': 'name', 'type': 'str', 'desc': 'The name of the backup to generate.', 'default': None, },
{'name': 'wait', 'type': 'boolean', 'desc': 'If true, wait for the backup to complete before returning.',
'default': True, },
),
'returns': {'type': 'str', 'desc': 'The name of the newly created backup.', }}},
{'name': 'list', 'desc': 'Get a list of backup names.',
'type': {'type': 'function', '_funcname': '_listBackups',
'returns': {'type': 'list', 'desc': 'A list of backup names.', }}},
{'name': 'del', 'desc': 'Remove a backup by name.',
'type': {'type': 'function', '_funcname': '_delBackup',
'args': (
{'name': 'name', 'type': 'str', 'desc': 'The name of the backup to remove.', },
),
'returns': {'type': 'null', }}},
)
_storm_lib_path = ('backup',)
def getObjLocals(self):
return {
'run': self._runBackup,
'list': self._listBackups,
'del': self._delBackup,
}
async def _runBackup(self, name=None, wait=True):
name = await s_stormtypes.tostr(name, noneok=True)
wait = await s_stormtypes.tobool(wait)
todo = s_common.todo('runBackup', name=name, wait=wait)
gatekeys = ((self.runt.user.iden, ('backup', 'run'), None),)
return await self.dyncall('cortex', todo, gatekeys=gatekeys)
async def _listBackups(self):
todo = s_common.todo('getBackups')
gatekeys = ((self.runt.user.iden, ('backup', 'list'), None),)
return await self.dyncall('cortex', todo, gatekeys=gatekeys)
async def _delBackup(self, name):
name = await s_stormtypes.tostr(name)
todo = s_common.todo('delBackup', name)
gatekeys = ((self.runt.user.iden, ('backup', 'del'), None),)
return await self.dyncall('cortex', todo, gatekeys=gatekeys)
| {
"content_hash": "8fd71b8fd5c8c4edf51dda3319eb2b22",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 127,
"avg_line_length": 44.907407407407405,
"alnum_prop": 0.5360824742268041,
"repo_name": "vertexproject/synapse",
"id": "dad9ed94ab5b9c974c8c3c935e2055d027703f32",
"size": "2425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "synapse/lib/stormlib/backup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "4010"
},
{
"name": "HTML",
"bytes": "3"
},
{
"name": "Python",
"bytes": "5894053"
},
{
"name": "Shell",
"bytes": "10776"
}
],
"symlink_target": ""
} |
title: 'Startup Summits'
media_order: 23675013_1952128548337604_915895118384903538_o.jpg
---
Our annual startup summit, Converge, brings together creators, innovators and entrepreneurs at the frontline of our global technology, startups and creative ecosystems to offer key insights, big ideas and collaborate.
The Summit takes a uniqe focus on how Technology will transform the creative economy globally, and explores a technology driven future.
| {
"content_hash": "b47fee07c0b1e42f0463e0afad9fa6a0",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 218,
"avg_line_length": 64.42857142857143,
"alnum_prop": 0.8203991130820399,
"repo_name": "elixirlabsinc/next-gen",
"id": "638cf45c4c0a9ad652afe029b4373806f247a7cb",
"size": "455",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "user/pages/02.about/programs/summit/program.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "548872"
},
{
"name": "CoffeeScript",
"bytes": "1615"
},
{
"name": "HTML",
"bytes": "613462"
},
{
"name": "JavaScript",
"bytes": "309135"
},
{
"name": "Logos",
"bytes": "831"
},
{
"name": "PHP",
"bytes": "1345781"
},
{
"name": "Shell",
"bytes": "606"
}
],
"symlink_target": ""
} |
namespace ph
{
std::shared_ptr<Geometry> LightSource::genGeometry(CookingContext& context) const
{
return nullptr;
}
std::shared_ptr<Material> LightSource::genMaterial(CookingContext& context) const
{
const Vector3R linearSrgbAlbedo(0.5_r);
return std::make_shared<MatteOpaque>(linearSrgbAlbedo);
}
// command interface
LightSource::LightSource(const InputPacket& packet)
{}
SdlTypeInfo LightSource::ciTypeInfo()
{
return SdlTypeInfo(ETypeCategory::REF_LIGHT_SOURCE, "light-source");
}
void LightSource::ciRegister(CommandRegister& cmdRegister) {}
}// end namespace ph | {
"content_hash": "b6f33ca21992b411371b3b471fb45cf6",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 81,
"avg_line_length": 21.444444444444443,
"alnum_prop": 0.7772020725388601,
"repo_name": "TzuChieh/Photon-v2",
"id": "1c6381210004a6e1ebd2ccd9721891e0e64b34dc",
"size": "700",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Engine/Source/Actor/LightSource/LightSource.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "429"
},
{
"name": "C",
"bytes": "7059"
},
{
"name": "C++",
"bytes": "1572544"
},
{
"name": "CMake",
"bytes": "7944"
},
{
"name": "Java",
"bytes": "265901"
},
{
"name": "Objective-C",
"bytes": "336"
},
{
"name": "Python",
"bytes": "171368"
},
{
"name": "Shell",
"bytes": "439"
}
],
"symlink_target": ""
} |
<?php
namespace Wetcat\Fortie\Providers\Currencies;
use Wetcat\Fortie\AbstractFortieResource;
class Resource extends AbstractFortieResource
{
protected $wrapper = 'Currencies';
}
| {
"content_hash": "422470e71b1be5fe9f092efea4187479",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 45,
"avg_line_length": 18.6,
"alnum_prop": 0.7956989247311828,
"repo_name": "wetcat-studios/fortie",
"id": "6a0d326fc569928b235bb66566119aecb210d756",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/Providers/Currencies/Resource.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "190919"
}
],
"symlink_target": ""
} |
#include "RLEEncodeDecodeII.h"
RLEEncodeDecodeII::RLEEncodeDecodeII()
{}
RLEEncodeDecodeII::~RLEEncodeDecodeII()
{}
bool RLEEncodeDecodeII::run(Globals* g, const vector<string>& args) {
using namespace std;
bool success=true;
cout << "*** RLE Encoding and Decoding simple test ***" << endl;
cout << "--- Encoding page with the encoder - 1086 bits ---" << endl;
cout << " - type =1" << endl
<< " - size =4" << endl
<< " - reps =5" << endl;
TestDataSrc* dataSrc=new TestDataSrc();
dataSrc->addBlock(new RLEBlock(new RLETriple(new IntValPos(4,1),4,5), true));
RLEEncoderII* encoder=new RLEEncoderII(dataSrc,0,1086, 1, 4, 5);
cout << "-I : " << " Encoding triple (1, 4, 5)" << endl;
RLEDecoderII* decoder=new RLEDecoderII(encoder->getPage(), true);
success&=test("Start Int \t", true, *(int*)decoder->getStartVal()->value, 1);
success&=test("Start Pos \t", true, decoder->getStartPos(), 4);
success&=test("End Int \t", true, *(int*)decoder->getEndVal()->value, 1);
success&=test("End Pos \t", true, decoder->getEndPos(), 8);
byte* pagePtr=encoder->getPage();
delete decoder;
delete encoder;
delete pagePtr;
delete dataSrc;
cout << "*** RLE Encoding and Decoding randomized test ***" << endl;
dataSrc=new TestDataSrc();
unsigned int val=0;
unsigned int lastVal=0;
unsigned int currentPos=0;
unsigned int oldPos=0;
unsigned int reps=2;
unsigned int oldReps=2;
int numTriplesWritten=0;
int values[2500];
unsigned int starts[2500];
unsigned int repits[2500];
for (int i=0; i<2000; i++) {
dataSrc->addBlock(new RLEBlock(new RLETriple(new IntValPos(currentPos, val),currentPos,reps),false));
values[numTriplesWritten]=val;
starts[numTriplesWritten]=currentPos;
repits[numTriplesWritten]=reps;
lastVal=val;
oldPos=currentPos;
oldReps=reps;
val=rand()&0xF;
if (val==lastVal) {
val++;
val=val&0xF;
}
currentPos+=reps;
reps=((rand())&0x3F);
if (reps==0)
reps=1;
numTriplesWritten++;
}
cout << "--- Encoding page with the encoder - 10862 bits ---" << endl;
cout << " - type =1" << endl
<< " - size =4" << endl
<< " - reps =6" << endl;
encoder=new RLEEncoderII(dataSrc,0,10862, 1, 4, 6);
byte* page=encoder->getPage();
decoder=new RLEDecoderII(page, true);
bool triplesSuccess=true;
int counter=0;
bool flag=true;
cout << "Testing all triples match on decoding: ";
RLEBlock* block=((RLEBlock*) decoder->getNextBlock());
RLETriple* triple;
if (block==NULL) flag=false;
else triple=block->getTriple();
while (flag) {
assert(triple->value->type == ValPos::INTTYPE);
triplesSuccess&=(values[counter]==*(int*)triple->value->value);
triplesSuccess&=(starts[counter]==triple->startPos);
triplesSuccess&=(repits[counter]==triple->reps);
//cout << "Was: (" << triple->value << "," << triple->startPos << "," << triple->reps
// << ") E: (" << values[counter] << "," << starts[counter] << "," << repits[counter] << endl;
counter++;
block=((RLEBlock*) decoder->getNextBlock());
if (block==NULL) flag=false;
else triple=block->getTriple();
}
if (triplesSuccess) cout << "Matched on all " << counter << " triples" << endl;
else cout << "Failed to match some/all of " << counter << " triples" << endl;
test("Triple's fields", triplesSuccess, 0, 0);
success&=triplesSuccess;
int expNumTriples=(10862-32-16-64)/(4+6);
success&=test("NumTriples\t",true, counter, (10862-32-16-64)/(4+6));
success&=test("Start Int \t",true, *(int*)decoder->getStartVal()->value, 0);
success&=test("Start Pos \t",true, decoder->getStartPos(), 0);
success&=test("End Int \t",true, *(int*)decoder->getEndVal()->value, values[expNumTriples-1]);
success&=test("End Pos \t",true, decoder->getEndPos(), starts[expNumTriples]-1);
return success;
}
bool RLEEncodeDecodeII::test(char* msg_, int retBool_, int val_, int exp_) {
using namespace std;
if (retBool_) {
cout << msg_ << " X: " << val_ << "\tE[X]: " << exp_ << " \t";
if (val_==exp_) {
cout << "SUCCESS" << endl;
return true;
}
else {
cout << "FAILED" << endl;
return false;
}
}
else {
cout << "FAILED (function return failed)" << endl;
return false;
}
}
| {
"content_hash": "776252ae147469f334da90af7c3aa3f4",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 103,
"avg_line_length": 31.435714285714287,
"alnum_prop": 0.6066802999318337,
"repo_name": "ibrarahmad/cstore",
"id": "84224104ce4d51a362bd094e749c9ffe8e1f8a5c",
"size": "6228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/UnitTests/RLEEncodeDecodeII.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Awk",
"bytes": "1634"
},
{
"name": "Bison",
"bytes": "20492"
},
{
"name": "C",
"bytes": "4558"
},
{
"name": "C++",
"bytes": "4291862"
},
{
"name": "Makefile",
"bytes": "138539"
},
{
"name": "Perl",
"bytes": "87556"
},
{
"name": "Shell",
"bytes": "11329"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace AppControl
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| {
"content_hash": "f3f32265c3c7c2eb204546e2610f782a",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 42,
"avg_line_length": 19.058823529411764,
"alnum_prop": 0.7037037037037037,
"repo_name": "razsilev/TelerikAcademy_Homework",
"id": "de78767034f78e3761fef045fe43171c1fb92197",
"size": "326",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "OOP/OOP_TeamWork/OOPTeamWork/TeamWork/AppControl/App.xaml.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1604"
},
{
"name": "C#",
"bytes": "2431431"
},
{
"name": "CSS",
"bytes": "321817"
},
{
"name": "CoffeeScript",
"bytes": "943"
},
{
"name": "HTML",
"bytes": "530569"
},
{
"name": "JavaScript",
"bytes": "1370708"
},
{
"name": "XSLT",
"bytes": "3344"
}
],
"symlink_target": ""
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=calendar-access.interface.js.map | {
"content_hash": "1073b4d63023e4d04d7889f022dc5d8c",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 62,
"avg_line_length": 43.333333333333336,
"alnum_prop": 0.7461538461538462,
"repo_name": "jdonenine/disney-parks-calendar",
"id": "756fa8e2b013b7fca4645a8b40da97ab18a8c794",
"size": "130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/services/calendar-access.interface.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "TypeScript",
"bytes": "19158"
}
],
"symlink_target": ""
} |
(function(app) {
// #enddocregion appimport
// #docregion ng2import
var provide =
ng.core.provide;
var bootstrap =
ng.platformBrowserDynamic.bootstrap;
var LocationStrategy =
ng.common.LocationStrategy;
var HashLocationStrategy =
ng.common.HashLocationStrategy;
// #enddocregion ng2import
// #docregion appimport
var HeroComponent = app.HeroComponent;
// #enddocregion appimport
document.addEventListener('DOMContentLoaded', function() {
bootstrap(HeroComponent);
bootstrap(app.HeroComponentDsl);
bootstrap(app.HeroLifecycleComponent);
bootstrap(app.HeroDIComponent, [app.DataService]);
bootstrap(app.HeroDIInlineComponent, [app.DataService]);
bootstrap(app.HeroDIInjectComponent, [
ng.core.provide('heroName', {useValue: 'Windstorm'})
]);
bootstrap(app.HeroDIInjectComponent2, [
ng.core.provide('heroName', {useValue: 'Bombasto'})
]);
bootstrap(app.HeroDIInjectAdditionalComponent);
bootstrap(app.HeroIOComponent);
bootstrap(app.HeroesHostBindingsComponent);
bootstrap(app.HeroesQueriesComponent);
});
// #docregion appimport
})(window.app = window.app || {});
// #enddocregion appimport
| {
"content_hash": "0b62a3dd11a482d5f7aa830084be16e9",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 60,
"avg_line_length": 30.743589743589745,
"alnum_prop": 0.7222685571309424,
"repo_name": "luisvt/angular.io",
"id": "ed92d6f823414083e0693e67ebb79f7bb56b7c6a",
"size": "1238",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "public/docs/_examples/cb-ts-to-js/js/app/main.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "113624"
},
{
"name": "Dart",
"bytes": "95019"
},
{
"name": "HTML",
"bytes": "1340992"
},
{
"name": "JavaScript",
"bytes": "208517"
},
{
"name": "TypeScript",
"bytes": "278129"
}
],
"symlink_target": ""
} |
<!-- markdownlint-disable MD033 -->
## Prerequisites
Follow all steps from [common.md](./common.md).
## Configure node type specific parameters (local machine)
### 1. Set node type
[`deployment/ansible/inventory/group_vars/all.yml`]
```yaml
type_name: "Priv-SN"
...
```
### 2. Specify target instance address
[`deployment/ansible/inventory/hosts.yml`]
```yaml
all:
...
children:
...
private_sentries:
hosts:
<private sentry node IP address or hostname>
...
```
### 3. Set persistent peers string in private sentry configuration
[`deployment/ansible/roles/configure/vars/private-sentry.yml`]
```yaml
config:
p2p:
persistent_peers: "<node1-ID>@<node1-IP>:26656,..."
...
```
`persistent_peers` value:
- `Validator` node with private IP + other orgs' validator/sentry nodes with public IPs.
- For `testnet-2.0` or `main-net` get the latest `persistent_peers` (other orgs' validator/sentry nodes with public IPs) from the CSA slack channel.
- Use the following command to get `node-ID` of a node: `./dcld tendermint show-node-id`.
### 4. (Optional) If you are joining a long-running network, enable `statesync` or use one of the options in [running-node-in-existing-network.md](../advanced/running-node-in-existing-network.md)
[`deployment/ansible/roles/configure/vars/public-sentry.yml`]
```yaml
config:
...
statesync:
enable: true
rpc_servers: "http(s):<node1-IP>:26657, ..."
trust_height: <trust-height>
trust_hash: "<trust-hash>"
...
```
<details>
<summary>Example for Testnet 2.0 (clickable) </summary>
```yaml
config:
statesync:
enable: true
rpc_servers: "https://on.test-net.dcl.csa-iot.org:26657,https://on.test-net.dcl.csa-iot.org:26657"
```
</details>
<details>
<summary>Example for Mainnet (clickable) </summary>
```yaml
config:
statesync:
enable: true
rpc_servers: "https://on.dcl.csa-iot.org:26657,https://on.dcl.csa-iot.org:26657"
```
</details>
> **_NOTE:_** You should provide at least 2 addresses for `rpc_servers`. It can be 2 identical addresses
You can use the following command to obtain `<trust-height>` and `<trust-hash>` of your network
```bash
curl -s http(s)://<host>:<port>/commit | jq "{height: .result.signed_header.header.height, hash: .result.signed_header.commit.block_id.hash}"
```
<details>
<summary>Example for Testnet 2.0 (clickable) </summary>
```bash
curl -s https://on.test-net.dcl.csa-iot.org:26657/commit | jq "{height: .result.signed_header.header.height, hash: .result.signed_header.commit.block_id.hash}"
```
</details>
<details>
<summary>Example for Mainnet (clickable) </summary>
```bash
curl -s https://on.dcl.csa-iot.org:26657/commit | jq "{height: .result.signed_header.header.height, hash: .result.signed_header.commit.block_id.hash}"
```
</details>
- `<host>` - RPC endpoint host of the network being joined
- `<port>` - RPC endpoint port of the network being joined
> **_NOTE:_** State sync is not attempted if the node has any local state (LastBlockHeight > 0)
## Run ansible (local machine)
### 1. Verify that all the configuration parameters from the previous section are correct
### 2. Run ansible
```bash
ansible-playbook -i ./deployment/ansible/inventory -u <target-host-ssh-user> ./deployment/ansible/deploy.yml
```
- `<target-host-ssh-username>` - target host ssh user
- Ansible provisioning can take several minutes depending on number of nodes being provisioned
## Deployment Verification (target machine)
### 1. Switch to cosmovisor user
```bash
sudo su -s /bin/bash cosmovisor
```
### 2. Query status
```bash
dcld status
```
| {
"content_hash": "382d7860a08a1c2dde1b73e6f9e71c91",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 195,
"avg_line_length": 25.09027777777778,
"alnum_prop": 0.6944367561583172,
"repo_name": "zigbee-alliance/distributed-compliance-ledger",
"id": "e2563b79afbeaee7767977ddd5cbbd7d71f081ed",
"size": "3657",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/running-node-ansible/private-sentry.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "5987"
},
{
"name": "Go",
"bytes": "2084178"
},
{
"name": "HCL",
"bytes": "48142"
},
{
"name": "HTML",
"bytes": "822"
},
{
"name": "JavaScript",
"bytes": "5835672"
},
{
"name": "Jinja",
"bytes": "1994"
},
{
"name": "Makefile",
"bytes": "3442"
},
{
"name": "Python",
"bytes": "27217"
},
{
"name": "SCSS",
"bytes": "25"
},
{
"name": "Shell",
"bytes": "441697"
},
{
"name": "Smarty",
"bytes": "1261"
},
{
"name": "TypeScript",
"bytes": "6633426"
},
{
"name": "Vue",
"bytes": "2411"
}
],
"symlink_target": ""
} |
<?php
namespace AmidaMVC\Module;
class Emitter extends AModule implements IfModule
{
/**
* @var \AmidaMVC\Tools\Emit
*/
var $_emitClass = '\AmidaMVC\Tools\Emit';
/**
* @var array list of supported commands.
*/
var $commands = array( '_view', '_src', '_raw', '_bare' );
// +-------------------------------------------------------------+
/**
* initialize class.
* @param array $option option to initialize.
*/
function _init( $option=array() ) {
if( isset( $option[ 'emitClass' ] ) ) {
$this->_emitClass = $option[ 'emitClass' ];
}
}
// +-------------------------------------------------------------+
/**
* renders data (to html) and output data.
* @param \AmidaMVC\Framework\Controller $_ctrl
* @param \AmidaMVC\Framework\PageObj $_pageObj
* @param array $option
* @return bool
*/
function actionDefault( $_ctrl, &$_pageObj, $option=array() )
{
if( $command = $this->findCommand( $_ctrl->getCommands() ) ) {
$method = $_ctrl->makeActionMethod( $command );
return $this->$method( $_ctrl, $_pageObj, $option );
}
// default is view method.
return $this->action_view( $_ctrl, $_pageObj, $option );
}
// +-------------------------------------------------------------+
/**
* @param \AmidaMVC\Framework\Controller $_ctrl
* @param \AmidaMVC\Framework\PageObj $_pageObj
* @param array $option
* @return bool
*/
function action_view( $_ctrl, &$_pageObj, $option=array() ) {
$this->convert( $_pageObj );
$this->template( $_ctrl, $_pageObj );
$_pageObj->emit();
return TRUE;
}
// +-------------------------------------------------------------+
/**
* @param \AmidaMVC\Framework\Controller $_ctrl
* @param \AmidaMVC\Framework\PageObj $_pageObj
* @param array $option
* @return bool
*/
function action_bare( $_ctrl, &$_pageObj, $option=array() ) {
$this->convert( $_pageObj );
$_pageObj->emit();
return TRUE;
}
// +-------------------------------------------------------------+
/**
* @param \AmidaMVC\Framework\Controller $_ctrl
* @param \AmidaMVC\Framework\PageObj $_pageObj
* @param array $option
* @return bool
*/
function action_raw( $_ctrl, &$_pageObj, $option=array() ) {
$_pageObj->contentType( 'text' );
$_pageObj->emit();
return TRUE;
}
// +-------------------------------------------------------------+
/**
* @param \AmidaMVC\Framework\Controller $_ctrl
* @param \AmidaMVC\Framework\PageObj $_pageObj
* @param array $option
* @return bool
*/
function action_src( $_ctrl, &$_pageObj, $option=array() ) {
$_pageObj->contentType( 'php' );
$this->convert( $_pageObj );
$this->template( $_ctrl, $_pageObj );
$_pageObj->emit();
return TRUE;
}
// +-------------------------------------------------------------+
/**
* action for page not found; this action is invoked only from
* _App.php or some other models... reload pageNofFound file if
* set in siteObj. if not, generate simple err404 contents.
* @param \AmidaMVC\Framework\Controller $_ctrl
* @param \AmidaMVC\Framework\PageObj $_pageObj
* @return array
*/
function action_PageNotFound( $_ctrl, $_pageObj )
{
// show some excuses, or blame user for not finding a page.
if( $_ctrl->getOption( 'pageNotFound_file' ) ) {
// pageNotFound file is set. should load this page.
$_ctrl->prependModule( array(
array( '\AmidaMVC\AppSimple\Loader', 'loader' ),
array( '\AmidaMVC\AppSimple\Emitter', 'emitter' ),
) );
return array();
}
$_pageObj->title( 'Page Not Found' );
$contents = "#Error 404\n\nrequested page not found...\n\n";
$contents .= "[back to top](" . $_ctrl->getBaseUrl() . ")";
$_pageObj->setContent( $contents );
$_pageObj->contentType( 'markdown' );
$_pageObj->status( '404' );
$_ctrl->setMyAction( $_ctrl->defaultAct() );
return array();
}
// +-------------------------------------------------------------+
/**
* convert contents to HTML for md/text.
* @param \AmidaMVC\Framework\PageObj $_pageObj
*/
function convert( $_pageObj )
{
$content = $_pageObj->getContent();
$type = $_pageObj->contentType();
$emit = $this->_emitClass;
$emit::convertContentToHtml( $content, $type );
$_pageObj->setContent( $content );
$_pageObj->contentType( $type );
}
// +-------------------------------------------------------------+
/**
* inject into template if contentType is html.
* @param \AmidaMVC\Framework\Controller $_ctrl
* @param \AmidaMVC\Framework\PageObj $_pageObj
*/
function template( $_ctrl, $_pageObj )
{
if( $_pageObj->contentType() == 'html' ) {
$emit = $this->_emitClass;
// if template_file is set, use it as relative to ctrl_root.
$template = NULL;
if( $_ctrl->getOption( 'template_file' ) ) {
$template = $_ctrl->findFile( $_ctrl->getOption( 'template_file' ) );
}
$content_data = array( '_ctrl' => $_ctrl, '_pageObj' => $_pageObj );
$content = $emit::inject( $template, $content_data );
$_pageObj->setContent( $content );
}
}
// +-------------------------------------------------------------+
} | {
"content_hash": "d5f99318bdadf5eac6a8f7d7d674843e",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 85,
"avg_line_length": 36.75,
"alnum_prop": 0.4754927612070469,
"repo_name": "asaokamei/AmidaMVC",
"id": "380c2a3712c06ec2e87ffab90a2ee11b745e4f91",
"size": "5733",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AmidaMVC/Module/Emitter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1445"
},
{
"name": "JavaScript",
"bytes": "135826"
},
{
"name": "PHP",
"bytes": "295790"
},
{
"name": "Visual Basic",
"bytes": "262"
}
],
"symlink_target": ""
} |
//package org.jasig.cas.services;
//import org.springframework.orm.jpa.support.JpaDaoSupport;
//import java.util.List;
/**
* Implementation of the ServiceRegistryDao based on JPA.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.1
*/
public class JpaServiceRegistryDaoImpl : JpaDaoSupport :
ServiceRegistryDao {
public bool delete( RegisteredService registeredService) {
getJpaTemplate().remove(
getJpaTemplate().contains(registeredService) ? registeredService
: getJpaTemplate().merge(registeredService));
return true;
}
public List<RegisteredService> load() {
return getJpaTemplate().find("select r from AbstractRegisteredService r");
}
public RegisteredService save( RegisteredService registeredService) {
bool isNew = registeredService.getId() == -1;
RegisteredService r = getJpaTemplate().merge(registeredService);
if (!isNew) {
getJpaTemplate().persist(r);
}
return r;
}
public RegisteredService findServiceById( long id) {
return getJpaTemplate().find(AbstractRegisteredService.class, id);
}
}
| {
"content_hash": "c6fd51c2be4b821a5ef67b9ea874e9ef",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 82,
"avg_line_length": 28.386363636363637,
"alnum_prop": 0.6413130504403523,
"repo_name": "zbw911/CasServer",
"id": "9bc1ce2ef41291d1970c9470526a9c8ea1469812",
"size": "2062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CASLIB/NCAS/jasig/services/JpaServiceRegistryDaoImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "99"
},
{
"name": "C#",
"bytes": "843819"
},
{
"name": "CSS",
"bytes": "363435"
},
{
"name": "Java",
"bytes": "170158"
},
{
"name": "JavaScript",
"bytes": "392325"
}
],
"symlink_target": ""
} |
package com.signalcollect.dcop.vertices.id
class VariableId(num : Int) extends MaxSumId{
//Variable nodes have ids of the form V1, V2, ....
val id = "V" + num
} | {
"content_hash": "883ed30a2dd37d2335a273e651ff2146",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 51,
"avg_line_length": 18.666666666666668,
"alnum_prop": 0.6845238095238095,
"repo_name": "gmazlami/dcop-maxsum",
"id": "847bd161741c9706e84c79c0f98750c5a21f92ea",
"size": "815",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/com/signalcollect/dcop/vertices/id/VariableId.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "45940"
},
{
"name": "JavaScript",
"bytes": "954658"
},
{
"name": "Scala",
"bytes": "833789"
}
],
"symlink_target": ""
} |
export * from './intern';
export const environments = [
{ browserName: 'internet explorer', version: ['9.0', '10.0', '11.0'], platform: 'Windows 7' },
{ browserName: 'MicrosoftEdge', platform: 'Windows 10' },
{ browserName: 'firefox', platform: 'Windows 10' },
{ browserName: 'chrome', platform: 'Windows 10' },
{ browserName: 'safari', version: '8.0', platform: 'OS X 10.10' },
{ browserName: 'safari', version: '9.0', platform: 'OS X 10.11' },
{ browserName: 'android', deviceName: 'Google Nexus 7 HD Emulator' },
{ browserName: 'iphone', version: [ '7.1', '8.4' ] }
/* saucelabs has stability issues with iphone 9.1 and 9.2 */
];
/* SauceLabs supports more max concurrency */
export const maxConcurrency = 4;
export const tunnel = 'SauceLabsTunnel';
| {
"content_hash": "6c0486c3cd19568a8718238e4479951c",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 95,
"avg_line_length": 42.5,
"alnum_prop": 0.6588235294117647,
"repo_name": "kitsonk/widgets",
"id": "0fedf2117511798859f73152c4b79d9aa428f80e",
"size": "765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/intern-saucelabs.ts",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1085"
},
{
"name": "HTML",
"bytes": "1753"
},
{
"name": "JavaScript",
"bytes": "9758"
},
{
"name": "TypeScript",
"bytes": "72941"
}
],
"symlink_target": ""
} |
{
"General": {
"Buttons": {
"Add": "Hinzufügen",
"Cancel": "Abbrechen",
"Copy": "Kopieren",
"Delete": "Löschen",
"Edit": "Bearbeiten",
"ForceDelete": "zwangs-löschen",
"NotSave": "Nicht speichern",
"Permissions": "Berechtigungen",
"Refresh": "Aktualisieren",
"Rename": "Umbenennen",
"Save": "Speichern",
"System": "Erweitere System-Funktionen",
"Export": "export",
"Import": "import"
},
"Messages": {
"Loading": "wird geladen...",
"NothingFound": "Keine Datensätze gefunden",
"CantDelete": "Kann nicht gelöscht werden: {{target}}"
},
"Questions": {
"Delete": "Wirklich löschen? {{target}}",
"DeleteEntity": "'{{title}}' ({{id}}) löschen?",
"SystemInput": "Das ist für fortgeschrittene Benutzer. Benutze es nur, wenn du weisst, was du machst. \n\n Befehl eingeben:",
"ForceDelete": "möchtest du '{{title}}' ({{id}}) zwangs-löschen?"
},
"Terms": {
"Title": "Titel"
}
},
"DataType": {
"All": {
"Title": "Allgemeine Einstellungen"
},
"Boolean": {
"Short": "Ja/Nein",
"ShortTech": "Boolean",
"Choice": "Boolean (ja/nein)",
"Explanation": "ja/nein oder true/false Werte"
},
"DateTime": {
"Short": "Datum/Uhrzeit",
"ShortTech": "DateTime",
"Choice": "Datum und/oder Zeit",
"Explanation": "Für Datum, Zeit oder kombinierte Werte"
},
"Entity": {
"Short": "Inhalt(e)",
"ShortTech": "Entität",
"Choice": "Entität (andere Inhalte)",
"Explanation": "Ein oder mehrere andere Inhalte"
},
"Hyperlink": {
"Short": "Link",
"ShortTech": "Hyperlink",
"Choice": "Link / Datei Referenz",
"Explanation": "Link oder Referenz zu einer Datei / Bild"
},
"Number": {
"Short": "Nummer",
"ShortTech": "Decimal",
"Choice": "Nummer",
"Explanation": "Jede Art von Nummer"
},
"String": {
"Short": "Text",
"ShortTech": "String",
"Choice": "Text / Zeichenfolge",
"Explanation": "Jede Art von Text"
},
"Empty": {
"Short": "Leer",
"ShortTech": "Empty",
"Choice": "Leer - z.B. für Formular-Gruppierungen",
"Explanation": "Hilft, das Formular zu strukturieren"
},
"Custom": {
"Short": "Benutzerdefiniert",
"ShortTech": "Custom",
"Choice": "Benutzerdefiniert - ui-tools oder benutzerdefinierte Typen",
"Explanation": "Für Typen wie GPS-Picker (welcher mehrere Felder verwenden) oder für benutzerdefinierte Datenstrukturen wie z.B. ein Array oder ein JSON-Objekt"
}
},
"ContentTypes": {
"Title": "Inhaltstypen und Daten",
"TypesTable": {
"Name": "Name",
"Description": "Beschreibung",
"Fields": "Felder",
"Items": "Inhalte",
"Actions": ""
},
"TitleExportImport": "Export / Import",
"Buttons": {
"Export": "Export",
"Import": "Import",
"ChangeScope": "Scope ändern",
"ChangeScopeQuestion": "Das ist eine erweiterte Funktion um Inhaltstypen aus einem anderen Scope anzuzeigen. Benutze es nur wenn du weisst was du machst. Normalerweise sind die Inhaltstypen aus einem anderen Scope versteckt."
},
"Messages": {
"SharedDefinition": "Dieser Inhaltstyp benutzt die Konfiguration von #{{SharedDefId}}, deshalb kann er hier nicht bearbeitet werden - 2sxc.org/help?tag=shared-types",
"TypeOwn": "this is an own content-type, it does not use the definition of another content-type - read 2sxc.org/help?tag=shared-types",
"TypeShared": "this content-type inherits the definition of #{{SharedDefId}} - read 2sxc.org/help?tag=shared-types"
}
},
"ContentTypeEdit": {
"Title": "Inhaltstyp bearbeiten",
"Name": "Name",
"Description": "Beschreibung",
"Scope": "Scope"
},
"Fields": {
"Title": "Inhaltstyp Felder",
"TitleEdit": "Feld hinzufügen",
"Table": {
"Title": "Titel",
"Name": "Name (statisch)",
"DataType": "Datentyp",
"Label": "Label",
"InputType": "Eingabetyp",
"Notes": "Notizen",
"Sort": "Sortierung",
"Action": ""
},
"General": "Allgemein"
},
"Permissions": {
"Title": "Berechtigungen",
"Table": {
"Name": "Name",
"Id": "ID",
"Condition": "Bedingung",
"Grant": "Gewährung",
"Actions": ""
}
},
"Pipeline": {
"Manage": {
"Title": "Visuelle Queries / Pipelines",
"Intro": "Mit dem visuellen Abfragen Designer können benutzerdefinierte Abfragen erstellt und aus verschiedenen Quellen zusammengeführt werden. Dies kann in Vorlagen mit direkten JSON-Abfragen verwendet werden (Wenn die Berechtigung erteilt ist). <a href='http://2sxc.org/en/help?tag=visualquerydesigner' target='_blank'>Mehr Informationen</a>",
"Table": {
"Id": "ID",
"Name": "Name",
"Description": "Beschreibung",
"Actions": ""
}
},
"Designer": {},
"Stats": {
"Title": "Resultate der Abfrage",
"Intro": "Die vollständige Abfrage wurde in der Konsole ausgegeben. Weiter unten findest du weitere Debug-Informationen.",
"ParamTitle": "Parameter & Statistiken",
"ExecutedIn": "Ausgeführt in {{ms}}ms ({{ticks}} ticks)",
"QueryTitle": "Resultate",
"SourcesAndStreamsTitle": "Quellen und Streams",
"Sources": {
"Title": "Quellen",
"Guid": "Guid",
"Type": "Typ",
"Config": "Konfiguration"
},
"Streams": {
"Title": "Streams",
"Source": "Quelle",
"Target": "Ziel",
"Items": "Einträge",
"Error": "Fehler"
}
}
},
"Content": {
"Manage": {
"Title": "Inhalt / Daten verwalten",
"Table": {
"Id": "ID",
"Status": "Status",
"Title": "Titel",
"Actions": ""
},
"NoTitle": "- kein Titel -"
},
"Publish": {
"PnV": "Publiziert und sichtbar",
"DoP": "Dies ist ein Entwurf einer anderen, veröffentlichten Version.",
"D": "Nicht publiziert im Moment",
"HD": "Hat einen Entwurf: {{id}}",
"HP": "Ersetzt die publizierte Version"
},
"Export": {
"Title": "Inhalt / Daten exportieren",
"Help": "Es wird eine xml-Datei erstellt welche im Excel bearbeitet werden kann. Um neue Daten zu importieren kann diese xml-Datei als Schema im Excel verwendet werden. Besuche <a href='http://2sxc.org/help' target='_blank'>http://2sxc.org/help</a> für mehr Informationen.",
"Commands": {
"Export": "Export"
},
"Fields": {
"Language": {
"Label": "Sprachen",
"Options": {
"All": "Alle"
}
},
"LanguageReferences": {
"Label": "Werte, die auf andere Sprachen verweisen",
"Options": {
"Link": "Verweise auf andere Sprachen behalten (für Re-Import)",
"Resolve": "Referenzen mit Werten ersetzen"
}
},
"ResourcesReferences": {
"Label": "Datei / Seitenverweise",
"Options": {
"Link": "Verweise beibehalten (für Re-Import, z.B. Page:4711)",
"Resolve": "Verweise mit entsprechender URL ersetzen (z.B. /Portals/0...)"
}
},
"RecordExport": {
"Label": "Daten exportieren",
"Options": {
"Blank": "Nein, nur Schema exportieren (für den Import von neuen Datensätzen)",
"All": "Ja, alle Inhalte exportieren",
"Selection": "Nur ausgewählte {{count}} Elemente"
}
}
}
},
"Import": {
"Title": "Inhalt / Daten importieren",
"TitleSteps": "{{step}} von 3",
"Help": "Importiert Datensätze in 2sxc. Stelle sicher, dass der Datentyp bereits definiert ist, und dass das XML vorgängig mit dem Export generiert wurde. Für weitere Infos: <a href='http://2sxc.org/help' target='_blank'>http://2sxc.org/help</a>.",
"Fields": {
"File": {
"Label": "Datei auswählen"
},
"ResourcesReferences": {
"Label": "Verweise auf Seiten / Dateien",
"Options": {
"Keep": "Links wie in der Import-Datei angegeben importieren (z.B. /Portals/...)",
"Resolve": "Versuche, die Verweise aufzulösen"
}
},
"ClearEntities": {
"Label": "Alle anderen Datensätze entfernen",
"Options": {
"None": "Behalte die Datensätze, die im Import nicht enthalten sind",
"All": "Entferne die Datensätze, die im Import nicht enthalten sind"
}
}
},
"Commands": {
"Preview": "Vorschau des Imports",
"Import": "Import"
},
"Messages": {
"BackupContentBefore": "Stelle sicher, dass du ein Backup der Datenbank hast, bevor du fortfährst!",
"WaitingForResponse": "Bitte warten...",
"ImportSucceeded": "Import fertiggestellt.",
"ImportFailed": "Import fehlgeschlagen.",
"ImportCanTakeSomeTime": "Hinweis: Der Import kann mehrere Minuten dauern."
},
"Evaluation": {
"Error": {
"Title": "Try to import file '{{filename}}'",
"Codes": {
"0": "Unknown error occured.",
"1": "Selected content-type does not exist.",
"2": "Document is not a valid XML file.",
"3": "Selected content-type does not match the content-type in the XML file.",
"4": "The language is not supported.",
"5": "The document does not specify all languages for all entities.",
"6": "Language reference cannot be parsed, the language is not supported.",
"7": "Language reference cannot be parsed, the read-write protection is not supported.",
"8": "Value cannot be read, because of it has an invalid format."
},
"Detail": "Details: {{detail}}",
"LineNumber": "Line-no: {{number}}",
"LineDetail": "Line-details: {{detail}}"
},
"Detail": {
"Title": "Try to import file '{{filename}}'",
"File": {
"Title": "File contains:",
"ElementCount": "{{count}} content-items (records/entities)",
"LanguageCount": "{{count}} languages",
"Attributes": "{{count}} columns: {{attributes}}"
},
"Entities": {
"Title": "If you press Import, it will:",
"Create": "Create {{count}} content-items",
"Update": "Update {{count}} content-items",
"Delete": "Delete {{count}} content-items",
"AttributesIgnored": "Ignore {{count}} columns: {{attributes}}"
}
}
}
},
"History": {
"Title": "Versionen von {{id}}",
"Table": {
"Id": "#",
"When": "Wann",
"User": "Benutzer",
"Actions": ""
}
}
},
"AdvancedMode": {
"Info": {
"Available": "Dieser Dialog einen erweiterten / Debug Modus für Power-Users – erfahre mehr 2sxc.org/help?tag=debug-mode",
"TurnOn": "erweiterten / Debug Modus ein",
"TurnOff": "erweiterten / Debug Modus aus"
}
}
} | {
"content_hash": "6857049d9126fd78a8733cbe39fed62d",
"timestamp": "",
"source": "github",
"line_count": 316,
"max_line_length": 348,
"avg_line_length": 32.25632911392405,
"alnum_prop": 0.6101245953105072,
"repo_name": "2sic/2sxc-eav-languages",
"id": "e5a699df32833a9d56efee86d0fc449eb5405d3e",
"size": "10236",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/i18n/admin-de.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "68671"
}
],
"symlink_target": ""
} |
CREATE TABLE `webcore_page_photos` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned DEFAULT NULL,
`site_id` int(10) unsigned DEFAULT NULL,
`caption` text,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
/*
`crop_x` int(10) unsigned DEFAULT NULL,
`crop_y` int(10) unsigned DEFAULT NULL,
`crop_h` int(10) unsigned DEFAULT NULL,
`crop_w` int(10) unsigned DEFAULT NULL,
*/
PRIMARY KEY (`id`)
);
| {
"content_hash": "b7c4e11ef655a73e852142639d647e47",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 48,
"avg_line_length": 31.2,
"alnum_prop": 0.6794871794871795,
"repo_name": "tmaly1980/webcore",
"id": "124c69e2572b77abe3383629d1fbd035ca11cd0e",
"size": "468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sql/page_photos.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "46648"
},
{
"name": "HTML",
"bytes": "30952"
},
{
"name": "JavaScript",
"bytes": "86838"
},
{
"name": "Ruby",
"bytes": "74639"
}
],
"symlink_target": ""
} |
<?php
namespace Core\Auth;
use Core\Database\Database;
class DBAuth
{
private $db;
public function __construct(Database $db)
{
$this->db = $db;
}
public function getUserId(){
if($this->logged()){
return $_SESSION['auth'];
}
return false;
}
// Checks in the database if username and password given by user are correct
// @param $username / @param $password
// @return boolean return true if user exists and password is correct else return false.
public function login($username, $password)
{
$user = $this->db->prepare('SELECT * FROM users WHERE username = ?', [$username], null, true);
if($user){
if($user->password === sha1($password)){
$_SESSION['auth'] = $user->id;
$_SESSION['username'] = $user->username;
$_SESSION['role'] = $user->role;
// $_SESSION['email'] = $user->email;
// $_SESSION['userLocked'] = $user->userLocked;
return true;
}
}
return false;
}
// Check if the user is logged.
public function logged()
{
return isset($_SESSION['auth']);
}
}
/**
// Check if the user is an admin
public function isAdmin()
{
if (!isset($_SESSION['role']))
{
return false;
}
return ($_SESSION['role'] === 'admin');
// @return bool
}
// Check if the user is locked
public function userLocked()
{
if (!isset($_SESSION['userLocked'])){
return false;
}
return ($_SESSION['userLocked'] == 1);
}
// @return bool
}
*/ | {
"content_hash": "7ed5c22502ab582f8832d8d3215ed164",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 102,
"avg_line_length": 22.493333333333332,
"alnum_prop": 0.5168938944872555,
"repo_name": "Mickey3d/bloogy",
"id": "dd0500ee428cdaafa1c1f6684d7188c6ea885637",
"size": "1687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/Auth/DBAuth.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "31721"
},
{
"name": "JavaScript",
"bytes": "13574"
},
{
"name": "PHP",
"bytes": "207232"
}
],
"symlink_target": ""
} |
package com.facebook.buck.jvm.java;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.jar.Attributes.Name.IMPLEMENTATION_VERSION;
import static java.util.jar.Attributes.Name.MANIFEST_VERSION;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.event.BuckEventBusForTests;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.TestProjectFilesystems;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.TestExecutionContext;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.testutil.ZipArchive;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.zip.CustomZipOutputStream;
import com.facebook.buck.util.zip.ZipConstants;
import com.facebook.buck.util.zip.ZipOutputStreams;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.compress.archivers.zip.ZipUtil;
import org.junit.Rule;
import org.junit.Test;
public class JarDirectoryStepTest {
@Rule public TemporaryPaths folder = new TemporaryPaths();
@Test
public void shouldNotThrowAnExceptionWhenAddingDuplicateEntries()
throws InterruptedException, IOException {
Path zipup = folder.newFolder("zipup");
Path first = createZip(zipup.resolve("a.zip"), "example.txt");
Path second = createZip(zipup.resolve("b.zip"), "example.txt", "com/example/Main.class");
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(zipup),
JarParameters.builder()
.setJarPath(Paths.get("output.jar"))
.setEntriesToJar(ImmutableSortedSet.of(first.getFileName(), second.getFileName()))
.setMainClass(Optional.of("com.example.Main"))
.setMergeManifests(true)
.build());
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context).getExitCode();
assertEquals(0, returnCode);
Path zip = zipup.resolve("output.jar");
assertTrue(Files.exists(zip));
// "example.txt" "Main.class" and the MANIFEST.MF.
assertZipFileCountIs(3, zip);
assertZipContains(zip, "example.txt");
}
@Test
public void shouldNotifyEventBusWhenDuplicateClassesAreFound()
throws InterruptedException, IOException {
Path jarDirectory = folder.newFolder("jarDir");
Path first =
createZip(
jarDirectory.resolve("a.jar"),
"com/example/Main.class",
"com/example/common/Helper.class");
Path second = createZip(jarDirectory.resolve("b.jar"), "com/example/common/Helper.class");
Path outputPath = Paths.get("output.jar");
ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(jarDirectory);
JarDirectoryStep step =
new JarDirectoryStep(
filesystem,
JarParameters.builder()
.setJarPath(outputPath)
.setEntriesToJar(ImmutableSortedSet.of(first.getFileName(), second.getFileName()))
.setMainClass(Optional.of("com.example.Main"))
.setMergeManifests(true)
.build());
ExecutionContext context = TestExecutionContext.newInstance();
BuckEventBusForTests.CapturingConsoleEventListener listener =
new BuckEventBusForTests.CapturingConsoleEventListener();
context.getBuckEventBus().register(listener);
step.execute(context);
String expectedMessage =
String.format(
"Duplicate found when adding 'com/example/common/Helper.class' to '%s' from '%s'",
filesystem.getPathForRelativePath(outputPath), second.toAbsolutePath());
assertThat(listener.getLogMessages(), hasItem(expectedMessage));
}
@Test(expected = HumanReadableException.class)
public void shouldFailIfMainClassMissing() throws InterruptedException, IOException {
Path zipup = folder.newFolder("zipup");
Path zip = createZip(zipup.resolve("a.zip"), "com/example/Main.class");
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(zipup),
JarParameters.builder()
.setJarPath(Paths.get("output.jar"))
.setEntriesToJar(ImmutableSortedSet.of(zip.getFileName()))
.setMainClass(Optional.of("com.example.MissingMain"))
.setMergeManifests(true)
.build());
TestConsole console = new TestConsole();
ExecutionContext context = TestExecutionContext.newBuilder().setConsole(console).build();
try {
step.execute(context);
} catch (HumanReadableException e) {
assertEquals(
"ERROR: Main class com.example.MissingMain does not exist.",
e.getHumanReadableErrorMessage());
throw e;
}
}
@Test
public void shouldNotComplainWhenDuplicateDirectoryNamesAreAdded()
throws InterruptedException, IOException {
Path zipup = folder.newFolder();
Path first = createZip(zipup.resolve("first.zip"), "dir/example.txt", "dir/root1file.txt");
Path second =
createZip(
zipup.resolve("second.zip"),
"dir/example.txt",
"dir/root2file.txt",
"com/example/Main.class");
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(zipup),
JarParameters.builder()
.setJarPath(Paths.get("output.jar"))
.setEntriesToJar(ImmutableSortedSet.of(first.getFileName(), second.getFileName()))
.setMainClass(Optional.of("com.example.Main"))
.setMergeManifests(true)
.build());
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context).getExitCode();
assertEquals(0, returnCode);
Path zip = zipup.resolve("output.jar");
// The three below plus the manifest and Main.class.
assertZipFileCountIs(5, zip);
assertZipContains(zip, "dir/example.txt", "dir/root1file.txt", "dir/root2file.txt");
}
@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars()
throws InterruptedException, IOException {
String expected = "1.4";
// Write the manifest, setting the implementation version
Path tmp = folder.newFolder();
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
Path manifestFile = tmp.resolve("manifest");
try (OutputStream fos = Files.newOutputStream(manifestFile)) {
manifest.write(fos);
}
// Write another manifest, setting the implementation version to something else
manifest = new Manifest();
manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");
Path input = tmp.resolve("input.jar");
try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
out.putNextEntry(entry);
manifest.write(out);
}
Path output = tmp.resolve("output.jar");
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(tmp),
JarParameters.builder()
.setJarPath(output)
.setEntriesToJar(ImmutableSortedSet.of(Paths.get("input.jar")))
.setManifestFile(Optional.of(tmp.resolve("manifest")))
.setMergeManifests(true)
.build());
ExecutionContext context = TestExecutionContext.newInstance();
assertEquals(0, step.execute(context).getExitCode());
try (ZipArchive zipArchive = new ZipArchive(output, false)) {
byte[] rawManifest = zipArchive.readFully("META-INF/MANIFEST.MF");
manifest = new Manifest(new ByteArrayInputStream(rawManifest));
String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);
assertEquals(expected, version);
}
}
@Test
public void jarsShouldContainDirectoryEntries() throws InterruptedException, IOException {
Path zipup = folder.newFolder("dir-zip");
Path subdir = zipup.resolve("dir/subdir");
Files.createDirectories(subdir);
Files.write(subdir.resolve("a.txt"), "cake".getBytes());
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(zipup),
JarParameters.builder()
.setJarPath(Paths.get("output.jar"))
.setEntriesToJar(ImmutableSortedSet.of(zipup))
.setMergeManifests(true)
.build());
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context).getExitCode();
assertEquals(0, returnCode);
Path zip = zipup.resolve("output.jar");
assertTrue(Files.exists(zip));
// Iterate over each of the entries, expecting to see the directory names as entries.
Set<String> expected = Sets.newHashSet("dir/", "dir/subdir/");
try (ZipInputStream is = new ZipInputStream(Files.newInputStream(zip))) {
for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
expected.remove(entry.getName());
}
}
assertTrue("Didn't see entries for: " + expected, expected.isEmpty());
}
@Test
public void shouldNotMergeManifestsIfRequested() throws InterruptedException, IOException {
Manifest fromJar = createManifestWithExampleSection(ImmutableMap.of("Not-Seen", "ever"));
Manifest fromUser = createManifestWithExampleSection(ImmutableMap.of("cake", "cheese"));
Manifest seenManifest = jarDirectoryAndReadManifest(fromJar, fromUser, false);
assertEquals(fromUser.getEntries(), seenManifest.getEntries());
}
@Test
public void shouldMergeManifestsIfAsked() throws InterruptedException, IOException {
Manifest fromJar = createManifestWithExampleSection(ImmutableMap.of("Not-Seen", "ever"));
Manifest fromUser = createManifestWithExampleSection(ImmutableMap.of("cake", "cheese"));
Manifest seenManifest = jarDirectoryAndReadManifest(fromJar, fromUser, true);
Manifest expectedManifest = new Manifest(fromJar);
Attributes attrs = new Attributes();
attrs.putValue("Not-Seen", "ever");
attrs.putValue("cake", "cheese");
expectedManifest.getEntries().put("example", attrs);
assertEquals(expectedManifest.getEntries(), seenManifest.getEntries());
}
@Test
public void shouldSortManifestAttributesAndEntries() throws InterruptedException, IOException {
Manifest fromJar =
createManifestWithExampleSection(ImmutableMap.of("foo", "bar", "baz", "waz"));
Manifest fromUser =
createManifestWithExampleSection(ImmutableMap.of("bar", "foo", "waz", "baz"));
String seenManifest =
new String(jarDirectoryAndReadManifestContents(fromJar, fromUser, true), UTF_8);
assertEquals(
Joiner.on("\r\n")
.join(
"Manifest-Version: 1.0",
"",
"Name: example",
"bar: foo",
"baz: waz",
"foo: bar",
"waz: baz",
"",
""),
seenManifest);
}
@Test
public void shouldNotIncludeFilesInBlacklist() throws InterruptedException, IOException {
Path zipup = folder.newFolder();
Path first =
createZip(
zipup.resolve("first.zip"),
"dir/file1.txt",
"dir/file2.class",
"com/example/Main.class");
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(zipup),
JarParameters.builder()
.setJarPath(Paths.get("output.jar"))
.setEntriesToJar(ImmutableSortedSet.of(first.getFileName()))
.setMainClass(Optional.of("com.example.Main"))
.setMergeManifests(true)
.setRemoveEntryPredicate(
new RemoveClassesPatternsMatcher(ImmutableSet.of(Pattern.compile(".*2.*"))))
.build());
assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());
Path zip = zipup.resolve("output.jar");
// 3 files in total: file1.txt, & com/example/Main.class & the manifest.
assertZipFileCountIs(3, zip);
assertZipContains(zip, "dir/file1.txt");
assertZipDoesNotContain(zip, "dir/file2.txt");
}
@Test
public void shouldNotIncludeFilesInClassesToRemoveFromJar()
throws InterruptedException, IOException {
Path zipup = folder.newFolder();
Path first =
createZip(
zipup.resolve("first.zip"),
"com/example/A.class",
"com/example/B.class",
"com/example/C.class");
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(zipup),
JarParameters.builder()
.setJarPath(Paths.get("output.jar"))
.setEntriesToJar(ImmutableSortedSet.of(first.getFileName()))
.setMainClass(Optional.of("com.example.A"))
.setMergeManifests(true)
.setRemoveEntryPredicate(
new RemoveClassesPatternsMatcher(
ImmutableSet.of(
Pattern.compile("com.example.B"), Pattern.compile("com.example.C"))))
.build());
assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());
Path zip = zipup.resolve("output.jar");
// 2 files in total: com/example/A/class & the manifest.
assertZipFileCountIs(2, zip);
assertZipContains(zip, "com/example/A.class");
assertZipDoesNotContain(zip, "com/example/B.class");
assertZipDoesNotContain(zip, "com/example/C.class");
}
@Test
public void timesAreSanitized() throws InterruptedException, IOException {
Path zipup = folder.newFolder("dir-zip");
// Create a jar file with a file and a directory.
Path subdir = zipup.resolve("dir");
Files.createDirectories(subdir);
Files.write(subdir.resolve("a.txt"), "cake".getBytes());
Path outputJar = folder.getRoot().resolve("output.jar");
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(folder.getRoot()),
JarParameters.builder()
.setJarPath(outputJar)
.setEntriesToJar(ImmutableSortedSet.of(zipup))
.setMergeManifests(true)
.build());
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context).getExitCode();
assertEquals(0, returnCode);
// Iterate over each of the entries, expecting to see all zeros in the time fields.
assertTrue(Files.exists(outputJar));
Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
try (ZipInputStream is = new ZipInputStream(new FileInputStream(outputJar.toFile()))) {
for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
assertEquals(entry.getName(), dosEpoch, new Date(entry.getTime()));
}
}
}
/**
* From the constructor of {@link JarInputStream}:
*
* <p>This implementation assumes the META-INF/MANIFEST.MF entry should be either the first or the
* second entry (when preceded by the dir META-INF/). It skips the META-INF/ and then "consumes"
* the MANIFEST.MF to initialize the Manifest object.
*
* <p>A simple implementation of {@link JarDirectoryStep} would iterate over all entries to be
* included, adding them to the output jar, while merging manifest files, writing the merged
* manifest as the last item in the jar. That will generate jars the {@code JarInputStream} won't
* be able to find the manifest for.
*/
@Test
public void manifestShouldBeSecondEntryInJar() throws Exception {
Path manifestPath = Paths.get(JarFile.MANIFEST_NAME);
// Create a directory with a manifest in it and more than two files.
Path dir = folder.newFolder();
Manifest dirManifest = new Manifest();
Attributes attrs = new Attributes();
attrs.putValue("From-Dir", "cheese");
dirManifest.getEntries().put("Section", attrs);
Files.createDirectories(dir.resolve(manifestPath).getParent());
try (OutputStream out = Files.newOutputStream(dir.resolve(manifestPath))) {
dirManifest.write(out);
}
Files.write(dir.resolve("A.txt"), "hello world".getBytes(UTF_8));
Files.write(dir.resolve("B.txt"), "hello world".getBytes(UTF_8));
Files.write(dir.resolve("aa.txt"), "hello world".getBytes(UTF_8));
Files.write(dir.resolve("bb.txt"), "hello world".getBytes(UTF_8));
// Create a jar with a manifest and more than two other files.
Path inputJar = folder.newFile("example.jar");
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(inputJar))) {
byte[] data = "hello world".getBytes(UTF_8);
ZipEntry entry = new ZipEntry("C.txt");
zos.putNextEntry(entry);
zos.write(data, 0, data.length);
zos.closeEntry();
entry = new ZipEntry("cc.txt");
zos.putNextEntry(entry);
zos.write(data, 0, data.length);
zos.closeEntry();
entry = new ZipEntry("META-INF/");
zos.putNextEntry(entry);
zos.closeEntry();
// Note: at end of the stream. Technically invalid.
entry = new ZipEntry(JarFile.MANIFEST_NAME);
zos.putNextEntry(entry);
Manifest zipManifest = new Manifest();
attrs = new Attributes();
attrs.putValue("From-Zip", "peas");
zipManifest.getEntries().put("Section", attrs);
zipManifest.write(zos);
zos.closeEntry();
}
// Merge and check that the manifest includes everything
Path output = folder.newFile("output.jar");
JarDirectoryStep step =
new JarDirectoryStep(
new FakeProjectFilesystem(folder.getRoot()),
JarParameters.builder()
.setJarPath(output)
.setEntriesToJar(ImmutableSortedSet.of(dir, inputJar))
.setMergeManifests(true)
.build());
int exitCode = step.execute(TestExecutionContext.newInstance()).getExitCode();
assertEquals(0, exitCode);
Manifest manifest;
try (InputStream is = Files.newInputStream(output);
JarInputStream jis = new JarInputStream(is)) {
manifest = jis.getManifest();
}
assertNotNull(manifest);
Attributes readAttributes = manifest.getAttributes("Section");
assertEquals(2, readAttributes.size());
assertEquals("cheese", readAttributes.getValue("From-Dir"));
assertEquals("peas", readAttributes.getValue("From-Zip"));
}
private Manifest createManifestWithExampleSection(Map<String, String> attributes) {
Manifest manifest = new Manifest();
Attributes attrs = new Attributes();
for (Map.Entry<String, String> stringStringEntry : attributes.entrySet()) {
attrs.put(new Attributes.Name(stringStringEntry.getKey()), stringStringEntry.getValue());
}
manifest.getEntries().put("example", attrs);
return manifest;
}
private Manifest jarDirectoryAndReadManifest(
Manifest fromJar, Manifest fromUser, boolean mergeEntries)
throws InterruptedException, IOException {
byte[] contents = jarDirectoryAndReadManifestContents(fromJar, fromUser, mergeEntries);
return new Manifest(new ByteArrayInputStream(contents));
}
private byte[] jarDirectoryAndReadManifestContents(
Manifest fromJar, Manifest fromUser, boolean mergeEntries)
throws InterruptedException, IOException {
// Create a jar with a manifest we'd expect to see merged.
Path originalJar = folder.newFile("unexpected.jar");
JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar);
ignored.close();
// Now create the actual manifest
Path manifestFile = folder.newFile("actual_manfiest.mf");
try (OutputStream os = Files.newOutputStream(manifestFile)) {
fromUser.write(os);
}
Path tmp = folder.newFolder();
Path output = tmp.resolve("example.jar");
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(tmp),
JarParameters.builder()
.setJarPath(output)
.setEntriesToJar(ImmutableSortedSet.of(originalJar))
.setManifestFile(Optional.of(manifestFile))
.setMergeManifests(mergeEntries)
.setRemoveEntryPredicate(RemoveClassesPatternsMatcher.EMPTY)
.build());
ExecutionContext context = TestExecutionContext.newInstance();
step.execute(context);
try (JarFile jf = new JarFile(output.toFile())) {
JarEntry manifestEntry = jf.getJarEntry(JarFile.MANIFEST_NAME);
try (InputStream manifestStream = jf.getInputStream(manifestEntry)) {
return ByteStreams.toByteArray(manifestStream);
}
}
}
private Path createZip(Path zipFile, String... fileNames) throws IOException {
try (ZipArchive zip = new ZipArchive(zipFile, true)) {
for (String fileName : fileNames) {
zip.add(fileName, "");
}
}
return zipFile;
}
private void assertZipFileCountIs(int expected, Path zip) throws IOException {
Set<String> fileNames = getFileNames(zip);
assertEquals(fileNames.toString(), expected, fileNames.size());
}
private void assertZipContains(Path zip, String... files) throws IOException {
Set<String> contents = getFileNames(zip);
for (String file : files) {
assertTrue(String.format("%s -> %s", file, contents), contents.contains(file));
}
}
private void assertZipDoesNotContain(Path zip, String... files) throws IOException {
Set<String> contents = getFileNames(zip);
for (String file : files) {
assertFalse(String.format("%s -> %s", file, contents), contents.contains(file));
}
}
private Set<String> getFileNames(Path zipFile) throws IOException {
try (ZipArchive zip = new ZipArchive(zipFile, false)) {
return zip.getFileNames();
}
}
}
| {
"content_hash": "d0ce9760458a7357be348aceb7723bd7",
"timestamp": "",
"source": "github",
"line_count": 605,
"max_line_length": 100,
"avg_line_length": 39.10413223140496,
"alnum_prop": 0.6822216586355567,
"repo_name": "clonetwin26/buck",
"id": "d8d3dc18f92f367efe1266c66bd5792786e579a2",
"size": "24263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/com/facebook/buck/jvm/java/JarDirectoryStepTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "793"
},
{
"name": "Batchfile",
"bytes": "2215"
},
{
"name": "C",
"bytes": "263152"
},
{
"name": "C#",
"bytes": "237"
},
{
"name": "C++",
"bytes": "14997"
},
{
"name": "CSS",
"bytes": "54894"
},
{
"name": "D",
"bytes": "1017"
},
{
"name": "Go",
"bytes": "4646"
},
{
"name": "Groovy",
"bytes": "3362"
},
{
"name": "HTML",
"bytes": "7248"
},
{
"name": "Haskell",
"bytes": "971"
},
{
"name": "IDL",
"bytes": "385"
},
{
"name": "Java",
"bytes": "25118787"
},
{
"name": "JavaScript",
"bytes": "933531"
},
{
"name": "Kotlin",
"bytes": "19145"
},
{
"name": "Lex",
"bytes": "2867"
},
{
"name": "Makefile",
"bytes": "1816"
},
{
"name": "Matlab",
"bytes": "47"
},
{
"name": "OCaml",
"bytes": "4935"
},
{
"name": "Objective-C",
"bytes": "160741"
},
{
"name": "Objective-C++",
"bytes": "34"
},
{
"name": "PowerShell",
"bytes": "244"
},
{
"name": "Prolog",
"bytes": "858"
},
{
"name": "Python",
"bytes": "1848054"
},
{
"name": "Roff",
"bytes": "1207"
},
{
"name": "Rust",
"bytes": "5199"
},
{
"name": "Scala",
"bytes": "5046"
},
{
"name": "Shell",
"bytes": "57970"
},
{
"name": "Smalltalk",
"bytes": "3794"
},
{
"name": "Swift",
"bytes": "10663"
},
{
"name": "Thrift",
"bytes": "42010"
},
{
"name": "Yacc",
"bytes": "323"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>free-groups: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.0 / free-groups - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
free-groups
<small>
8.9.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-26 03:34:25 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-26 03:34:25 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/free-groups"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/FreeGroups"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: free group"
"category: Mathematics/Algebra"
]
authors: [
"Daniel Schepler <dschepler@gmail.com>"
]
bug-reports: "https://github.com/coq-contribs/free-groups/issues"
dev-repo: "git+https://github.com/coq-contribs/free-groups.git"
synopsis: "Free Groups"
description: """
This small contribution is a formalization of van der Waerden's proof of the construction of a free group on a set of generators, as the reduced words where a letter is a generator or its formal inverse."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/free-groups/archive/v8.9.0.tar.gz"
checksum: "md5=be61048705c8ad244619dc1c8e526bf3"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-free-groups.8.9.0 coq.8.13.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0).
The following dependencies couldn't be met:
- coq-free-groups -> coq < 8.10~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-free-groups.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "fb24260cb12768fef68bb9ca57d59b6b",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 225,
"avg_line_length": 41.50588235294118,
"alnum_prop": 0.5457766439909297,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "670b01908d1a9a0cb7802cf75c25ec1c8ce5bea9",
"size": "7081",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.13.0/free-groups/8.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
* qc.Point getTilePosition(number x, number y)
## Paramters
| Paramter | Type | Description |
| --------- | --------- | --------- |
| x | number | index in axis x |
| y | number | index in axis y |
## Description
Get tile position.
| {
"content_hash": "9dae9899fe591d538ebbeb4cd315ea07",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 46,
"avg_line_length": 23.4,
"alnum_prop": 0.5641025641025641,
"repo_name": "qiciengine/qiciengine-documentation",
"id": "6f058bbf6c48527df78f1a72637d563371091500",
"size": "292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "en/api/gameobject/tilemap_getTilePosition.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "336"
},
{
"name": "JavaScript",
"bytes": "3311"
}
],
"symlink_target": ""
} |
package miyagi389.android.apps.tr.presentation.ui;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import miyagi389.android.apps.tr.presentation.R;
import miyagi389.android.apps.tr.presentation.databinding.TemplateEditActivityBinding;
public class TemplateEditActivity extends BaseActivity implements TemplateEditFragment.Listener {
public static final String EXTRA_ID = "EXTRA_ID";
public static final int RESULT_SAVED = RESULT_FIRST_USER + 1;
private final TemplateEditActivity self = this;
private TemplateEditActivityBinding binding;
private TemplateEditFragment templateEditFragment;
@NonNull
public static Intent newIntent(
@NonNull final Context context,
final long id
) {
final Intent intent = new Intent(context, TemplateEditActivity.class);
intent.putExtra(EXTRA_ID, id);
return intent;
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bindingContentView();
initializeActivity();
}
private void bindingContentView() {
self.binding = DataBindingUtil.setContentView(self, R.layout.template_edit_activity);
self.binding.toolbar.setTitle(getTitle());
setSupportActionBar(self.binding.toolbar);
}
private void initializeActivity() {
final FragmentManager fm = getSupportFragmentManager();
self.templateEditFragment = (TemplateEditFragment) fm.findFragmentById(R.id.content_wrapper);
if (self.templateEditFragment == null) {
final long id = getIntentId();
if (id > 0) {
self.templateEditFragment = TemplateEditFragment.newInstance(id);
replaceFragment(R.id.content_wrapper, self.templateEditFragment);
}
}
}
private long getIntentId() {
final Intent intent = getIntent();
return intent == null ? 0L : intent.getLongExtra(EXTRA_ID, 0L);
}
/**
* {@link TemplateEditFragment.Listener#onSaved(TemplateEditFragment)}
*/
@Override
public void onSaved(@NonNull final TemplateEditFragment fragment) {
setResult(RESULT_SAVED);
finish();
}
}
| {
"content_hash": "f34b3f94063b86989f567e47398e67b9",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 101,
"avg_line_length": 32.45945945945946,
"alnum_prop": 0.6994171523730225,
"repo_name": "miyagi389/mtimerec-android",
"id": "88922fdf8866c9a4dc4d4f12992bd34e8467a223",
"size": "2402",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app-presentation/src/main/java/miyagi389/android/apps/tr/presentation/ui/TemplateEditActivity.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "128588"
},
{
"name": "IDL",
"bytes": "1705"
},
{
"name": "Java",
"bytes": "376295"
},
{
"name": "Prolog",
"bytes": "350"
},
{
"name": "Shell",
"bytes": "2446"
}
],
"symlink_target": ""
} |
/* Bluetooth: Mesh Generic OnOff, Generic Level, Lighting & Vendor Models
*
* Copyright (c) 2018 Vikrant More
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "console/console.h"
#include "hal/hal_gpio.h"
#include "mesh/mesh.h"
#include "app_gpio.h"
#include "storage.h"
#include "ble_mesh.h"
#include "device_composition.h"
#include "state_binding.h"
#include "transition.h"
static struct bt_mesh_health_srv health_srv = {
};
static struct bt_mesh_model_pub health_pub;
static struct bt_mesh_model_pub gen_onoff_srv_pub_root;
static struct bt_mesh_model_pub gen_onoff_cli_pub_root;
static struct bt_mesh_model_pub gen_level_srv_pub_root;
static struct bt_mesh_model_pub gen_level_cli_pub_root;
static struct bt_mesh_model_pub gen_def_trans_time_srv_pub;
static struct bt_mesh_model_pub gen_def_trans_time_cli_pub;
static struct bt_mesh_model_pub gen_power_onoff_srv_pub;
static struct bt_mesh_model_pub gen_power_onoff_cli_pub;
static struct bt_mesh_model_pub light_lightness_srv_pub;
static struct bt_mesh_model_pub light_lightness_cli_pub;
static struct bt_mesh_model_pub light_ctl_srv_pub;
static struct bt_mesh_model_pub light_ctl_cli_pub;
static struct bt_mesh_model_pub vnd_pub;
static struct bt_mesh_model_pub gen_level_srv_pub_s0;
static struct bt_mesh_model_pub gen_level_cli_pub_s0;
static struct os_mbuf *bt_mesh_pub_msg_health_pub;
static struct os_mbuf *bt_mesh_pub_msg_gen_onoff_srv_pub_root;
static struct os_mbuf *bt_mesh_pub_msg_gen_onoff_cli_pub_root;
static struct os_mbuf *bt_mesh_pub_msg_gen_level_srv_pub_root;
static struct os_mbuf *bt_mesh_pub_msg_gen_level_cli_pub_root;
static struct os_mbuf *bt_mesh_pub_msg_gen_def_trans_time_srv_pub;
static struct os_mbuf *bt_mesh_pub_msg_gen_def_trans_time_cli_pub;
static struct os_mbuf *bt_mesh_pub_msg_gen_power_onoff_srv_pub;
static struct os_mbuf *bt_mesh_pub_msg_gen_power_onoff_cli_pub;
static struct os_mbuf *bt_mesh_pub_msg_light_lightness_srv_pub;
static struct os_mbuf *bt_mesh_pub_msg_light_lightness_cli_pub;
static struct os_mbuf *bt_mesh_pub_msg_light_ctl_srv_pub;
static struct os_mbuf *bt_mesh_pub_msg_light_ctl_cli_pub;
static struct os_mbuf *bt_mesh_pub_msg_vnd_pub;
static struct os_mbuf *bt_mesh_pub_msg_gen_level_srv_pub_s0;
static struct os_mbuf *bt_mesh_pub_msg_gen_level_cli_pub_s0;
void init_pub(void)
{
bt_mesh_pub_msg_health_pub = NET_BUF_SIMPLE(1 + 3 + 0);
bt_mesh_pub_msg_gen_onoff_srv_pub_root = NET_BUF_SIMPLE(2 + 3);
bt_mesh_pub_msg_gen_onoff_cli_pub_root = NET_BUF_SIMPLE(2 + 4);
bt_mesh_pub_msg_gen_level_srv_pub_root = NET_BUF_SIMPLE(2 + 5);
bt_mesh_pub_msg_gen_level_cli_pub_root = NET_BUF_SIMPLE(2 + 7);
bt_mesh_pub_msg_gen_power_onoff_srv_pub = NET_BUF_SIMPLE(2 + 1);
bt_mesh_pub_msg_gen_power_onoff_cli_pub = NET_BUF_SIMPLE(2 + 1);
bt_mesh_pub_msg_gen_def_trans_time_srv_pub = NET_BUF_SIMPLE(2 + 1);
bt_mesh_pub_msg_gen_def_trans_time_cli_pub = NET_BUF_SIMPLE(2 + 1);
bt_mesh_pub_msg_light_lightness_srv_pub = NET_BUF_SIMPLE(2 + 5);
bt_mesh_pub_msg_light_lightness_cli_pub = NET_BUF_SIMPLE(2 + 5);
bt_mesh_pub_msg_light_ctl_srv_pub = NET_BUF_SIMPLE(2 + 9);
bt_mesh_pub_msg_light_ctl_cli_pub = NET_BUF_SIMPLE(2 + 9);
bt_mesh_pub_msg_vnd_pub = NET_BUF_SIMPLE(3 + 6);
bt_mesh_pub_msg_gen_level_srv_pub_s0 = NET_BUF_SIMPLE(2 + 5);
bt_mesh_pub_msg_gen_level_cli_pub_s0 = NET_BUF_SIMPLE(2 + 7);
health_pub.msg = bt_mesh_pub_msg_health_pub;
gen_onoff_srv_pub_root.msg = bt_mesh_pub_msg_gen_onoff_srv_pub_root;
gen_onoff_cli_pub_root.msg = bt_mesh_pub_msg_gen_onoff_cli_pub_root;
gen_level_srv_pub_root.msg = bt_mesh_pub_msg_gen_level_srv_pub_root;
gen_level_cli_pub_root.msg = bt_mesh_pub_msg_gen_level_cli_pub_root;
gen_power_onoff_srv_pub.msg = bt_mesh_pub_msg_gen_power_onoff_srv_pub;
gen_power_onoff_cli_pub.msg = bt_mesh_pub_msg_gen_power_onoff_cli_pub;
gen_def_trans_time_srv_pub.msg = bt_mesh_pub_msg_gen_def_trans_time_srv_pub;
gen_def_trans_time_cli_pub.msg = bt_mesh_pub_msg_gen_def_trans_time_cli_pub;
light_lightness_srv_pub.msg = bt_mesh_pub_msg_light_lightness_srv_pub;
light_lightness_cli_pub.msg = bt_mesh_pub_msg_light_lightness_cli_pub;
light_ctl_srv_pub.msg = bt_mesh_pub_msg_light_ctl_srv_pub;
light_ctl_cli_pub.msg = bt_mesh_pub_msg_light_ctl_cli_pub;
vnd_pub.msg = bt_mesh_pub_msg_vnd_pub;
gen_level_srv_pub_s0.msg = bt_mesh_pub_msg_gen_level_srv_pub_s0;
gen_level_cli_pub_s0.msg = bt_mesh_pub_msg_gen_level_cli_pub_s0;
}
/* Definitions of models user data (Start) */
struct generic_onoff_state gen_onoff_srv_root_user_data = {
.transition = &lightness_transition,
};
struct generic_level_state gen_level_srv_root_user_data = {
.transition = &lightness_transition,
};
struct gen_def_trans_time_state gen_def_trans_time_srv_user_data;
struct generic_onpowerup_state gen_power_onoff_srv_user_data;
struct light_lightness_state light_lightness_srv_user_data = {
.transition = &lightness_transition,
};
struct light_ctl_state light_ctl_srv_user_data = {
.transition = &lightness_transition,
};
struct vendor_state vnd_user_data;
struct generic_level_state gen_level_srv_s0_user_data = {
.transition = &temp_transition,
};
/* Definitions of models user data (End) */
static struct bt_mesh_elem elements[];
/* message handlers (Start) */
/* Generic OnOff Server message handlers */
static int gen_onoff_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 3 + 4);
struct generic_onoff_state *state = model->user_data;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_GEN_ONOFF_STATUS);
net_buf_simple_add_u8(msg, state->onoff);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_u8(msg, state->target_onoff);
net_buf_simple_add_u8(msg, state->transition->rt);
}
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send GEN_ONOFF_SRV Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
int gen_onoff_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct generic_onoff_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_GEN_ONOFF_STATUS);
net_buf_simple_add_u8(msg, state->onoff);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_u8(msg, state->target_onoff);
net_buf_simple_add_u8(msg, state->transition->rt);
}
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static int gen_onoff_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, onoff, tt, delay;
int64_t now;
int err;
struct generic_onoff_state *state = model->user_data;
onoff = net_buf_simple_pull_u8(buf);
tid = net_buf_simple_pull_u8(buf);
if (onoff > STATE_ON) {
return 0;
}
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return 0;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->target_onoff = onoff;
if (state->target_onoff != state->onoff) {
onoff_tt_values(state, tt, delay);
} else {
return gen_onoff_publish(model);
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->onoff = state->target_onoff;
}
state->transition->just_started = true;
err = gen_onoff_publish(model);
onoff_handler(state);
if (err) {
return err;
}
return 0;
}
static int gen_onoff_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, onoff, tt, delay;
int64_t now;
int rc;
struct generic_onoff_state *state = model->user_data;
onoff = net_buf_simple_pull_u8(buf);
tid = net_buf_simple_pull_u8(buf);
if (onoff > STATE_ON) {
return 0;
}
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
rc = gen_onoff_get(model, ctx, buf);
return rc;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->target_onoff = onoff;
if (state->target_onoff != state->onoff) {
onoff_tt_values(state, tt, delay);
} else {
gen_onoff_get(model, ctx, buf);
rc = gen_onoff_publish(model);
return rc;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->onoff = state->target_onoff;
}
state->transition->just_started = true;
gen_onoff_get(model, ctx, buf);
rc = gen_onoff_publish(model);
onoff_handler(state);
return rc;
}
/* Generic OnOff Client message handlers */
static int gen_onoff_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from GEN_ONOFF_SRV\n");
printk("Present OnOff = %02x\n", net_buf_simple_pull_u8(buf));
if (buf->om_len == 2) {
printk("Target OnOff = %02x\n", net_buf_simple_pull_u8(buf));
printk("Remaining Time = %02x\n", net_buf_simple_pull_u8(buf));
}
return 0;
}
/* Generic Level Server message handlers */
static int gen_level_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 5 + 4);
struct generic_level_state *state = model->user_data;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_GEN_LEVEL_STATUS);
net_buf_simple_add_le16(msg, state->level);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_level);
net_buf_simple_add_u8(msg, state->transition->rt);
}
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send GEN_LEVEL_SRV Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
int gen_level_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct generic_level_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_GEN_LEVEL_STATUS);
net_buf_simple_add_le16(msg, state->level);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_level);
net_buf_simple_add_u8(msg, state->transition->rt);
}
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static int gen_level_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int16_t level;
int64_t now;
struct generic_level_state *state = model->user_data;
level = (int16_t) net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return 0;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->target_level = level;
if (state->target_level != state->level) {
level_tt_values(state, tt, delay);
} else {
gen_level_publish(model);
return 0;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->level = state->target_level;
}
state->transition->just_started = true;
gen_level_publish(model);
if (bt_mesh_model_elem(model)->addr == elements[0].addr) {
/* Root element */
transition_type = LEVEL_TT;
level_lightness_handler(state);
} else if (bt_mesh_model_elem(model)->addr == elements[1].addr) {
/* Secondary element */
transition_type = LEVEL_TEMP_TT;
level_temp_handler(state);
}
return 0;
}
static int gen_level_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int16_t level;
int64_t now;
struct generic_level_state *state = model->user_data;
level = (int16_t) net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
gen_level_get(model, ctx, buf);
return 0;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->target_level = level;
if (state->target_level != state->level) {
level_tt_values(state, tt, delay);
} else {
gen_level_get(model, ctx, buf);
gen_level_publish(model);
return 0;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->level = state->target_level;
}
state->transition->just_started = true;
gen_level_get(model, ctx, buf);
gen_level_publish(model);
if (bt_mesh_model_elem(model)->addr == elements[0].addr) {
/* Root element */
transition_type = LEVEL_TT;
level_lightness_handler(state);
} else if (bt_mesh_model_elem(model)->addr == elements[1].addr) {
/* Secondary element */
transition_type = LEVEL_TEMP_TT;
level_temp_handler(state);
}
return 0;
}
static int gen_delta_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int32_t tmp32, delta;
int64_t now;
struct generic_level_state *state = model->user_data;
delta = (int32_t) net_buf_simple_pull_le32(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
if (state->last_delta == delta) {
return 0;
}
tmp32 = state->last_level + delta;
} else {
state->last_level = state->level;
tmp32 = state->level + delta;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->last_delta = delta;
if (tmp32 < INT16_MIN) {
tmp32 = INT16_MIN;
} else if (tmp32 > INT16_MAX) {
tmp32 = INT16_MAX;
}
state->target_level = tmp32;
if (state->target_level != state->level) {
level_tt_values(state, tt, delay);
} else {
return gen_level_publish(model);
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->level = state->target_level;
}
state->transition->just_started = true;
gen_level_publish(model);
if (bt_mesh_model_elem(model)->addr == elements[0].addr) {
/* Root element */
transition_type = LEVEL_TT_DELTA;
level_lightness_handler(state);
} else if (bt_mesh_model_elem(model)->addr ==
elements[1].addr) {
/* Secondary element */
transition_type = LEVEL_TEMP_TT_DELTA;
level_temp_handler(state);
}
return 0;
}
static int gen_delta_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int32_t tmp32, delta;
int64_t now;
struct generic_level_state *state = model->user_data;
delta = (int32_t) net_buf_simple_pull_le32(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
if (state->last_delta == delta) {
gen_level_get(model, ctx, buf);
return 0;
}
tmp32 = state->last_level + delta;
} else {
state->last_level = state->level;
tmp32 = state->level + delta;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->last_delta = delta;
if (tmp32 < INT16_MIN) {
tmp32 = INT16_MIN;
} else if (tmp32 > INT16_MAX) {
tmp32 = INT16_MAX;
}
state->target_level = tmp32;
if (state->target_level != state->level) {
level_tt_values(state, tt, delay);
} else {
gen_level_get(model, ctx, buf);
gen_level_publish(model);
return 0;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->level = state->target_level;
}
state->transition->just_started = true;
gen_level_get(model, ctx, buf);
gen_level_publish(model);
if (bt_mesh_model_elem(model)->addr == elements[0].addr) {
/* Root element */
transition_type = LEVEL_TT_DELTA;
level_lightness_handler(state);
} else if (bt_mesh_model_elem(model)->addr == elements[1].addr) {
/* Secondary element */
transition_type = LEVEL_TEMP_TT_DELTA;
level_temp_handler(state);
}
return 0;
}
static int gen_level_move_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 5 + 4);
struct generic_level_state *state = model->user_data;
int rc;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_GEN_LEVEL_STATUS);
net_buf_simple_add_le16(msg, state->level);
if (state->transition->counter) {
if (state->last_delta < 0) {
net_buf_simple_add_le16(msg, INT16_MIN);
} else { /* 0 should not be possible */
net_buf_simple_add_le16(msg, INT16_MAX);
}
net_buf_simple_add_u8(msg, UNKNOWN_VALUE);
}
rc = bt_mesh_model_send(model, ctx, msg, NULL, NULL);
if (rc) {
printk("Unable to send GEN_LEVEL_SRV Status response\n");
}
os_mbuf_free_chain(msg);
return rc;
}
static int gen_level_move_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct generic_level_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_GEN_LEVEL_STATUS);
net_buf_simple_add_le16(msg, state->level);
if (state->transition->counter) {
if (state->last_delta < 0) {
net_buf_simple_add_le16(msg, INT16_MIN);
} else { /* 0 should not be possible */
net_buf_simple_add_le16(msg, INT16_MAX);
}
net_buf_simple_add_u8(msg, UNKNOWN_VALUE);
}
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static int gen_move_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int16_t delta;
int32_t tmp32;
int64_t now;
struct generic_level_state *state = model->user_data;
int rc;
delta = (int16_t) net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return 0;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->last_delta = delta;
tmp32 = state->level + delta;
if (tmp32 < INT16_MIN) {
tmp32 = INT16_MIN;
} else if (tmp32 > INT16_MAX) {
tmp32 = INT16_MAX;
}
state->target_level = tmp32;
if (state->target_level != state->level) {
level_tt_values(state, tt, delay);
} else {
rc = gen_level_move_publish(model);
return rc;
}
if (state->transition->counter == 0) {
return 0;
}
state->transition->just_started = true;
rc = gen_level_move_publish(model);
if (bt_mesh_model_elem(model)->addr == elements[0].addr) {
/* Root element */
transition_type = LEVEL_TT_MOVE;
level_lightness_handler(state);
} else if (bt_mesh_model_elem(model)->addr == elements[1].addr) {
/* Secondary element */
transition_type = LEVEL_TEMP_TT_MOVE;
level_temp_handler(state);
}
return rc;
}
static int gen_move_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int16_t delta;
int32_t tmp32;
int64_t now;
struct generic_level_state *state = model->user_data;
int rc;
delta = (int16_t) net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
rc = gen_level_move_get(model, ctx, buf);
return rc;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->last_delta = delta;
tmp32 = state->level + delta;
if (tmp32 < INT16_MIN) {
tmp32 = INT16_MIN;
} else if (tmp32 > INT16_MAX) {
tmp32 = INT16_MAX;
}
state->target_level = tmp32;
if (state->target_level != state->level) {
level_tt_values(state, tt, delay);
} else {
gen_level_move_get(model, ctx, buf);
rc = gen_level_move_publish(model);
return rc;
}
if (state->transition->counter == 0) {
return 0;
}
state->transition->just_started = true;
gen_level_move_get(model, ctx, buf);
rc = gen_level_move_publish(model);
if (bt_mesh_model_elem(model)->addr == elements[0].addr) {
/* Root element */
transition_type = LEVEL_TT_MOVE;
level_lightness_handler(state);
} else if (bt_mesh_model_elem(model)->addr == elements[1].addr) {
/* Secondary element */
transition_type = LEVEL_TEMP_TT_MOVE;
level_temp_handler(state);
}
return rc;
}
/* Generic Level Client message handlers */
static int gen_level_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from GEN_LEVEL_SRV\n");
printk("Present Level = %04x\n", net_buf_simple_pull_le16(buf));
if (buf->om_len == 3) {
printk("Target Level = %04x\n", net_buf_simple_pull_le16(buf));
printk("Remaining Time = %02x\n", net_buf_simple_pull_u8(buf));
}
return 0;
}
/* Generic Default Transition Time Server message handlers */
static int gen_def_trans_time_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 1 + 4);
struct gen_def_trans_time_state *state = model->user_data;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_GEN_DEF_TRANS_TIME_STATUS);
net_buf_simple_add_u8(msg, state->tt);
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send GEN_DEF_TT_SRV Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
static int gen_def_trans_time_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct gen_def_trans_time_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_GEN_DEF_TRANS_TIME_STATUS);
net_buf_simple_add_u8(msg, state->tt);
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static bool gen_def_trans_time_setunack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tt;
struct gen_def_trans_time_state *state = model->user_data;
tt = net_buf_simple_pull_u8(buf);
/* Here, Model specification is silent about tid implementation */
if ((tt & 0x3F) == 0x3F) {
return false;
}
if (state->tt != tt) {
state->tt = tt;
default_tt = tt;
save_on_flash(GEN_DEF_TRANS_TIME_STATE);
}
return true;
}
static int gen_def_trans_time_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
if (gen_def_trans_time_setunack(model, ctx, buf) == true) {
return gen_def_trans_time_publish(model);
}
return 0;
}
static int gen_def_trans_time_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
if (gen_def_trans_time_setunack(model, ctx, buf) == true) {
gen_def_trans_time_get(model, ctx, buf);
return gen_def_trans_time_publish(model);
}
return 0;
}
/* Generic Default Transition Time Client message handlers */
static int gen_def_trans_time_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from GEN_DEF_TT_SRV\n");
printk("Transition Time = %02x\n", net_buf_simple_pull_u8(buf));
return 0;
}
/* Generic Power OnOff Server message handlers */
static int gen_onpowerup_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 1 + 4);
struct generic_onpowerup_state *state = model->user_data;
int rc;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_GEN_ONPOWERUP_STATUS);
net_buf_simple_add_u8(msg, state->onpowerup);
rc = bt_mesh_model_send(model, ctx, msg, NULL, NULL);
if (rc) {
printk("Unable to send GEN_POWER_ONOFF_SRV Status response\n");
}
os_mbuf_free_chain(msg);
return rc;
}
/* Generic Power OnOff Client message handlers */
static int gen_onpowerup_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from GEN_POWER_ONOFF_SRV\n");
printk("OnPowerUp = %02x\n", net_buf_simple_pull_u8(buf));
return 0;
}
/* Generic Power OnOff Setup Server message handlers */
static int gen_onpowerup_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct generic_onpowerup_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_GEN_ONPOWERUP_STATUS);
net_buf_simple_add_u8(msg, state->onpowerup);
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static bool gen_onpowerup_setunack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t onpowerup;
struct generic_onpowerup_state *state = model->user_data;
onpowerup = net_buf_simple_pull_u8(buf);
/* Here, Model specification is silent about tid implementation */
if (onpowerup > STATE_RESTORE) {
return false;
}
if (state->onpowerup != onpowerup) {
state->onpowerup = onpowerup;
save_on_flash(GEN_ONPOWERUP_STATE);
}
return true;
}
static int gen_onpowerup_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
if (gen_onpowerup_setunack(model, ctx, buf) == true) {
return gen_onpowerup_publish(model);
}
return 0;
}
static int gen_onpowerup_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
if (gen_onpowerup_setunack(model, ctx, buf) == true) {
gen_onpowerup_get(model, ctx, buf);
return gen_onpowerup_publish(model);
}
return 0;
}
/* Vendor Model message handlers*/
static int vnd_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(3 + 6 + 4);
struct vendor_state *state = model->user_data;
int err;
/* This is dummy response for demo purpose */
state->response = 0xA578FEB3;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_3(0x04, CID_RUNTIME));
net_buf_simple_add_le16(msg, state->current);
net_buf_simple_add_le32(msg, state->response);
err = bt_mesh_model_send(model, ctx, msg, NULL, NULL);
if (err) {
printk("Unable to send VENDOR Status response\n");
}
os_mbuf_free_chain(msg);
return err;
}
static int vnd_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid;
int current;
int64_t now;
struct vendor_state *state = model->user_data;
current = net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return 0;
}
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->current = current;
printk("Vendor model message = %04x\n", state->current);
if (state->current == STATE_ON) {
/* LED2 On */
hal_gpio_write(led_device[1], 0);
} else {
/* LED2 Off */
hal_gpio_write(led_device[1], 1);
}
return 0;
}
static int vnd_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
int rc;
rc = vnd_set_unack(model, ctx, buf);
if (rc) {
return rc;
}
rc = vnd_get(model, ctx, buf);
if (rc) {
return rc;
}
return 0;
}
static int vnd_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from Vendor\n");
printk("cmd = %04x\n", net_buf_simple_pull_le16(buf));
printk("response = %08lx\n", net_buf_simple_pull_le32(buf));
return 0;
}
/* Light Lightness Server message handlers */
static int light_lightness_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 5 + 4);
struct light_lightness_state *state = model->user_data;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_LIGHTNESS_STATUS);
net_buf_simple_add_le16(msg, state->actual);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_actual);
net_buf_simple_add_u8(msg, state->transition->rt);
}
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send LightLightnessAct Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
int light_lightness_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct light_lightness_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_LIGHTNESS_STATUS);
net_buf_simple_add_le16(msg, state->actual);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_actual);
net_buf_simple_add_u8(msg, state->transition->rt);
}
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static int light_lightness_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
uint16_t actual;
int64_t now;
struct light_lightness_state *state = model->user_data;
actual = net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return 0;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
if (actual > 0 && actual < state->light_range_min) {
actual = state->light_range_min;
} else if (actual > state->light_range_max) {
actual = state->light_range_max;
}
state->target_actual = actual;
if (state->target_actual != state->actual) {
light_lightness_actual_tt_values(state, tt, delay);
} else {
light_lightness_publish(model);
return 0;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->actual = state->target_actual;
}
state->transition->just_started = true;
light_lightness_publish(model);
light_lightness_actual_handler(state);
return 0;
}
static int light_lightness_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
uint16_t actual;
int64_t now;
struct light_lightness_state *state = model->user_data;
int rc;
actual = net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return light_lightness_get(model, ctx, buf);
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
if (actual > 0 && actual < state->light_range_min) {
actual = state->light_range_min;
} else if (actual > state->light_range_max) {
actual = state->light_range_max;
}
state->target_actual = actual;
if (state->target_actual != state->actual) {
light_lightness_actual_tt_values(state, tt, delay);
} else {
rc = light_lightness_get(model, ctx, buf);
light_lightness_publish(model);
return rc;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->actual = state->target_actual;
}
state->transition->just_started = true;
light_lightness_get(model, ctx, buf);
light_lightness_publish(model);
light_lightness_actual_handler(state);
return 0;
}
static int light_lightness_linear_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 5 + 4);
struct light_lightness_state *state = model->user_data;
bt_mesh_model_msg_init(msg,
BT_MESH_MODEL_LIGHT_LIGHTNESS_LINEAR_STATUS);
net_buf_simple_add_le16(msg, state->linear);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_linear);
net_buf_simple_add_u8(msg, state->transition->rt);
}
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send LightLightnessLin Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
int light_lightness_linear_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct light_lightness_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg,
BT_MESH_MODEL_LIGHT_LIGHTNESS_LINEAR_STATUS);
net_buf_simple_add_le16(msg, state->linear);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_linear);
net_buf_simple_add_u8(msg, state->transition->rt);
}
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static int light_lightness_linear_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
uint16_t linear;
int64_t now;
struct light_lightness_state *state = model->user_data;
linear = net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return 0;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->target_linear = linear;
if (state->target_linear != state->linear) {
light_lightness_linear_tt_values(state, tt, delay);
} else {
light_lightness_linear_publish(model);
return 0;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->linear = state->target_linear;
}
state->transition->just_started = true;
light_lightness_linear_publish(model);
light_lightness_linear_handler(state);
return 0;
}
static int light_lightness_linear_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
uint16_t linear;
int64_t now;
struct light_lightness_state *state = model->user_data;
int rc;
linear = net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return light_lightness_linear_get(model, ctx, buf);
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->target_linear = linear;
if (state->target_linear != state->linear) {
light_lightness_linear_tt_values(state, tt, delay);
} else {
rc = light_lightness_linear_get(model, ctx, buf);
light_lightness_linear_publish(model);
return rc;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->linear = state->target_linear;
}
state->transition->just_started = true;
light_lightness_linear_get(model, ctx, buf);
light_lightness_linear_publish(model);
light_lightness_linear_handler(state);
return 0;
}
static int light_lightness_last_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 2 + 4);
struct light_lightness_state *state = model->user_data;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_LIGHTNESS_LAST_STATUS);
net_buf_simple_add_le16(msg, state->last);
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send LightLightnessLast Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
static int light_lightness_default_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 2 + 4);
struct light_lightness_state *state = model->user_data;
bt_mesh_model_msg_init(msg,
BT_MESH_MODEL_LIGHT_LIGHTNESS_DEFAULT_STATUS);
net_buf_simple_add_le16(msg, state->def);
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send LightLightnessDef Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
static int light_lightness_range_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 5 + 4);
struct light_lightness_state *state = model->user_data;
state->status_code = RANGE_SUCCESSFULLY_UPDATED;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_LIGHTNESS_RANGE_STATUS);
net_buf_simple_add_u8(msg, state->status_code);
net_buf_simple_add_le16(msg, state->light_range_min);
net_buf_simple_add_le16(msg, state->light_range_max);
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send LightLightnessRange Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
/* Light Lightness Setup Server message handlers */
static int light_lightness_default_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct light_lightness_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg,
BT_MESH_MODEL_LIGHT_LIGHTNESS_DEFAULT_STATUS);
net_buf_simple_add_le16(msg, state->def);
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static int light_lightness_default_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint16_t lightness;
struct light_lightness_state *state = model->user_data;
lightness = net_buf_simple_pull_le16(buf);
/* Here, Model specification is silent about tid implementation */
if (state->def != lightness) {
state->def = lightness;
light_ctl_srv_user_data.lightness_def = state->def;
save_on_flash(LIGHTNESS_TEMP_DEF_STATE);
}
return light_lightness_default_publish(model);
}
static int light_lightness_default_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
int rc;
rc = light_lightness_default_set_unack(model, ctx, buf);
if (rc) {
return rc;
}
rc = light_lightness_default_get(model, ctx, buf);
if (rc) {
return rc;
}
rc = light_lightness_default_publish(model);
if (rc) {
return rc;
}
return 0;
}
static int light_lightness_range_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct light_lightness_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_LIGHTNESS_RANGE_STATUS);
net_buf_simple_add_u8(msg, state->status_code);
net_buf_simple_add_le16(msg, state->light_range_min);
net_buf_simple_add_le16(msg, state->light_range_max);
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static bool light_lightness_range_setunack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint16_t min, max;
struct light_lightness_state *state = model->user_data;
min = net_buf_simple_pull_le16(buf);
max = net_buf_simple_pull_le16(buf);
/* Here, Model specification is silent about tid implementation */
if (min == 0 || max == 0) {
return false;
} else {
if (min <= max) {
state->status_code = RANGE_SUCCESSFULLY_UPDATED;
if (state->light_range_min != min ||
state->light_range_max != max) {
state->light_range_min = min;
state->light_range_max = max;
save_on_flash(LIGHTNESS_RANGE);
}
} else {
/* The provided value for Range Max cannot be set */
state->status_code = CANNOT_SET_RANGE_MAX;
return false;
}
}
return true;
}
static int light_lightness_range_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
if (light_lightness_range_setunack(model, ctx, buf) == true) {
return light_lightness_range_publish(model);
}
return 0;
}
static int light_lightness_range_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
int rc;
if (light_lightness_range_setunack(model, ctx, buf) == true) {
rc = light_lightness_range_get(model, ctx, buf);
if (rc) {
return rc;
}
rc = light_lightness_range_publish(model);
if (rc) {
return rc;
}
}
return 0;
}
/* Light Lightness Client message handlers */
static int light_lightness_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from LIGHT_LIGHTNESS_SRV (Actual)\n");
printk("Present Lightness = %04x\n", net_buf_simple_pull_le16(buf));
if (buf->om_len == 3) {
printk("Target Lightness = %04x\n",
net_buf_simple_pull_le16(buf));
printk("Remaining Time = %02x\n", net_buf_simple_pull_u8(buf));
}
return 0;
}
static int light_lightness_linear_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from LIGHT_LIGHTNESS_SRV (Linear)\n");
printk("Present Lightness = %04x\n", net_buf_simple_pull_le16(buf));
if (buf->om_len == 3) {
printk("Target Lightness = %04x\n",
net_buf_simple_pull_le16(buf));
printk("Remaining Time = %02x\n", net_buf_simple_pull_u8(buf));
}
return 0;
}
static int light_lightness_last_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from LIGHT_LIGHTNESS_SRV (Last)\n");
printk("Lightness = %04x\n", net_buf_simple_pull_le16(buf));
return 0;
}
static int light_lightness_default_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from LIGHT_LIGHTNESS_SRV (Default)\n");
printk("Lightness = %04x\n", net_buf_simple_pull_le16(buf));
return 0;
}
static int light_lightness_range_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from LIGHT_LIGHTNESS_SRV (Lightness Range)\n");
printk("Status Code = %02x\n", net_buf_simple_pull_u8(buf));
printk("Range Min = %04x\n", net_buf_simple_pull_le16(buf));
printk("Range Max = %04x\n", net_buf_simple_pull_le16(buf));
return 0;
}
/* Light CTL Server message handlers */
static int light_ctl_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 9 + 4);
struct light_ctl_state *state = model->user_data;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_CTL_STATUS);
net_buf_simple_add_le16(msg, state->lightness);
net_buf_simple_add_le16(msg, state->temp);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_lightness);
net_buf_simple_add_le16(msg, state->target_temp);
net_buf_simple_add_u8(msg, state->transition->rt);
}
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send LightCTL Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
int light_ctl_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct light_ctl_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_CTL_STATUS);
/* Here, as per Model specification, status should be
* made up of lightness & temperature values only
*/
net_buf_simple_add_le16(msg, state->lightness);
net_buf_simple_add_le16(msg, state->temp);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_lightness);
net_buf_simple_add_le16(msg, state->target_temp);
net_buf_simple_add_u8(msg, state->transition->rt);
}
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static int light_ctl_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int16_t delta_uv;
uint16_t lightness, temp;
int64_t now;
struct light_ctl_state *state = model->user_data;
lightness = net_buf_simple_pull_le16(buf);
temp = net_buf_simple_pull_le16(buf);
delta_uv = (int16_t) net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
if (temp < TEMP_MIN || temp > TEMP_MAX) {
return 0;
}
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return 0;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->target_lightness = lightness;
if (temp < state->temp_range_min) {
temp = state->temp_range_min;
} else if (temp > state->temp_range_max) {
temp = state->temp_range_max;
}
state->target_temp = temp;
state->target_delta_uv = delta_uv;
if (state->target_lightness != state->lightness ||
state->target_temp != state->temp ||
state->target_delta_uv != state->delta_uv) {
light_ctl_tt_values(state, tt, delay);
} else {
light_ctl_publish(model);
return 0;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->lightness = state->target_lightness;
state->temp = state->target_temp;
state->delta_uv = state->target_delta_uv;
}
state->transition->just_started = true;
light_ctl_publish(model);
light_ctl_handler(state);
return 0;
}
static int light_ctl_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int16_t delta_uv;
uint16_t lightness, temp;
int64_t now;
struct light_ctl_state *state = model->user_data;
lightness = net_buf_simple_pull_le16(buf);
temp = net_buf_simple_pull_le16(buf);
delta_uv = (int16_t) net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
if (temp < TEMP_MIN || temp > TEMP_MAX) {
return 0;
}
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
light_ctl_get(model, ctx, buf);
return 0;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
state->target_lightness = lightness;
if (temp < state->temp_range_min) {
temp = state->temp_range_min;
} else if (temp > state->temp_range_max) {
temp = state->temp_range_max;
}
state->target_temp = temp;
state->target_delta_uv = delta_uv;
if (state->target_lightness != state->lightness ||
state->target_temp != state->temp ||
state->target_delta_uv != state->delta_uv) {
light_ctl_tt_values(state, tt, delay);
} else {
light_ctl_get(model, ctx, buf);
light_ctl_publish(model);
return 0;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->lightness = state->target_lightness;
state->temp = state->target_temp;
state->delta_uv = state->target_delta_uv;
}
state->transition->just_started = true;
light_ctl_get(model, ctx, buf);
light_ctl_publish(model);
light_ctl_handler(state);
return 0;
}
static int light_ctl_temp_range_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 5 + 4);
struct light_ctl_state *state = model->user_data;
int rc;
state->status_code = RANGE_SUCCESSFULLY_UPDATED;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_CTL_TEMP_RANGE_STATUS);
net_buf_simple_add_u8(msg, state->status_code);
net_buf_simple_add_le16(msg, state->temp_range_min);
net_buf_simple_add_le16(msg, state->temp_range_max);
rc = bt_mesh_model_send(model, ctx, msg, NULL, NULL);
if (rc) {
printk("Unable to send LightCTL Temp Range Status response\n");
}
os_mbuf_free_chain(msg);
return rc;
}
static int light_ctl_default_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 6 + 4);
struct light_ctl_state *state = model->user_data;
int rc;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_CTL_DEFAULT_STATUS);
net_buf_simple_add_le16(msg, state->lightness_def);
net_buf_simple_add_le16(msg, state->temp_def);
net_buf_simple_add_le16(msg, state->delta_uv_def);
rc = bt_mesh_model_send(model, ctx, msg, NULL, NULL);
if (rc) {
printk("Unable to send LightCTL Default Status response\n");
}
os_mbuf_free_chain(msg);
return rc;
}
/* Light CTL Setup Server message handlers */
static int light_ctl_default_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct light_ctl_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_CTL_DEFAULT_STATUS);
net_buf_simple_add_le16(msg, state->lightness_def);
net_buf_simple_add_le16(msg, state->temp_def);
net_buf_simple_add_le16(msg, state->delta_uv_def);
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static bool light_ctl_default_setunack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint16_t lightness, temp;
int16_t delta_uv;
struct light_ctl_state *state = model->user_data;
lightness = net_buf_simple_pull_le16(buf);
temp = net_buf_simple_pull_le16(buf);
delta_uv = (int16_t) net_buf_simple_pull_le16(buf);
/* Here, Model specification is silent about tid implementation */
if (temp < TEMP_MIN || temp > TEMP_MAX) {
return false;
}
if (temp < state->temp_range_min) {
temp = state->temp_range_min;
} else if (temp > state->temp_range_max) {
temp = state->temp_range_max;
}
if (state->lightness_def != lightness || state->temp_def != temp ||
state->delta_uv_def != delta_uv) {
state->lightness_def = lightness;
state->temp_def = temp;
state->delta_uv_def = delta_uv;
save_on_flash(LIGHTNESS_TEMP_DEF_STATE);
}
return true;
}
static int light_ctl_default_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
if (light_ctl_default_setunack(model, ctx, buf) == true) {
return light_ctl_default_publish(model);
}
return 0;
}
static int light_ctl_default_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
if (light_ctl_default_setunack(model, ctx, buf) == true) {
light_ctl_default_get(model, ctx, buf);
return light_ctl_default_publish(model);
}
return 0;
}
static int light_ctl_temp_range_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct light_ctl_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_CTL_TEMP_RANGE_STATUS);
net_buf_simple_add_u8(msg, state->status_code);
net_buf_simple_add_le16(msg, state->temp_range_min);
net_buf_simple_add_le16(msg, state->temp_range_max);
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static bool light_ctl_temp_range_setunack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint16_t min, max;
struct light_ctl_state *state = model->user_data;
min = net_buf_simple_pull_le16(buf);
max = net_buf_simple_pull_le16(buf);
/* Here, Model specification is silent about tid implementation */
/* This is as per 6.1.3.1 in Mesh Model Specification */
if (min < TEMP_MIN || min > TEMP_MAX ||
max < TEMP_MIN || max > TEMP_MAX) {
return false;
}
if (min <= max) {
state->status_code = RANGE_SUCCESSFULLY_UPDATED;
if (state->temp_range_min != min ||
state->temp_range_max != max) {
state->temp_range_min = min;
state->temp_range_max = max;
save_on_flash(TEMPERATURE_RANGE);
}
} else {
/* The provided value for Range Max cannot be set */
state->status_code = CANNOT_SET_RANGE_MAX;
return false;
}
return true;
}
static int light_ctl_temp_range_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
if (light_ctl_temp_range_setunack(model, ctx, buf) == true) {
return light_ctl_temp_range_publish(model);
}
return 0;
}
static int light_ctl_temp_range_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
if (light_ctl_temp_range_setunack(model, ctx, buf) == true) {
light_ctl_temp_range_get(model, ctx, buf);
return light_ctl_temp_range_publish(model);
}
return 0;
}
/* Light CTL Client message handlers */
static int light_ctl_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from LIGHT_CTL_SRV\n");
printk("Present CTL Lightness = %04x\n", net_buf_simple_pull_le16(buf));
printk("Present CTL Temperature = %04x\n",
net_buf_simple_pull_le16(buf));
if (buf->om_len == 5) {
printk("Target CTL Lightness = %04x\n",
net_buf_simple_pull_le16(buf));
printk("Target CTL Temperature = %04x\n",
net_buf_simple_pull_le16(buf));
printk("Remaining Time = %02x\n", net_buf_simple_pull_u8(buf));
}
return 0;
}
static int light_ctl_temp_range_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from LIGHT_CTL_SRV (Temperature Range)\n");
printk("Status Code = %02x\n", net_buf_simple_pull_u8(buf));
printk("Range Min = %04x\n", net_buf_simple_pull_le16(buf));
printk("Range Max = %04x\n", net_buf_simple_pull_le16(buf));
return 0;
}
static int light_ctl_temp_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from LIGHT_CTL_TEMP_SRV\n");
printk("Present CTL Temperature = %04x\n",
net_buf_simple_pull_le16(buf));
printk("Present CTL Delta UV = %04x\n",
net_buf_simple_pull_le16(buf));
if (buf->om_len == 5) {
printk("Target CTL Temperature = %04x\n",
net_buf_simple_pull_le16(buf));
printk("Target CTL Delta UV = %04x\n",
net_buf_simple_pull_le16(buf));
printk("Remaining Time = %02x\n", net_buf_simple_pull_u8(buf));
}
return 0;
}
static int light_ctl_default_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
printk("Acknownledgement from LIGHT_CTL_SRV (Default)\n");
printk("Lightness = %04x\n", net_buf_simple_pull_le16(buf));
printk("Temperature = %04x\n", net_buf_simple_pull_le16(buf));
printk("Delta UV = %04x\n", net_buf_simple_pull_le16(buf));
return 0;
}
/* Light CTL Temp. Server message handlers */
static int light_ctl_temp_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
struct os_mbuf *msg = NET_BUF_SIMPLE(2 + 9 + 4);
struct light_ctl_state *state = model->user_data;
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_CTL_TEMP_STATUS);
net_buf_simple_add_le16(msg, state->temp);
net_buf_simple_add_le16(msg, state->delta_uv);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_temp);
net_buf_simple_add_le16(msg, state->target_delta_uv);
net_buf_simple_add_u8(msg, state->transition->rt);
}
if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) {
printk("Unable to send LightCTL Temp. Status response\n");
}
os_mbuf_free_chain(msg);
return 0;
}
int light_ctl_temp_publish(struct bt_mesh_model *model)
{
int err;
struct os_mbuf *msg = model->pub->msg;
struct light_ctl_state *state = model->user_data;
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return 0;
}
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_LIGHT_CTL_TEMP_STATUS);
net_buf_simple_add_le16(msg, state->temp);
net_buf_simple_add_le16(msg, state->delta_uv);
if (state->transition->counter) {
calculate_rt(state->transition);
net_buf_simple_add_le16(msg, state->target_temp);
net_buf_simple_add_le16(msg, state->target_delta_uv);
net_buf_simple_add_u8(msg, state->transition->rt);
}
err = bt_mesh_model_publish(model);
if (err) {
printk("bt_mesh_model_publish err %d\n", err);
}
return err;
}
static int light_ctl_temp_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int16_t delta_uv;
uint16_t temp;
int64_t now;
struct light_ctl_state *state = model->user_data;
temp = net_buf_simple_pull_le16(buf);
delta_uv = (int16_t) net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
if (temp < TEMP_MIN || temp > TEMP_MAX) {
return 0;
}
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return 0;
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
if (temp < state->temp_range_min) {
temp = state->temp_range_min;
} else if (temp > state->temp_range_max) {
temp = state->temp_range_max;
}
state->target_temp = temp;
state->target_delta_uv = delta_uv;
if (state->target_temp != state->temp ||
state->target_delta_uv != state->delta_uv) {
light_ctl_temp_tt_values(state, tt, delay);
} else {
light_ctl_temp_publish(model);
return 0;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->temp = state->target_temp;
state->delta_uv = state->target_delta_uv;
}
state->transition->just_started = true;
light_ctl_temp_publish(model);
light_ctl_temp_handler(state);
return 0;
}
static int light_ctl_temp_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct os_mbuf *buf)
{
uint8_t tid, tt, delay;
int16_t delta_uv;
uint16_t temp;
int64_t now;
struct light_ctl_state *state = model->user_data;
temp = net_buf_simple_pull_le16(buf);
delta_uv = (int16_t) net_buf_simple_pull_le16(buf);
tid = net_buf_simple_pull_u8(buf);
if (temp < TEMP_MIN || temp > TEMP_MAX) {
return 0;
}
now = k_uptime_get();
if (state->last_tid == tid &&
state->last_src_addr == ctx->addr &&
state->last_dst_addr == ctx->recv_dst &&
(now - state->last_msg_timestamp <= K_SECONDS(6))) {
return light_ctl_temp_get(model, ctx, buf);
}
switch (buf->om_len) {
case 0x00: /* No optional fields are available */
tt = default_tt;
delay = 0;
break;
case 0x02: /* Optional fields are available */
tt = net_buf_simple_pull_u8(buf);
if ((tt & 0x3F) == 0x3F) {
return 0;
}
delay = net_buf_simple_pull_u8(buf);
break;
default:
return 0;
}
*ptr_counter = 0;
os_callout_stop(ptr_timer);
state->last_tid = tid;
state->last_src_addr = ctx->addr;
state->last_dst_addr = ctx->recv_dst;
state->last_msg_timestamp = now;
if (temp < state->temp_range_min) {
temp = state->temp_range_min;
} else if (temp > state->temp_range_max) {
temp = state->temp_range_max;
}
state->target_temp = temp;
state->target_delta_uv = delta_uv;
if (state->target_temp != state->temp ||
state->target_delta_uv != state->delta_uv) {
light_ctl_temp_tt_values(state, tt, delay);
} else {
light_ctl_temp_get(model, ctx, buf);
light_ctl_temp_publish(model);
return 0;
}
/* For Instantaneous Transition */
if (state->transition->counter == 0) {
state->temp = state->target_temp;
state->delta_uv = state->target_delta_uv;
}
state->transition->just_started = true;
light_ctl_temp_get(model, ctx, buf);
light_ctl_temp_publish(model);
light_ctl_temp_handler(state);
return 0;
}
/* message handlers (End) */
/* Mapping of message handlers for Generic OnOff Server (0x1000) */
static const struct bt_mesh_model_op gen_onoff_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x01), 0, gen_onoff_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x02), 2, gen_onoff_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x03), 2, gen_onoff_set_unack },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Generic OnOff Client (0x1001) */
static const struct bt_mesh_model_op gen_onoff_cli_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x04), 1, gen_onoff_status },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Generic Levl Server (0x1002) */
static const struct bt_mesh_model_op gen_level_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x05), 0, gen_level_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x06), 3, gen_level_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x07), 3, gen_level_set_unack },
{ BT_MESH_MODEL_OP_2(0x82, 0x09), 5, gen_delta_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x0A), 5, gen_delta_set_unack },
{ BT_MESH_MODEL_OP_2(0x82, 0x0B), 3, gen_move_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x0C), 3, gen_move_set_unack },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Generic Level Client (0x1003) */
static const struct bt_mesh_model_op gen_level_cli_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x08), 2, gen_level_status },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Generic Default TT Server (0x1004) */
static const struct bt_mesh_model_op gen_def_trans_time_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x0D), 0, gen_def_trans_time_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x0E), 1, gen_def_trans_time_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x0F), 1, gen_def_trans_time_set_unack },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Generic Default TT Client (0x1005) */
static const struct bt_mesh_model_op gen_def_trans_time_cli_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x10), 1, gen_def_trans_time_status },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Generic Power OnOff Server (0x1006) */
static const struct bt_mesh_model_op gen_power_onoff_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x11), 0, gen_onpowerup_get },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Generic Power OnOff Setup Server (0x1007) */
static const struct bt_mesh_model_op gen_power_onoff_setup_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x13), 1, gen_onpowerup_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x14), 1, gen_onpowerup_set_unack },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Generic Power OnOff Client (0x1008) */
static const struct bt_mesh_model_op gen_power_onoff_cli_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x12), 1, gen_onpowerup_status },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Light Lightness Server (0x1300) */
static const struct bt_mesh_model_op light_lightness_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x4B), 0, light_lightness_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x4C), 3, light_lightness_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x4D), 3, light_lightness_set_unack },
{ BT_MESH_MODEL_OP_2(0x82, 0x4F), 0, light_lightness_linear_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x50), 3, light_lightness_linear_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x51), 3,
light_lightness_linear_set_unack },
{ BT_MESH_MODEL_OP_2(0x82, 0x53), 0, light_lightness_last_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x55), 0, light_lightness_default_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x57), 0, light_lightness_range_get },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Light Lightness Setup Server (0x1301) */
static const struct bt_mesh_model_op light_lightness_setup_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x59), 2, light_lightness_default_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x5A), 2,
light_lightness_default_set_unack },
{ BT_MESH_MODEL_OP_2(0x82, 0x5B), 4, light_lightness_range_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x5C), 4, light_lightness_range_set_unack },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Light Lightness Client (0x1302) */
static const struct bt_mesh_model_op light_lightness_cli_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x4E), 2, light_lightness_status },
{ BT_MESH_MODEL_OP_2(0x82, 0x52), 2, light_lightness_linear_status },
{ BT_MESH_MODEL_OP_2(0x82, 0x54), 2, light_lightness_last_status },
{ BT_MESH_MODEL_OP_2(0x82, 0x56), 2, light_lightness_default_status },
{ BT_MESH_MODEL_OP_2(0x82, 0x58), 5, light_lightness_range_status },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Light CTL Server (0x1303) */
static const struct bt_mesh_model_op light_ctl_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x5D), 0, light_ctl_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x5E), 7, light_ctl_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x5F), 7, light_ctl_set_unack },
{ BT_MESH_MODEL_OP_2(0x82, 0x62), 0, light_ctl_temp_range_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x67), 0, light_ctl_default_get },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Light CTL Setup Server (0x1304) */
static const struct bt_mesh_model_op light_ctl_setup_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x69), 6, light_ctl_default_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x6A), 6, light_ctl_default_set_unack },
{ BT_MESH_MODEL_OP_2(0x82, 0x6B), 4, light_ctl_temp_range_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x6C), 4, light_ctl_temp_range_set_unack },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Light CTL Client (0x1305) */
static const struct bt_mesh_model_op light_ctl_cli_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x60), 4, light_ctl_status },
{ BT_MESH_MODEL_OP_2(0x82, 0x63), 5, light_ctl_temp_range_status },
{ BT_MESH_MODEL_OP_2(0x82, 0x66), 4, light_ctl_temp_status },
{ BT_MESH_MODEL_OP_2(0x82, 0x68), 6, light_ctl_default_status },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Light CTL Temp. Server (0x1306) */
static const struct bt_mesh_model_op light_ctl_temp_srv_op[] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x61), 0, light_ctl_temp_get },
{ BT_MESH_MODEL_OP_2(0x82, 0x64), 5, light_ctl_temp_set },
{ BT_MESH_MODEL_OP_2(0x82, 0x65), 5, light_ctl_temp_set_unack },
BT_MESH_MODEL_OP_END,
};
/* Mapping of message handlers for Vendor (0x4321) */
static const struct bt_mesh_model_op vnd_ops[] = {
{ BT_MESH_MODEL_OP_3(0x01, CID_RUNTIME), 0, vnd_get },
{ BT_MESH_MODEL_OP_3(0x02, CID_RUNTIME), 3, vnd_set },
{ BT_MESH_MODEL_OP_3(0x03, CID_RUNTIME), 3, vnd_set_unack },
{ BT_MESH_MODEL_OP_3(0x04, CID_RUNTIME), 6, vnd_status },
BT_MESH_MODEL_OP_END,
};
struct bt_mesh_model root_models[] = {
BT_MESH_MODEL_CFG_SRV,
BT_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_ONOFF_SRV,
gen_onoff_srv_op, &gen_onoff_srv_pub_root,
&gen_onoff_srv_root_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_ONOFF_CLI,
gen_onoff_cli_op, &gen_onoff_cli_pub_root,
NULL),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_LEVEL_SRV,
gen_level_srv_op, &gen_level_srv_pub_root,
&gen_level_srv_root_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_LEVEL_CLI,
gen_level_cli_op, &gen_level_cli_pub_root,
NULL),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_SRV,
gen_def_trans_time_srv_op,
&gen_def_trans_time_srv_pub,
&gen_def_trans_time_srv_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_CLI,
gen_def_trans_time_cli_op,
&gen_def_trans_time_cli_pub,
NULL),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_POWER_ONOFF_SRV,
gen_power_onoff_srv_op, &gen_power_onoff_srv_pub,
&gen_power_onoff_srv_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_POWER_ONOFF_SETUP_SRV,
gen_power_onoff_setup_srv_op,
&gen_power_onoff_srv_pub,
&gen_power_onoff_srv_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_POWER_ONOFF_CLI,
gen_power_onoff_cli_op, &gen_power_onoff_cli_pub,
NULL),
BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV,
light_lightness_srv_op, &light_lightness_srv_pub,
&light_lightness_srv_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_SETUP_SRV,
light_lightness_setup_srv_op,
&light_lightness_srv_pub,
&light_lightness_srv_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI,
light_lightness_cli_op, &light_lightness_cli_pub,
NULL),
BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_CTL_SRV,
light_ctl_srv_op, &light_ctl_srv_pub,
&light_ctl_srv_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_CTL_SETUP_SRV,
light_ctl_setup_srv_op, &light_ctl_srv_pub,
&light_ctl_srv_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_CTL_CLI,
light_ctl_cli_op, &light_ctl_cli_pub,
NULL),
};
struct bt_mesh_model vnd_models[] = {
BT_MESH_MODEL_VND(CID_RUNTIME, 0x4321, vnd_ops,
&vnd_pub, &vnd_user_data),
};
struct bt_mesh_model s0_models[] = {
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_LEVEL_SRV,
gen_level_srv_op, &gen_level_srv_pub_s0,
&gen_level_srv_s0_user_data),
BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_LEVEL_CLI,
gen_level_cli_op, &gen_level_cli_pub_s0,
NULL),
BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_CTL_TEMP_SRV,
light_ctl_temp_srv_op, &light_ctl_srv_pub,
&light_ctl_srv_user_data),
};
static struct bt_mesh_elem elements[] = {
BT_MESH_ELEM(0, root_models, vnd_models),
BT_MESH_ELEM(0, s0_models, BT_MESH_MODEL_NONE),
};
const struct bt_mesh_comp comp = {
.cid = CID_RUNTIME,
.elem = elements,
.elem_count = ARRAY_SIZE(elements),
};
| {
"content_hash": "05296e58edba85e157355d34d7ccf3f6",
"timestamp": "",
"source": "github",
"line_count": 2846,
"max_line_length": 79,
"avg_line_length": 27.089248067463107,
"alnum_prop": 0.6590225173809277,
"repo_name": "apache/mynewt-nimble",
"id": "40ede501261196051ede4c04b77856a75304013a",
"size": "77902",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "apps/blemesh_models_example_2/src/device_composition.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1870"
},
{
"name": "C",
"bytes": "6993392"
},
{
"name": "C++",
"bytes": "8323"
},
{
"name": "Makefile",
"bytes": "11104"
},
{
"name": "Python",
"bytes": "105770"
},
{
"name": "Ruby",
"bytes": "25717"
},
{
"name": "Shell",
"bytes": "10984"
}
],
"symlink_target": ""
} |
<?php
namespace thinker_g\IshtarGate;
use Yii;
use yii\web\AssetBundle;
use yii\web\View;
use yii\helpers\Html;
/**
* Asset bundle of jquery plugin "Inews ticker".
* @author Thinker_g
* @see https://github.com/progpars/inewsticker
*
*/
class INewsTickerAsset extends AssetBundle
{
/**
* @var string overriding parament property.
* @see \yii\web\AssetBundle::$sourcePath
*/
public $sourcePath = '@thinker_g/IshtarGate/assets';
/**
* @var array overriding parent property.
* @see \yii\web\AssetBundle::$js
*/
public $js = [
'inewsticker.js'
];
/**
* @var array overriding parent property.
* @see \yii\web\AssetBundle::$css
*/
public $css = [
'inewsticker.css'
];
/**
* @var array overriding parent property.
* @see \yii\web\AssetBundle::$css
*/
public $depends = [
'yii\web\JqueryAsset',
'yii\bootstrap\BootstrapAsset',
'yii\bootstrap\BootstrapPluginAsset'
];
/**
* @var string css classes added to newsbar container.
*/
public $containerCssClass = 'inewsticker-container container';
/**
* @var string newsbar id of the HTML element.
*/
public $tickerId = 'ishtar-inewsticker';
/**
* @var string css classes added to news ticker element.
*/
public $tickerCssClass = 'inewsticker text-center';
/**
* @var array options passed to the jquery plugin "inewsticker"
* Any option supported by inewsticker can be set in this array.
* @see https://github.com/progpars/inewsticker
*/
public $pluginOptions = [
'effect' => 'slide',
'speed' => 3000,
'dir' => 'ltr',
'color' => '#fff',
'font_size' => 13,
'font_family' => 'arial',
'delay_after' => 5000
];
/* (non-PHPdoc)
* @see \yii\web\AssetBundle::init()
*/
public function init()
{
parent::init();
Yii::$app->getView()->registerJs($this->getJs(), View::POS_READY);
}
/**
* Js codes will be registered to view component.
* @param \yii\web\View $view
* @see \yii\web\AssetBundle::register()
*/
protected function getJs()
{
$options = json_encode($this->pluginOptions);
$html = $this->getHtml();
return "
ishtarNewsticker = {};
ishtarNewsticker.holder = $('<div>').css({
position: 'absolute',
width: '100%',
top: '0px',
left: '0px'
});
ishtarNewsticker.container = $('<div>', {
class: '{$this->containerCssClass} alert fade in'
}).hide();
ishtarNewsticker.tickerNode = $('<ul>', {
id: '{$this->tickerId}',
class: '{$this->tickerCssClass}'
}).html('$html');
$('<button>',{
'class': 'close',
'data-dismiss': 'alert'
}).html('<span>×</span>').appendTo(ishtarNewsticker.container);
ishtarNewsticker.container.on('close.bs.alert', function(){
console.info('close ishtar news ticker');//
});
ishtarNewsticker.container.append(ishtarNewsticker.tickerNode);
ishtarNewsticker.holder.append(ishtarNewsticker.container);
$('body').prepend(ishtarNewsticker.holder);
ishtarNewsticker.tickerNode.inewsticker({$options});
setTimeout('ishtarNewsticker.container.fadeIn();',500);
";
}
/**
* @return string html codes needed by the plugin.
*/
protected function getHtml()
{
$html = '';
foreach (Yii::$app->getView()->params['news'] as $ts => $news) {
$html .= '<li>' . Html::encode(str_replace('{ts}', $ts, $news)) . '</li>';
}
return $html;
}
}
?> | {
"content_hash": "6e1569d3cc46cada5a9085f127b964ab",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 86,
"avg_line_length": 26.126666666666665,
"alnum_prop": 0.5394233222760908,
"repo_name": "thinker-g/yii2-ishtar-gate",
"id": "1da6b883cf271626e71b66878375d49cdacd6a20",
"size": "4078",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "INewsTickerAsset.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "480"
},
{
"name": "PHP",
"bytes": "30128"
}
],
"symlink_target": ""
} |
* Basic OAuth stubbing works
* Forked from `emmerge:google-fake`
| {
"content_hash": "529b637b653217bbe197fbd95cd5008e",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 35,
"avg_line_length": 32.5,
"alnum_prop": 0.7692307692307693,
"repo_name": "ryepdx/meteor-linkedin-fake",
"id": "99b5e1c05159b5258e664c016909178ef67b13d4",
"size": "73",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "533"
},
{
"name": "JavaScript",
"bytes": "5037"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b1a29df88e53e3d1dcaf284ddb78c547",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 18,
"avg_line_length": 8.384615384615385,
"alnum_prop": 0.6788990825688074,
"repo_name": "mdoering/backbone",
"id": "bd2ec09759065eee54cb11295a9ad40077be7a24",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Puccinia/Puccinia asiatica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import Component from "vue-class-component";
import AuthComponent from "../../components/authComponent/authComponent";
import RegisterButton from "../../controls/registerButton/registerButton.vue";
import AuthButton from "../../controls/authButton/authButton.vue";
import AuthListTile from "../../controls/authListTile/authListTile.vue";
import RegisterListTile from "../../controls/registerListTile/registerListTile.vue";
@Component({
components: {
RegisterButton,
AuthButton,
AuthListTile,
RegisterListTile
}
})
export default class NavBar extends AuthComponent {
public get IsAdministrator(): boolean {
if (!this.IsAuthenticated) {
return false;
}
if (this.$store.getters["isAdministrator"]) {
return true;
}
return false;
}
} | {
"content_hash": "b0bb7eb6b21f0d24f4cc56503d79054b",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 84,
"avg_line_length": 29.214285714285715,
"alnum_prop": 0.6931540342298288,
"repo_name": "Divergic/techmentorweb",
"id": "ac701f3fd30d9332123fee1daf3ca9e25e23102e",
"size": "818",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/controls/navbar/navbar.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "934"
},
{
"name": "HTML",
"bytes": "60518"
},
{
"name": "JavaScript",
"bytes": "30628"
},
{
"name": "TypeScript",
"bytes": "353810"
},
{
"name": "Vue",
"bytes": "4129"
}
],
"symlink_target": ""
} |
title: Sample Sequencer
name: sample-sequencer
type: page
date: "Mon, 17 Nov 2008 20:31:18 +0000"
author: niels
category: uncategorized
---
Its easy to sequence Samples with Reloaded - and to record the sequence to a new sample.This is how the Sequencer looks like:[caption id="attachment_200" align="aligncenter" width="194" caption="Sequencer"]
[](http://www.veejayhq.net/wp-content/uploads/2008/11/sequencer.png)[/caption]In the 10x10 board below you have 100 slots, in each you can place exactly one sample.First, play the sample you want to sequence and left-mouse click one of the slots. Doso for the other samples you want to sequence. The grid is played from top left tobottom right and empty slots are simply skipped. The play pattern in the grid below is:1,2,3,1,2,3,4,5,6,7,8,9You can click the 'Play and repeat sample grid' which will do the obvious, play the pattern. | {
"content_hash": "afabfe94bac6461e2e0a1e118cd0e7c8",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 631,
"avg_line_length": 97.9,
"alnum_prop": 0.7732379979570991,
"repo_name": "mvhenten/veejayhq",
"id": "445c658793ca06e6ab5dc99f91e2a4348d42e367",
"size": "983",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/page/sample-sequencer.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2300"
},
{
"name": "JavaScript",
"bytes": "8455"
}
],
"symlink_target": ""
} |
//
// Sprite.m
// Final-Project-Refactored
//
// Sprite class for touch management adapted from. Subclass of CCSprite
// http://lethain.com/entry/2008/oct/20/touch-detection-in-cocos2d-iphone/
//
#import "Sprite.h"
@implementation Sprite
static NSMutableArray * sprites = nil;
/*
*sprites returns the synchronized array of sprites. a synchronized variable
*is connected among all objects. sprites is a class function
*@return array of sprites tracked
*/
+(NSMutableArray *)sprites {
// synchronize the sprites array accross all class instances
@synchronized(sprites) {
// returns the array of sprites
if (sprites == nil)
sprites = [[NSMutableArray alloc] init];
return sprites;
}
return nil;
}
/*
*track puts the member sprite into the sprites array
*@return aSprite the sprite to track
*/
+(void)track: (Sprite *)aSprite {
@synchronized(sprites) {
[[Sprite sprites] addObject:aSprite];
}
}
/*
*untrack removes the sprite from the sprites array
*@param aSprite is the sprite to remove from the array
*/
+(void)untrack: (Sprite *)aSprite {
@synchronized(sprites) {
[[Sprite sprites] removeObject:aSprite];
}
}
/*
*init initializes the sprite and tracks it
*@return the sprite object
*/
-(id)init {
self = [super init];
if (self) [Sprite track:self];
return self;
}
/*
*dealloc deallocates the memory and untracks the sprite
*used for release calls
*/
-(void)dealloc {
[Sprite untrack:self];
[super dealloc];
}
/*
*rect generates the bounding box for the sprite to use for collision
*@return returns the bounding box of the sprite
*/
-(CGRect)rect{
// generate the rectangle
return CGRectMake(
self.position.x - (self.contentSize.width/2),
self.position.y - (self.contentSize.height/2),
self.contentSize.width,
self.contentSize.height);
}
@end
| {
"content_hash": "f0d5111bac61ba43f5ee46b847ba72db",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 77,
"avg_line_length": 22.903614457831324,
"alnum_prop": 0.6796422935297212,
"repo_name": "dhenke/CollegeNostalgia-Shooter",
"id": "bf06709c02c8817f1b44c374d2e684af07e97f9f",
"size": "1901",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Classes/Sprite.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "146580"
},
{
"name": "C++",
"bytes": "561"
},
{
"name": "Objective-C",
"bytes": "1439963"
}
],
"symlink_target": ""
} |
local api, cmd, g, opt, o = vim.api, vim.cmd, vim.g, vim.opt, vim.o
---------------------------------------------------------------------------
-- Global Config
---------------------------------------------------------------------------
-- Disable python2 and perl support
g.loaded_python_provider = 0
g.loaded_perl_provider = 0
-- Use pyenv for python3 support
g.python3_host_prog = '~/.pyenv/versions/neovim/bin/python'
---------------------------------------------------------------------------
-- Plugins
---------------------------------------------------------------------------
require('packer').startup(function()
-- Self Update
use('wbthomason/packer.nvim')
-- NeoVim helpers
use('neovim/nvim-lspconfig')
use('tami5/lspsaga.nvim')
use({'nvim-treesitter/nvim-treesitter', run = ':TSUpdate'})
-- Auto Completion
use({'hrsh7th/nvim-cmp', requires = {
{'hrsh7th/cmp-buffer'},
{'hrsh7th/cmp-nvim-lsp'},
{'hrsh7th/cmp-nvim-lua'},
{'hrsh7th/cmp-path'},
{'L3MON4D3/LuaSnip'},
{'saadparwaiz1/cmp_luasnip'}
}})
-- File Finder
use({'nvim-telescope/telescope.nvim', requires = {
{'nvim-lua/popup.nvim'},
{'nvim-lua/plenary.nvim'},
{'kyazdani42/nvim-web-devicons'},
}})
-- UI plugins
use('navarasu/onedark.nvim')
use({'hoob3rt/lualine.nvim', requires = {'kyazdani42/nvim-web-devicons', opt = true}})
use({'kyazdani42/nvim-tree.lua', requires = {'kyazdani42/nvim-web-devicons', opt = true}})
use({'lewis6991/gitsigns.nvim', requires = {'nvim-lua/plenary.nvim'}})
use('phaazon/hop.nvim')
use('ray-x/lsp_signature.nvim')
-- Editor plugins
use('editorconfig/editorconfig-vim')
use('windwp/nvim-autopairs')
use('sbdchd/neoformat')
-- Extra languages
use('abhishekmukherg/xonsh-vim')
end)
---------------------------------------------------------------------------
-- Editor Config
---------------------------------------------------------------------------
-- Keys
g.mapleader = ',' -- Lead with ,
opt.mouse = 'a' -- Activate mouse support
opt.clipboard = 'unnamed' -- Use system clipboard
-- Visuals
opt.termguicolors = true -- Color support
opt.number = true -- Show always line numbers
opt.relativenumber = true -- But relatives to the current one
opt.scrolloff = 4 -- Keep 4 lines off the edges of the screen
opt.colorcolumn = '100'
-- Indenting
opt.wrap = false -- No wrap lines
opt.tabstop = 4 -- A tab is 4 spaces
opt.softtabstop = 4 -- Also softabs
opt.expandtab = true -- Expand the tabs
opt.backspace = 'indent,eol,start' -- Allow backspacing over everything
opt.autoindent = true -- Always indent
opt.smartindent = true -- Trying to be smart
opt.copyindent = true -- Copy the previous indentation
opt.shiftwidth = 4 -- Four spaces on indenting
opt.shiftround = true -- Use multiples of swidth
opt.textwidth = 120 -- Width of 120 chars per line
-- Search
opt.ignorecase = true -- Ignore case when searching
opt.smartcase = true -- Only if it's all lowercase
opt.hlsearch = true -- Highlight the terms
opt.incsearch = true -- Show as you type
-- Notifications
opt.visualbell = true -- Please don't beep
opt.errorbells = false -- Really, don't
-- History
opt.history = 1000 -- A big history
opt.undolevels = 1000 -- Same for undos
-- Autocomplete Menus
opt.wildmode = 'list:longest,full' -- AutoComplete menus more useful
opt.wildchar = 9 -- Iterate with the tab through them
o.completeopt = 'menu,menuone,noselect' -- Completion popups
-- Menus
opt.showmode = true -- Show status
opt.showcmd = true -- Show typing commands
opt.ruler = true -- Show position info
opt.laststatus = 2 -- Show the status line always
opt.ch = 2 -- Command line height
opt.backspace = '2' -- Backspacing over everything in insert mode
opt.whichwrap:append('<,>,h,l,[,]') -- Move between lines with the arrows
---------------------------------------------------------------------------
-- Plugins Config
---------------------------------------------------------------------------
-- Auto Pairs
require('nvim-autopairs').setup()
-- Luasnip
local luasnip = require('luasnip')
-- Completion
local cmp = require('cmp')
local cmp_autopairs = require('nvim-autopairs.completion.cmp')
cmp.setup({
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end
},
sources = {
{ name = 'nvim_lsp' },
{ name = 'buffer' },
{ name = 'luasnip' },
{ name = 'path' },
{ name = 'nvim_lua' },
},
mapping = {
['<CR>'] = cmp.mapping.confirm({ select = true, behavior = cmp.ConfirmBehavior.Replace }),
['<Tab>'] = function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
else
fallback()
end
end,
}
})
-- Git Signs
require('gitsigns').setup()
-- LuaLine
require('lualine').setup({
options = {
icons_enabled = true,
theme = 'auto',
},
sections = {
lualine_b = {
'branch',
},
lualine_x = {
{ 'diagnostics', sources = {"nvim_diagnostic"}, symbols = {error = ' ', warn = ' ', info = ' ', hint = ' '} },
'filetype',
},
},
})
-- LSP
local nlsp = require('lspconfig')
local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
local on_attach = function(_, bufnr)
vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
end
local servers = {
'eslint', 'gopls', 'jsonls', 'pyright', 'rust_analyzer', 'stylelint_lsp',
'tsserver', 'yamlls',
}
for _, lsp in ipairs(servers) do
nlsp[lsp].setup {
on_attach = on_attach,
capabilities = capabilities,
}
end
-- LSP - Formatting and auto-save
api.nvim_set_keymap("n", "<Leader>ff", ":lua vim.lsp.buf.formatting()<CR>", { noremap = true, silent = true })
vim.cmd [[autocmd BufWritePre *.go lua vim.lsp.buf.formatting_sync()]]
-- LSP Saga
require('lspsaga').init_lsp_saga({
error_sign = '',
warn_sign = '',
hint_sign = '',
infor_sign = '',
border_style = 'round',
finder_action_keys = {
open = '<CR>', vsplit = '<C-v>', split = '<C-h>', quit = '<ESC>',
scroll_down = '<C-f>', scroll_up = '<C-b>'
},
code_action_keys = {
quit = '<ESC>', exec = '<CR>'
},
rename_action_keys = {
quit = '<ESC>', exec = '<CR>'
},
})
api.nvim_set_keymap('n', '<Leader>gr', ':Lspsaga lsp_finder<CR>', { noremap = true, silent = true })
api.nvim_set_keymap('n', '<Leader>gs', ':Lspsaga signature_help<CR>', { noremap = true, silent = true })
api.nvim_set_keymap('n', '<Leader>gd', ':Lspsaga hover_doc<CR>', { noremap = true, silent = true })
api.nvim_set_keymap('n', '<Leader>ga', ':Lspsaga code_action<CR>', { noremap = true, silent = true })
api.nvim_set_keymap('n', '<Leader>ge', ':Lspsaga diagnostic_jump_next<CR>', { noremap = true, silent = true })
-- LSP Signature
require('lsp_signature').setup()
-- OneDark
require('onedark').load()
-- Telescope
local actions = require('telescope.actions')
api.nvim_set_keymap('n', '<C-p>', ':Telescope find_files<CR>', { noremap = true, silent = true })
api.nvim_set_keymap('n', '<C-g>', ':Telescope live_grep<CR>', { noremap = true, silent = true })
require('telescope').setup({
defaults = {
mappings = {
i = {
["<C-h>"] = actions.file_split
},
},
}
})
-- Tree Browser
local tree_cb = require('nvim-tree.config').nvim_tree_callback
api.nvim_set_keymap('n', '<Leader>tr', ':NvimTreeToggle<CR>', { noremap = true, silent = true })
require('nvim-tree').setup({
git = {
ignore = true,
},
filters = {
dotfiles = false,
custom = {'.git', 'node_modules'}
},
renderer = {
group_empty = true,
special_files = {},
icons = {
show = {
folder = true,
file = true,
folder_arrow = true,
git = true
},
},
},
view = {
mappings = {
list = {
{ key = "t", cb = tree_cb("create") },
{ key = "<C-h>", cb = tree_cb("split") },
},
},
},
})
-- TreeSitter config
require('nvim-treesitter.configs').setup({
ensure_installed = 'all',
highlight = {enable = true},
incremental_selection = {enable = true},
indent = {enable = true},
})
-- Hop
require('hop').setup()
vim.api.nvim_set_keymap('n', '<Leader><Leader>w', ":HopWord<CR>", { noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '<Leader><Leader>c', ":HopChar1<CR>", { noremap = true, silent = true})
---------------------------------------------------------------------------
-- Shorcuts
---------------------------------------------------------------------------
-- ,ws -> Delete all whitespaces
api.nvim_set_keymap('n', '<Leader>ws', ':%s/ \\+$//gc<CR>', { noremap = true })
-- ,se -> Spellcheck in English
api.nvim_set_keymap('n', '<Leader>se', ':setlocal spell spelllang=en<CR>', { noremap = true })
-- ,ss -> Spellcheck in Spanish
api.nvim_set_keymap('n', '<Leader>ss', ':setlocal spell spelllang=es<CR>', { noremap = true })
| {
"content_hash": "1aef260493572e63c932fe28cf68fd01",
"timestamp": "",
"source": "github",
"line_count": 309,
"max_line_length": 126,
"avg_line_length": 32.45307443365696,
"alnum_prop": 0.5110690067810132,
"repo_name": "igalarzab/dotfiles",
"id": "3c888a65904b163fc9e28a02895f458ef702f577",
"size": "10208",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "vim/nvim.configsymlink/init.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "10208"
},
{
"name": "Python",
"bytes": "3354"
},
{
"name": "Ruby",
"bytes": "12490"
},
{
"name": "Shell",
"bytes": "6126"
},
{
"name": "Xonsh",
"bytes": "2780"
}
],
"symlink_target": ""
} |
package com.hotels.plunger;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.hotels.plunger.Bucket;
import com.hotels.plunger.PlungerFlow;
import cascading.flow.FlowDef;
import cascading.pipe.Pipe;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import cascading.tuple.TupleEntry;
import cascading.tuple.TupleEntryCollector;
@RunWith(MockitoJUnitRunner.class)
public class BucketTest {
private static final Fields FIELDS = new Fields("A", "B");
private static final Tuple TUPLE_1 = new Tuple(1, "x");
private static final Tuple TUPLE_2 = new Tuple(2, "y");
@Mock
private PlungerFlow flow;
@Mock
private FlowDef flowDef;
@Mock
private Pipe pipe;
@Before
public void setup() {
when(flow.isComplete()).thenReturn(false);
when(flow.getFlowDef()).thenReturn(flowDef);
}
@Test
public void addsToFlowDef() throws IOException {
Bucket sink = new Bucket(FIELDS, pipe, flow);
verify(flowDef).addTailSink(pipe, sink);
}
@Test(expected = IllegalStateException.class)
public void failsIfAlreadyComplete() throws IOException {
when(flow.isComplete()).thenReturn(true);
new Bucket(FIELDS, pipe, flow);
}
@Test
public void asTupleEntryList() throws IOException {
Bucket sink = new Bucket(FIELDS, pipe, flow);
TupleEntryCollector collector = sink.openForWrite(null, null);
collector.add(TUPLE_1);
collector.add(TUPLE_2);
List<TupleEntry> tupleEntryList = sink.result().asTupleEntryList();
assertThat(tupleEntryList.size(), is(2));
assertThat(tupleEntryList.get(0).getFields(), is(FIELDS));
assertThat(tupleEntryList.get(0).getTuple(), is(TUPLE_1));
assertThat(tupleEntryList.get(1).getFields(), is(FIELDS));
assertThat(tupleEntryList.get(1).getTuple(), is(TUPLE_2));
}
@Test
public void asTupleList() throws IOException {
Bucket sink = new Bucket(FIELDS, pipe, flow);
TupleEntryCollector collector = sink.openForWrite(null, null);
collector.add(TUPLE_1);
collector.add(TUPLE_2);
List<Tuple> tupleList = sink.result().asTupleList();
assertThat(tupleList.size(), is(2));
assertThat(tupleList.get(0), is(TUPLE_1));
assertThat(tupleList.get(1), is(TUPLE_2));
}
@Test(expected = UnsupportedOperationException.class)
public void asTupleEntryListReturnsImmutable() throws IOException {
Bucket sink = new Bucket(FIELDS, pipe, flow);
sink.result().asTupleEntryList().add(new TupleEntry());
}
@Test(expected = UnsupportedOperationException.class)
public void asTupleListReturnsImmutable() throws IOException {
Bucket sink = new Bucket(FIELDS, pipe, flow);
sink.result().asTupleList().add(new Tuple());
}
@Test
public void getIdentifier() {
Bucket sink = new Bucket(FIELDS, pipe, flow);
assertThat(sink.getIdentifier().startsWith(Bucket.class.getSimpleName()), is(true));
}
@Test
public void createResource() throws IOException {
Bucket sink = new Bucket(FIELDS, pipe, flow);
assertThat(sink.resourceExists(new Properties()), is(false));
assertThat(sink.createResource(new Properties()), is(true));
assertThat(sink.resourceExists(new Properties()), is(true));
}
@Test
public void deleteResource() throws IOException {
Bucket sink = new Bucket(FIELDS, pipe, flow);
assertThat(sink.deleteResource(new Properties()), is(true));
}
@Test
public void modified() throws IOException, InterruptedException {
Bucket sink = new Bucket(FIELDS, pipe, flow);
long modifiedTime = sink.getModifiedTime(new Properties());
Thread.sleep(10);
long checkTime = System.currentTimeMillis();
assertThat(modifiedTime < checkTime, is(true));
Thread.sleep(10);
sink.modified();
Thread.sleep(10);
modifiedTime = sink.getModifiedTime(new Properties());
assertThat(modifiedTime > checkTime, is(true));
assertThat(modifiedTime < System.currentTimeMillis(), is(true));
}
}
| {
"content_hash": "ad286de27e91129b7389d5c5973a2f95",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 88,
"avg_line_length": 31.96268656716418,
"alnum_prop": 0.7235582535605883,
"repo_name": "patduin/plunger",
"id": "303408b68622b2a25933fb6a8cbc8dab9cb1e003",
"size": "4879",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/com/hotels/plunger/BucketTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "176812"
}
],
"symlink_target": ""
} |
package com.github.hburgmeier.jerseyoauth2.rs.impl.base;
import javax.ws.rs.core.Response;
public class OAuth2FilterException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
private Response errorResponse;
public OAuth2FilterException() {
super();
}
public OAuth2FilterException(Response errorResponse) {
super();
this.setErrorResponse(errorResponse);
}
public Response getErrorResponse() {
return errorResponse;
}
public final void setErrorResponse(Response errorResponse) {
this.errorResponse = errorResponse;
}
}
| {
"content_hash": "25277060d7e308b99fa0170a631cef09",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 61,
"avg_line_length": 19.806451612903224,
"alnum_prop": 0.7166123778501629,
"repo_name": "hburgmeier/jerseyoauth2",
"id": "e1ce042fe6c25eb53e5ad62dd7ce37f94c70a270",
"size": "614",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jersey-oauth2-rs-impl-base/src/main/java/com/github/hburgmeier/jerseyoauth2/rs/impl/base/OAuth2FilterException.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "306145"
}
],
"symlink_target": ""
} |
package org.apache.geode.codeAnalysis;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.geode.codeAnalysis.decode.CompiledClass;
import org.apache.geode.codeAnalysis.decode.CompiledField;
/**
* A class used to store the names of dataserializable classes and the sizes of their
* toData/fromData methods.
*
*
*/
public class ClassAndVariableDetails implements Comparable {
public String className;
public boolean hasSerialVersionUID;
public String serialVersionUID;
public Map<String, String> variables = new HashMap<>();
public ClassAndVariableDetails(CompiledClass dclass) {
className = dclass.fullyQualifiedName();
}
public ClassAndVariableDetails(String storedValues) throws IOException {
String[] fields = storedValues.split(",");
try {
int fieldIndex = 2;
className = fields[0];
hasSerialVersionUID = Boolean.parseBoolean(fields[1]);
if (hasSerialVersionUID) {
serialVersionUID = fields[2];
fieldIndex++;
}
for (int i = fieldIndex; i < fields.length; i++) {
String[] nameAndType = fields[i].split(":");
variables.put(nameAndType[0], nameAndType[1]);
}
} catch (Exception e) {
throw new IOException("Error parsing " + storedValues, e);
}
}
/*
* returns a string that can be parsed by ClassAndVariableDetails(String)
*/
public String valuesAsString() {
StringBuilder sb = new StringBuilder(80);
sb.append(className);
for (Map.Entry<String, String> entry : variables.entrySet()) {
sb.append(',').append(entry.getKey()).append(':').append(entry.getValue());
}
return sb.toString();
}
/*
* convert a ClassAndMethods into a string that can then be used to instantiate a
* ClassAndVariableDetails
*/
public static String convertForStoring(ClassAndVariables cam) {
StringBuilder sb = new StringBuilder(150);
sb.append(cam.dclass.fullyQualifiedName());
sb.append(',').append(cam.hasSerialVersionUID);
if (cam.hasSerialVersionUID) {
sb.append(',').append(cam.serialVersionUID);
}
List<CompiledField> fields = new ArrayList<>(cam.variables.values());
Collections.sort(fields);
for (CompiledField field : fields) {
sb.append(',').append(field.name()).append(':').append(field.descriptor());
}
return sb.toString();
}
@Override
public String toString() {
return valuesAsString();
}
@Override
public int compareTo(Object other) {
return className.compareTo(((ClassAndVariableDetails) other).className);
}
}
| {
"content_hash": "78786d0dc70b1df54644253603fe3d68",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 85,
"avg_line_length": 29.47252747252747,
"alnum_prop": 0.6905294556301268,
"repo_name": "smgoller/geode",
"id": "7a9794afbeec114f65c7e3501869b0c1f2b498cd",
"size": "3471",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "geode-junit/src/main/java/org/apache/geode/codeAnalysis/ClassAndVariableDetails.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "104031"
},
{
"name": "Dockerfile",
"bytes": "15956"
},
{
"name": "Go",
"bytes": "40709"
},
{
"name": "Groovy",
"bytes": "41926"
},
{
"name": "HTML",
"bytes": "4037528"
},
{
"name": "Java",
"bytes": "33124128"
},
{
"name": "JavaScript",
"bytes": "1780821"
},
{
"name": "Python",
"bytes": "29801"
},
{
"name": "Ruby",
"bytes": "1801"
},
{
"name": "SCSS",
"bytes": "2677"
},
{
"name": "Shell",
"bytes": "274196"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "cd01d418084cf2e1123bcb3b09e0761a",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e262fc95ecf0671ff41e4b83ace17f369fab7b50",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Grammitidaceae/Xiphopteris/Xiphopteris aethiopica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.pentaho.di.ui.trans.steps.sftpput;
import java.net.InetAddress;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.entries.sftp.SFTPClient;
import org.pentaho.di.job.entries.sftpput.JobEntrySFTPPUT;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.steps.sftpput.SFTPPutMeta;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.LabelTextVar;
import org.pentaho.di.ui.core.widget.PasswordTextVar;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
/**
* Send file to SFTP host.
*
* @author Samatar Hassan
* @since 30-April-2012
*/
public class SFTPPutDialog extends BaseStepDialog implements StepDialogInterface {
//for i18n purposes, needed by Translator2!!
private static Class<?> PKG = org.pentaho.di.trans.steps.sftpput.SFTPPutMeta.class;
private boolean gotPreviousFields = false;
private static final String[] FILETYPES =
new String[] {
BaseMessages.getString( PKG, "SFTPPUT.Filetype.Pem" ),
BaseMessages.getString( PKG, "SFTPPUT.Filetype.All" ) };
private SFTPPutMeta input;
private CTabFolder wTabFolder;
private Composite wGeneralComp, wFilesComp;
private CTabItem wGeneralTab, wFilesTab;
private FormData fdGeneralComp, fdFilesComp;
private FormData fdTabFolder;
private SelectionAdapter lsDef;
private Group wServerSettings;
private FormData fdServerSettings;
private Group wSourceFiles;
private FormData fdSourceFiles;
private Group wTargetFiles;
private FormData fdTargetFiles;
private Label wlSourceFileNameField;
private CCombo wSourceFileNameField;
private FormData fdlSourceFileNameField, fdSourceFileNameField;
private boolean changed;
private Button wTest;
private FormData fdTest;
private Listener lsTest;
private Label wlAddFilenameToResult;
private Button wAddFilenameToResult;
private FormData fdlAddFilenameToResult, fdAddFilenameToResult;
private Label wlInputIsStream;
private Button wInputIsStream;
private FormData fdlInputIsStream, fdInputIsStream;
private LabelTextVar wkeyfilePass;
private FormData fdkeyfilePass;
private Label wlusePublicKey;
private Button wusePublicKey;
private FormData fdlusePublicKey, fdusePublicKey;
private Label wlKeyFilename;
private Button wbKeyFilename;
private TextVar wKeyFilename;
private FormData fdlKeyFilename, fdbKeyFilename, fdKeyFilename;
private Label wlCreateRemoteFolder;
private Button wCreateRemoteFolder;
private FormData fdlCreateRemoteFolder, fdCreateRemoteFolder;
private Label wlServerName;
private TextVar wServerName;
private FormData fdlServerName, fdServerName;
private Label wlServerPort;
private TextVar wServerPort;
private FormData fdlServerPort, fdServerPort;
private Label wlUserName;
private TextVar wUserName;
private FormData fdlUserName, fdUserName;
private Label wlPassword;
private TextVar wPassword;
private FormData fdlPassword, fdPassword;
private Label wlRemoteDirectory;
private CCombo wRemoteDirectory;
private FormData fdlRemoteDirectory, fdRemoteDirectory;
private Label wlProxyType;
private FormData fdlProxyType;
private CCombo wProxyType;
private FormData fdProxyType;
private LabelTextVar wProxyHost;
private FormData fdProxyHost;
private LabelTextVar wProxyPort;
private FormData fdProxyPort;
private LabelTextVar wProxyUsername;
private FormData fdProxyUsername;
private LabelTextVar wProxyPassword;
private FormData fdProxyPasswd;
private Label wlCompression;
private FormData fdlCompression;
private CCombo wCompression;
private FormData fdCompression;
private Label wlAfterFTPPut;
private CCombo wAfterFTPPut;
private FormData fdlAfterFTPPut, fdAfterFTPPut;
private Label wlCreateDestinationFolder;
private Button wCreateDestinationFolder;
private FormData fdlCreateDestinationFolder, fdCreateDestinationFolder;
private Label wlDestinationFolderFieldName;
private CCombo wDestinationFolderFieldName;
private FormData fdlDestinationFolderFieldName, fdDestinationFolderFieldName;
private Label wlRemoteFileName;
private CCombo wRemoteFileName;
private FormData fdlRemoteFileName, fdRemoteFileName;
private SFTPClient sftpclient = null;
public SFTPPutDialog( Shell parent, Object in, TransMeta tr, String sname ) {
super( parent, (BaseStepMeta) in, tr, sname );
input = (SFTPPutMeta) in;
}
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX );
props.setLook( shell );
setShellImage( shell, input );
ModifyListener lsMod = new ModifyListener() {
public void modifyText( ModifyEvent e ) {
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "SFTPPutDialog.Shell.Title" ) );
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname = new Label( shell, SWT.RIGHT );
wlStepname.setText( BaseMessages.getString( PKG, "SFTPPutDialog.Stepname.Label" ) );
props.setLook( wlStepname );
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment( 0, 0 );
fdlStepname.right = new FormAttachment( middle, -margin );
fdlStepname.top = new FormAttachment( 0, margin );
wlStepname.setLayoutData( fdlStepname );
wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wStepname.setText( stepname );
props.setLook( wStepname );
wStepname.addModifyListener( lsMod );
fdStepname = new FormData();
fdStepname.left = new FormAttachment( middle, 0 );
fdStepname.top = new FormAttachment( 0, margin );
fdStepname.right = new FormAttachment( 100, 0 );
wStepname.setLayoutData( fdStepname );
wTabFolder = new CTabFolder( shell, SWT.BORDER );
props.setLook( wTabFolder, Props.WIDGET_STYLE_TAB );
// ////////////////////////
// START OF GENERAL TAB ///
// ////////////////////////
wGeneralTab = new CTabItem( wTabFolder, SWT.NONE );
wGeneralTab.setText( BaseMessages.getString( PKG, "SFTPPutDialog.Tab.General.Label" ) );
wGeneralComp = new Composite( wTabFolder, SWT.NONE );
props.setLook( wGeneralComp );
FormLayout generalLayout = new FormLayout();
generalLayout.marginWidth = 3;
generalLayout.marginHeight = 3;
wGeneralComp.setLayout( generalLayout );
// ////////////////////////
// START OF SERVER SETTINGS GROUP///
// /
wServerSettings = new Group( wGeneralComp, SWT.SHADOW_NONE );
props.setLook( wServerSettings );
wServerSettings.setText( BaseMessages.getString( PKG, "SFTPPUT.ServerSettings.Group.Label" ) );
FormLayout ServerSettingsgroupLayout = new FormLayout();
ServerSettingsgroupLayout.marginWidth = 10;
ServerSettingsgroupLayout.marginHeight = 10;
wServerSettings.setLayout( ServerSettingsgroupLayout );
// ServerName line
wlServerName = new Label( wServerSettings, SWT.RIGHT );
wlServerName.setText( BaseMessages.getString( PKG, "SFTPPUT.Server.Label" ) );
props.setLook( wlServerName );
fdlServerName = new FormData();
fdlServerName.left = new FormAttachment( 0, 0 );
fdlServerName.top = new FormAttachment( wStepname, margin );
fdlServerName.right = new FormAttachment( middle, -margin );
wlServerName.setLayoutData( fdlServerName );
wServerName = new TextVar( transMeta, wServerSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wServerName );
wServerName.addModifyListener( lsMod );
fdServerName = new FormData();
fdServerName.left = new FormAttachment( middle, 0 );
fdServerName.top = new FormAttachment( wStepname, margin );
fdServerName.right = new FormAttachment( 100, 0 );
wServerName.setLayoutData( fdServerName );
// ServerPort line
wlServerPort = new Label( wServerSettings, SWT.RIGHT );
wlServerPort.setText( BaseMessages.getString( PKG, "SFTPPUT.Port.Label" ) );
props.setLook( wlServerPort );
fdlServerPort = new FormData();
fdlServerPort.left = new FormAttachment( 0, 0 );
fdlServerPort.top = new FormAttachment( wServerName, margin );
fdlServerPort.right = new FormAttachment( middle, -margin );
wlServerPort.setLayoutData( fdlServerPort );
wServerPort = new TextVar( transMeta, wServerSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wServerPort );
wServerPort.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.Port.Tooltip" ) );
wServerPort.addModifyListener( lsMod );
fdServerPort = new FormData();
fdServerPort.left = new FormAttachment( middle, 0 );
fdServerPort.top = new FormAttachment( wServerName, margin );
fdServerPort.right = new FormAttachment( 100, 0 );
wServerPort.setLayoutData( fdServerPort );
// UserName line
wlUserName = new Label( wServerSettings, SWT.RIGHT );
wlUserName.setText( BaseMessages.getString( PKG, "SFTPPUT.Username.Label" ) );
props.setLook( wlUserName );
fdlUserName = new FormData();
fdlUserName.left = new FormAttachment( 0, 0 );
fdlUserName.top = new FormAttachment( wServerPort, margin );
fdlUserName.right = new FormAttachment( middle, -margin );
wlUserName.setLayoutData( fdlUserName );
wUserName = new TextVar( transMeta, wServerSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wUserName );
wUserName.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.Username.Tooltip" ) );
wUserName.addModifyListener( lsMod );
fdUserName = new FormData();
fdUserName.left = new FormAttachment( middle, 0 );
fdUserName.top = new FormAttachment( wServerPort, margin );
fdUserName.right = new FormAttachment( 100, 0 );
wUserName.setLayoutData( fdUserName );
// Password line
wlPassword = new Label( wServerSettings, SWT.RIGHT );
wlPassword.setText( BaseMessages.getString( PKG, "SFTPPUT.Password.Label" ) );
props.setLook( wlPassword );
fdlPassword = new FormData();
fdlPassword.left = new FormAttachment( 0, 0 );
fdlPassword.top = new FormAttachment( wUserName, margin );
fdlPassword.right = new FormAttachment( middle, -margin );
wlPassword.setLayoutData( fdlPassword );
wPassword = new PasswordTextVar( transMeta, wServerSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wPassword );
wPassword.addModifyListener( lsMod );
fdPassword = new FormData();
fdPassword.left = new FormAttachment( middle, 0 );
fdPassword.top = new FormAttachment( wUserName, margin );
fdPassword.right = new FormAttachment( 100, 0 );
wPassword.setLayoutData( fdPassword );
// usePublicKey
wlusePublicKey = new Label( wServerSettings, SWT.RIGHT );
wlusePublicKey.setText( BaseMessages.getString( PKG, "SFTPPUT.useKeyFile.Label" ) );
props.setLook( wlusePublicKey );
fdlusePublicKey = new FormData();
fdlusePublicKey.left = new FormAttachment( 0, 0 );
fdlusePublicKey.top = new FormAttachment( wPassword, margin );
fdlusePublicKey.right = new FormAttachment( middle, -margin );
wlusePublicKey.setLayoutData( fdlusePublicKey );
wusePublicKey = new Button( wServerSettings, SWT.CHECK );
wusePublicKey.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.useKeyFile.Tooltip" ) );
props.setLook( wusePublicKey );
fdusePublicKey = new FormData();
fdusePublicKey.left = new FormAttachment( middle, 0 );
fdusePublicKey.top = new FormAttachment( wPassword, margin );
fdusePublicKey.right = new FormAttachment( 100, 0 );
wusePublicKey.setLayoutData( fdusePublicKey );
wusePublicKey.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
activeUseKey();
transMeta.setChanged();
}
} );
// Key File
wlKeyFilename = new Label( wServerSettings, SWT.RIGHT );
wlKeyFilename.setText( BaseMessages.getString( PKG, "SFTPPUT.KeyFilename.Label" ) );
props.setLook( wlKeyFilename );
fdlKeyFilename = new FormData();
fdlKeyFilename.left = new FormAttachment( 0, 0 );
fdlKeyFilename.top = new FormAttachment( wusePublicKey, margin );
fdlKeyFilename.right = new FormAttachment( middle, -margin );
wlKeyFilename.setLayoutData( fdlKeyFilename );
wbKeyFilename = new Button( wServerSettings, SWT.PUSH | SWT.CENTER );
props.setLook( wbKeyFilename );
wbKeyFilename.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) );
fdbKeyFilename = new FormData();
fdbKeyFilename.right = new FormAttachment( 100, 0 );
fdbKeyFilename.top = new FormAttachment( wusePublicKey, 0 );
// fdbKeyFilename.height = 22;
wbKeyFilename.setLayoutData( fdbKeyFilename );
wKeyFilename = new TextVar( transMeta, wServerSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wKeyFilename.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.KeyFilename.Tooltip" ) );
props.setLook( wKeyFilename );
wKeyFilename.addModifyListener( lsMod );
fdKeyFilename = new FormData();
fdKeyFilename.left = new FormAttachment( middle, 0 );
fdKeyFilename.top = new FormAttachment( wusePublicKey, margin );
fdKeyFilename.right = new FormAttachment( wbKeyFilename, -margin );
wKeyFilename.setLayoutData( fdKeyFilename );
wbKeyFilename.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
FileDialog dialog = new FileDialog( shell, SWT.OPEN );
dialog.setFilterExtensions( new String[] { "*.pem", "*" } );
if ( wKeyFilename.getText() != null ) {
dialog.setFileName( transMeta.environmentSubstitute( wKeyFilename.getText() ) );
}
dialog.setFilterNames( FILETYPES );
if ( dialog.open() != null ) {
wKeyFilename.setText( dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName() );
}
}
} );
// keyfilePass line
wkeyfilePass =
new LabelTextVar(
transMeta, wServerSettings, BaseMessages.getString( PKG, "SFTPPUT.keyfilePass.Label" ), BaseMessages
.getString( PKG, "SFTPPUT.keyfilePass.Tooltip" ), true );
props.setLook( wkeyfilePass );
wkeyfilePass.addModifyListener( lsMod );
fdkeyfilePass = new FormData();
fdkeyfilePass.left = new FormAttachment( 0, -margin );
fdkeyfilePass.top = new FormAttachment( wKeyFilename, margin );
fdkeyfilePass.right = new FormAttachment( 100, 0 );
wkeyfilePass.setLayoutData( fdkeyfilePass );
wlProxyType = new Label( wServerSettings, SWT.RIGHT );
wlProxyType.setText( BaseMessages.getString( PKG, "SFTPPUT.ProxyType.Label" ) );
props.setLook( wlProxyType );
fdlProxyType = new FormData();
fdlProxyType.left = new FormAttachment( 0, 0 );
fdlProxyType.right = new FormAttachment( middle, -margin );
fdlProxyType.top = new FormAttachment( wkeyfilePass, 2 * margin );
wlProxyType.setLayoutData( fdlProxyType );
wProxyType = new CCombo( wServerSettings, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER );
wProxyType.add( SFTPClient.PROXY_TYPE_HTTP );
wProxyType.add( SFTPClient.PROXY_TYPE_SOCKS5 );
wProxyType.select( 0 ); // +1: starts at -1
props.setLook( wProxyType );
fdProxyType = new FormData();
fdProxyType.left = new FormAttachment( middle, 0 );
fdProxyType.top = new FormAttachment( wkeyfilePass, 2 * margin );
fdProxyType.right = new FormAttachment( 100, 0 );
wProxyType.setLayoutData( fdProxyType );
wProxyType.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
setDefaulProxyPort();
}
} );
// Proxy host line
wProxyHost =
new LabelTextVar(
transMeta, wServerSettings, BaseMessages.getString( PKG, "SFTPPUT.ProxyHost.Label" ), BaseMessages
.getString( PKG, "SFTPPUT.ProxyHost.Tooltip" ) );
props.setLook( wProxyHost );
wProxyHost.addModifyListener( lsMod );
fdProxyHost = new FormData();
fdProxyHost.left = new FormAttachment( 0, -2 * margin );
fdProxyHost.top = new FormAttachment( wProxyType, margin );
fdProxyHost.right = new FormAttachment( 100, 0 );
wProxyHost.setLayoutData( fdProxyHost );
// Proxy port line
wProxyPort =
new LabelTextVar(
transMeta, wServerSettings, BaseMessages.getString( PKG, "SFTPPUT.ProxyPort.Label" ), BaseMessages
.getString( PKG, "SFTPPUT.ProxyPort.Tooltip" ) );
props.setLook( wProxyPort );
wProxyPort.addModifyListener( lsMod );
fdProxyPort = new FormData();
fdProxyPort.left = new FormAttachment( 0, -2 * margin );
fdProxyPort.top = new FormAttachment( wProxyHost, margin );
fdProxyPort.right = new FormAttachment( 100, 0 );
wProxyPort.setLayoutData( fdProxyPort );
// Proxy username line
wProxyUsername =
new LabelTextVar(
transMeta, wServerSettings, BaseMessages.getString( PKG, "SFTPPUT.ProxyUsername.Label" ), BaseMessages
.getString( PKG, "SFTPPUT.ProxyUsername.Tooltip" ) );
props.setLook( wProxyUsername );
wProxyUsername.addModifyListener( lsMod );
fdProxyUsername = new FormData();
fdProxyUsername.left = new FormAttachment( 0, -2 * margin );
fdProxyUsername.top = new FormAttachment( wProxyPort, margin );
fdProxyUsername.right = new FormAttachment( 100, 0 );
wProxyUsername.setLayoutData( fdProxyUsername );
// Proxy password line
wProxyPassword =
new LabelTextVar(
transMeta, wServerSettings, BaseMessages.getString( PKG, "SFTPPUT.ProxyPassword.Label" ), BaseMessages
.getString( PKG, "SFTPPUT.ProxyPassword.Tooltip" ), true );
props.setLook( wProxyPassword );
wProxyPassword.addModifyListener( lsMod );
fdProxyPasswd = new FormData();
fdProxyPasswd.left = new FormAttachment( 0, -2 * margin );
fdProxyPasswd.top = new FormAttachment( wProxyUsername, margin );
fdProxyPasswd.right = new FormAttachment( 100, 0 );
wProxyPassword.setLayoutData( fdProxyPasswd );
// Test connection button
wTest = new Button( wServerSettings, SWT.PUSH );
wTest.setText( BaseMessages.getString( PKG, "SFTPPUT.TestConnection.Label" ) );
props.setLook( wTest );
fdTest = new FormData();
wTest.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.TestConnection.Tooltip" ) );
fdTest.top = new FormAttachment( wProxyPassword, margin );
fdTest.right = new FormAttachment( 100, 0 );
wTest.setLayoutData( fdTest );
fdServerSettings = new FormData();
fdServerSettings.left = new FormAttachment( 0, margin );
fdServerSettings.top = new FormAttachment( wStepname, margin );
fdServerSettings.right = new FormAttachment( 100, -margin );
wServerSettings.setLayoutData( fdServerSettings );
// ///////////////////////////////////////////////////////////
// / END OF SERVER SETTINGS GROUP
// ///////////////////////////////////////////////////////////
wlCompression = new Label( wGeneralComp, SWT.RIGHT );
wlCompression.setText( BaseMessages.getString( PKG, "SFTPPUT.Compression.Label" ) );
props.setLook( wlCompression );
fdlCompression = new FormData();
fdlCompression.left = new FormAttachment( 0, -margin );
fdlCompression.right = new FormAttachment( middle, 0 );
fdlCompression.top = new FormAttachment( wServerSettings, margin );
wlCompression.setLayoutData( fdlCompression );
wCompression = new CCombo( wGeneralComp, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER );
wCompression.add( "none" );
wCompression.add( "zlib" );
wCompression.select( 0 ); // +1: starts at -1
props.setLook( wCompression );
fdCompression = new FormData();
fdCompression.left = new FormAttachment( middle, margin );
fdCompression.top = new FormAttachment( wServerSettings, margin );
fdCompression.right = new FormAttachment( 100, 0 );
wCompression.setLayoutData( fdCompression );
fdGeneralComp = new FormData();
fdGeneralComp.left = new FormAttachment( 0, 0 );
fdGeneralComp.top = new FormAttachment( 0, 0 );
fdGeneralComp.right = new FormAttachment( 100, 0 );
fdGeneralComp.bottom = new FormAttachment( 100, 0 );
wGeneralComp.setLayoutData( fdGeneralComp );
wGeneralComp.layout();
wGeneralTab.setControl( wGeneralComp );
props.setLook( wGeneralComp );
// ///////////////////////////////////////////////////////////
// / END OF GENERAL TAB
// ///////////////////////////////////////////////////////////
// ////////////////////////
// START OF Files TAB ///
// ////////////////////////
wFilesTab = new CTabItem( wTabFolder, SWT.NONE );
wFilesTab.setText( BaseMessages.getString( PKG, "SFTPPUT.Tab.Files.Label" ) );
wFilesComp = new Composite( wTabFolder, SWT.NONE );
props.setLook( wFilesComp );
FormLayout FilesLayout = new FormLayout();
FilesLayout.marginWidth = 3;
FilesLayout.marginHeight = 3;
wFilesComp.setLayout( FilesLayout );
// ////////////////////////
// START OF Source files GROUP///
// /
wSourceFiles = new Group( wFilesComp, SWT.SHADOW_NONE );
props.setLook( wSourceFiles );
wSourceFiles.setText( BaseMessages.getString( PKG, "SFTPPUT.SourceFiles.Group.Label" ) );
FormLayout SourceFilesgroupLayout = new FormLayout();
SourceFilesgroupLayout.marginWidth = 10;
SourceFilesgroupLayout.marginHeight = 10;
wSourceFiles.setLayout( SourceFilesgroupLayout );
// Add filenames to result filenames...
wlInputIsStream = new Label( wSourceFiles, SWT.RIGHT );
wlInputIsStream.setText( BaseMessages.getString( PKG, "SFTPPUT.InputIsStream.Label" ) );
props.setLook( wlInputIsStream );
fdlInputIsStream = new FormData();
fdlInputIsStream.left = new FormAttachment( 0, 0 );
fdlInputIsStream.top = new FormAttachment( wStepname, margin );
fdlInputIsStream.right = new FormAttachment( middle, -margin );
wlInputIsStream.setLayoutData( fdlInputIsStream );
wInputIsStream = new Button( wSourceFiles, SWT.CHECK );
wInputIsStream.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.InputIsStream.Tooltip" ) );
props.setLook( wInputIsStream );
fdInputIsStream = new FormData();
fdInputIsStream.left = new FormAttachment( middle, 0 );
fdInputIsStream.top = new FormAttachment( wStepname, margin );
fdInputIsStream.right = new FormAttachment( 100, 0 );
wInputIsStream.setLayoutData( fdInputIsStream );
wInputIsStream.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
setInputStream();
transMeta.setChanged();
}
} );
// SourceFileNameField field
wlSourceFileNameField = new Label( wSourceFiles, SWT.RIGHT );
wlSourceFileNameField.setText( BaseMessages.getString( PKG, "SFTPPUTDialog.SourceFileNameField.Label" ) );
props.setLook( wlSourceFileNameField );
fdlSourceFileNameField = new FormData();
fdlSourceFileNameField.left = new FormAttachment( 0, 0 );
fdlSourceFileNameField.right = new FormAttachment( middle, -margin );
fdlSourceFileNameField.top = new FormAttachment( wInputIsStream, margin );
wlSourceFileNameField.setLayoutData( fdlSourceFileNameField );
wSourceFileNameField = new CCombo( wSourceFiles, SWT.BORDER | SWT.READ_ONLY );
props.setLook( wSourceFileNameField );
wSourceFileNameField.setEditable( true );
wSourceFileNameField.addModifyListener( lsMod );
fdSourceFileNameField = new FormData();
fdSourceFileNameField.left = new FormAttachment( middle, 0 );
fdSourceFileNameField.top = new FormAttachment( wInputIsStream, margin );
fdSourceFileNameField.right = new FormAttachment( 100, -margin );
wSourceFileNameField.setLayoutData( fdSourceFileNameField );
wSourceFileNameField.addFocusListener( new FocusListener() {
public void focusLost( org.eclipse.swt.events.FocusEvent e ) {
}
public void focusGained( org.eclipse.swt.events.FocusEvent e ) {
Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT );
shell.setCursor( busy );
getFields();
shell.setCursor( null );
busy.dispose();
}
} );
// Add filenames to result filenames...
wlAddFilenameToResult = new Label( wSourceFiles, SWT.RIGHT );
wlAddFilenameToResult.setText( BaseMessages.getString( PKG, "SFTPPUT.AddfilenametoResult.Label" ) );
props.setLook( wlAddFilenameToResult );
fdlAddFilenameToResult = new FormData();
fdlAddFilenameToResult.left = new FormAttachment( 0, 0 );
fdlAddFilenameToResult.top = new FormAttachment( wSourceFileNameField, margin );
fdlAddFilenameToResult.right = new FormAttachment( middle, -margin );
wlAddFilenameToResult.setLayoutData( fdlAddFilenameToResult );
wAddFilenameToResult = new Button( wSourceFiles, SWT.CHECK );
wAddFilenameToResult.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.AddfilenametoResult.Tooltip" ) );
props.setLook( wAddFilenameToResult );
fdAddFilenameToResult = new FormData();
fdAddFilenameToResult.left = new FormAttachment( middle, 0 );
fdAddFilenameToResult.top = new FormAttachment( wSourceFileNameField, margin );
fdAddFilenameToResult.right = new FormAttachment( 100, 0 );
wAddFilenameToResult.setLayoutData( fdAddFilenameToResult );
// After FTP Put
wlAfterFTPPut = new Label( wSourceFiles, SWT.RIGHT );
wlAfterFTPPut.setText( BaseMessages.getString( PKG, "SFTPPUT.AfterFTPPut.Label" ) );
props.setLook( wlAfterFTPPut );
fdlAfterFTPPut = new FormData();
fdlAfterFTPPut.left = new FormAttachment( 0, 0 );
fdlAfterFTPPut.right = new FormAttachment( middle, -margin );
fdlAfterFTPPut.top = new FormAttachment( wAddFilenameToResult, 2 * margin );
wlAfterFTPPut.setLayoutData( fdlAfterFTPPut );
wAfterFTPPut = new CCombo( wSourceFiles, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER );
wAfterFTPPut.add( BaseMessages.getString( PKG, "SFTPPUT.AfterSFTP.DoNothing.Label" ) );
wAfterFTPPut.add( BaseMessages.getString( PKG, "SFTPPUT.AfterSFTP.Delete.Label" ) );
wAfterFTPPut.add( BaseMessages.getString( PKG, "SFTPPUT.AfterSFTP.Move.Label" ) );
wAfterFTPPut.select( 0 ); // +1: starts at -1
props.setLook( wAfterFTPPut );
fdAfterFTPPut = new FormData();
fdAfterFTPPut.left = new FormAttachment( middle, 0 );
fdAfterFTPPut.top = new FormAttachment( wAddFilenameToResult, 2 * margin );
fdAfterFTPPut.right = new FormAttachment( 100, -margin );
wAfterFTPPut.setLayoutData( fdAfterFTPPut );
wAfterFTPPut.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
AfterFTPPutActivate();
}
} );
// moveTo Directory
wlDestinationFolderFieldName = new Label( wSourceFiles, SWT.RIGHT );
wlDestinationFolderFieldName.setText( BaseMessages.getString( PKG, "SFTPPUT.DestinationFolder.Label" ) );
props.setLook( wlDestinationFolderFieldName );
fdlDestinationFolderFieldName = new FormData();
fdlDestinationFolderFieldName.left = new FormAttachment( 0, 0 );
fdlDestinationFolderFieldName.top = new FormAttachment( wAfterFTPPut, margin );
fdlDestinationFolderFieldName.right = new FormAttachment( middle, -margin );
wlDestinationFolderFieldName.setLayoutData( fdlDestinationFolderFieldName );
wDestinationFolderFieldName = new CCombo( wSourceFiles, SWT.BORDER | SWT.READ_ONLY );
wDestinationFolderFieldName
.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.DestinationFolder.Tooltip" ) );
props.setLook( wDestinationFolderFieldName );
wDestinationFolderFieldName.addModifyListener( lsMod );
fdDestinationFolderFieldName = new FormData();
fdDestinationFolderFieldName.left = new FormAttachment( middle, 0 );
fdDestinationFolderFieldName.top = new FormAttachment( wAfterFTPPut, margin );
fdDestinationFolderFieldName.right = new FormAttachment( 100, -margin );
wDestinationFolderFieldName.setLayoutData( fdDestinationFolderFieldName );
// Whenever something changes, set the tooltip to the expanded version:
wDestinationFolderFieldName.addModifyListener( new ModifyListener() {
public void modifyText( ModifyEvent e ) {
wDestinationFolderFieldName.setToolTipText( transMeta.environmentSubstitute( wDestinationFolderFieldName
.getText() ) );
}
} );
wDestinationFolderFieldName.addFocusListener( new FocusListener() {
public void focusLost( org.eclipse.swt.events.FocusEvent e ) {
}
public void focusGained( org.eclipse.swt.events.FocusEvent e ) {
Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT );
shell.setCursor( busy );
getFields();
shell.setCursor( null );
busy.dispose();
}
} );
// Create destination folder if necessary ...
wlCreateDestinationFolder = new Label( wSourceFiles, SWT.RIGHT );
wlCreateDestinationFolder.setText( BaseMessages.getString( PKG, "SFTPPUT.CreateDestinationFolder.Label" ) );
props.setLook( wlCreateDestinationFolder );
fdlCreateDestinationFolder = new FormData();
fdlCreateDestinationFolder.left = new FormAttachment( 0, 0 );
fdlCreateDestinationFolder.top = new FormAttachment( wDestinationFolderFieldName, margin );
fdlCreateDestinationFolder.right = new FormAttachment( middle, -margin );
wlCreateDestinationFolder.setLayoutData( fdlCreateDestinationFolder );
wCreateDestinationFolder = new Button( wSourceFiles, SWT.CHECK );
wCreateDestinationFolder.setToolTipText( BaseMessages.getString(
PKG, "SFTPPUT.CreateDestinationFolder.Tooltip" ) );
props.setLook( wCreateDestinationFolder );
fdCreateDestinationFolder = new FormData();
fdCreateDestinationFolder.left = new FormAttachment( middle, 0 );
fdCreateDestinationFolder.top = new FormAttachment( wDestinationFolderFieldName, margin );
fdCreateDestinationFolder.right = new FormAttachment( 100, 0 );
wCreateDestinationFolder.setLayoutData( fdCreateDestinationFolder );
fdSourceFiles = new FormData();
fdSourceFiles.left = new FormAttachment( 0, margin );
fdSourceFiles.top = new FormAttachment( wServerSettings, 2 * margin );
fdSourceFiles.right = new FormAttachment( 100, -margin );
wSourceFiles.setLayoutData( fdSourceFiles );
// ///////////////////////////////////////////////////////////
// / END OF Source files GROUP
// ///////////////////////////////////////////////////////////
// ////////////////////////
// START OF Target files GROUP///
// /
wTargetFiles = new Group( wFilesComp, SWT.SHADOW_NONE );
props.setLook( wTargetFiles );
wTargetFiles.setText( BaseMessages.getString( PKG, "SFTPPUT.TargetFiles.Group.Label" ) );
FormLayout TargetFilesgroupLayout = new FormLayout();
TargetFilesgroupLayout.marginWidth = 10;
TargetFilesgroupLayout.marginHeight = 10;
wTargetFiles.setLayout( TargetFilesgroupLayout );
// FtpDirectory line
wlRemoteDirectory = new Label( wTargetFiles, SWT.RIGHT );
wlRemoteDirectory.setText( BaseMessages.getString( PKG, "SFTPPUT.RemoteDir.Label" ) );
props.setLook( wlRemoteDirectory );
fdlRemoteDirectory = new FormData();
fdlRemoteDirectory.left = new FormAttachment( 0, 0 );
fdlRemoteDirectory.top = new FormAttachment( wSourceFiles, margin );
fdlRemoteDirectory.right = new FormAttachment( middle, -margin );
wlRemoteDirectory.setLayoutData( fdlRemoteDirectory );
// Target (remote) folder
wRemoteDirectory = new CCombo( wTargetFiles, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER );
props.setLook( wRemoteDirectory );
wRemoteDirectory.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.RemoteDir.Tooltip" ) );
wRemoteDirectory.addModifyListener( lsMod );
fdRemoteDirectory = new FormData();
fdRemoteDirectory.left = new FormAttachment( middle, 0 );
fdRemoteDirectory.top = new FormAttachment( wSourceFiles, margin );
fdRemoteDirectory.right = new FormAttachment( 100, -margin );
wRemoteDirectory.setLayoutData( fdRemoteDirectory );
wRemoteDirectory.addFocusListener( new FocusListener() {
public void focusLost( org.eclipse.swt.events.FocusEvent e ) {
}
public void focusGained( org.eclipse.swt.events.FocusEvent e ) {
Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT );
shell.setCursor( busy );
getFields();
shell.setCursor( null );
busy.dispose();
}
} );
// CreateRemoteFolder files after retrieval...
wlCreateRemoteFolder = new Label( wTargetFiles, SWT.RIGHT );
wlCreateRemoteFolder.setText( BaseMessages.getString( PKG, "SFTPPUT.CreateRemoteFolderFiles.Label" ) );
props.setLook( wlCreateRemoteFolder );
fdlCreateRemoteFolder = new FormData();
fdlCreateRemoteFolder.left = new FormAttachment( 0, 0 );
fdlCreateRemoteFolder.top = new FormAttachment( wRemoteDirectory, margin );
fdlCreateRemoteFolder.right = new FormAttachment( middle, -margin );
wlCreateRemoteFolder.setLayoutData( fdlCreateRemoteFolder );
wCreateRemoteFolder = new Button( wTargetFiles, SWT.CHECK );
props.setLook( wCreateRemoteFolder );
fdCreateRemoteFolder = new FormData();
wCreateRemoteFolder.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.CreateRemoteFolderFiles.Tooltip" ) );
fdCreateRemoteFolder.left = new FormAttachment( middle, 0 );
fdCreateRemoteFolder.top = new FormAttachment( wRemoteDirectory, margin );
fdCreateRemoteFolder.right = new FormAttachment( 100, 0 );
wCreateRemoteFolder.setLayoutData( fdCreateRemoteFolder );
wCreateRemoteFolder.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
transMeta.setChanged();
}
} );
// Remote filename
wlRemoteFileName = new Label( wTargetFiles, SWT.RIGHT );
wlRemoteFileName.setText( BaseMessages.getString( PKG, "SFTPPUT.RemoteFilename.Label" ) );
props.setLook( wlRemoteFileName );
fdlRemoteFileName = new FormData();
fdlRemoteFileName.left = new FormAttachment( 0, 0 );
fdlRemoteFileName.top = new FormAttachment( wCreateRemoteFolder, margin );
fdlRemoteFileName.right = new FormAttachment( middle, -margin );
wlRemoteFileName.setLayoutData( fdlRemoteFileName );
// Target (remote) folder
wRemoteFileName = new CCombo( wTargetFiles, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER );
props.setLook( wRemoteFileName );
wRemoteFileName.setToolTipText( BaseMessages.getString( PKG, "SFTPPUT.RemoteFilename.Tooltip" ) );
wRemoteFileName.addModifyListener( lsMod );
fdRemoteFileName = new FormData();
fdRemoteFileName.left = new FormAttachment( middle, 0 );
fdRemoteFileName.top = new FormAttachment( wCreateRemoteFolder, margin );
fdRemoteFileName.right = new FormAttachment( 100, -margin );
wRemoteFileName.setLayoutData( fdRemoteFileName );
wRemoteFileName.addFocusListener( new FocusListener() {
public void focusLost( org.eclipse.swt.events.FocusEvent e ) {
}
public void focusGained( org.eclipse.swt.events.FocusEvent e ) {
Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT );
shell.setCursor( busy );
getFields();
shell.setCursor( null );
busy.dispose();
}
} );
fdTargetFiles = new FormData();
fdTargetFiles.left = new FormAttachment( 0, margin );
fdTargetFiles.top = new FormAttachment( wSourceFiles, margin );
fdTargetFiles.right = new FormAttachment( 100, -margin );
wTargetFiles.setLayoutData( fdTargetFiles );
// ///////////////////////////////////////////////////////////
// / END OF Target files GROUP
// ///////////////////////////////////////////////////////////
fdFilesComp = new FormData();
fdFilesComp.left = new FormAttachment( 0, 0 );
fdFilesComp.top = new FormAttachment( 0, 0 );
fdFilesComp.right = new FormAttachment( 100, 0 );
fdFilesComp.bottom = new FormAttachment( 100, 0 );
wFilesComp.setLayoutData( fdFilesComp );
wFilesComp.layout();
wFilesTab.setControl( wFilesComp );
props.setLook( wFilesComp );
// ///////////////////////////////////////////////////////////
// / END OF Files TAB
// ///////////////////////////////////////////////////////////
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment( 0, 0 );
fdTabFolder.top = new FormAttachment( wStepname, margin );
fdTabFolder.right = new FormAttachment( 100, 0 );
fdTabFolder.bottom = new FormAttachment( 100, -50 );
wTabFolder.setLayoutData( fdTabFolder );
// Some buttons
wOK = new Button( shell, SWT.PUSH );
wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
setButtonPositions( new Button[] { wOK, wCancel }, margin, wTabFolder );
// Add listeners
lsCancel = new Listener() {
public void handleEvent( Event e ) {
cancel();
}
};
lsOK = new Listener() {
public void handleEvent( Event e ) {
ok();
}
};
wCancel.addListener( SWT.Selection, lsCancel );
wOK.addListener( SWT.Selection, lsOK );
lsTest = new Listener() {
public void handleEvent( Event e ) {
test();
}
};
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wTest.addListener( SWT.Selection, lsTest );
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wStepname.addSelectionListener( lsDef );
wServerName.addSelectionListener( lsDef );
wUserName.addSelectionListener( lsDef );
wPassword.addSelectionListener( lsDef );
wRemoteDirectory.addSelectionListener( lsDef );
wRemoteFileName.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
public void shellClosed( ShellEvent e ) {
cancel();
}
} );
wTabFolder.setSelection( 0 );
// Set the shell size, based upon previous time...
setSize();
getData();
activeUseKey();
AfterFTPPutActivate();
setInputStream();
input.setChanged( changed );
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return stepname;
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
wServerName.setText( Const.NVL( input.getServerName(), "" ) );
wServerPort.setText( Const.NVL( input.getServerPort(), "" ) );
wUserName.setText( Const.NVL( input.getUserName(), "" ) );
wPassword.setText( Const.NVL( input.getPassword(), "" ) );
wRemoteDirectory.setText( Const.NVL( input.getRemoteDirectoryFieldName(), "" ) );
wSourceFileNameField.setText( Const.NVL( input.getSourceFileFieldName(), "" ) );
wInputIsStream.setSelection( input.isInputStream() );
wAddFilenameToResult.setSelection( input.isAddFilenameResut() );
wusePublicKey.setSelection( input.isUseKeyFile() );
wKeyFilename.setText( Const.NVL( input.getKeyFilename(), "" ) );
wkeyfilePass.setText( Const.NVL( input.getKeyPassPhrase(), "" ) );
wCompression.setText( Const.NVL( input.getCompression(), "none" ) );
wProxyType.setText( Const.NVL( input.getProxyType(), "" ) );
wProxyHost.setText( Const.NVL( input.getProxyHost(), "" ) );
wProxyPort.setText( Const.NVL( input.getProxyPort(), "" ) );
wProxyUsername.setText( Const.NVL( input.getProxyUsername(), "" ) );
wProxyPassword.setText( Const.NVL( input.getProxyPassword(), "" ) );
wCreateRemoteFolder.setSelection( input.isCreateRemoteFolder() );
wAfterFTPPut.setText( JobEntrySFTPPUT.getAfterSFTPPutDesc( input.getAfterFTPS() ) );
wDestinationFolderFieldName.setText( Const.NVL( input.getDestinationFolderFieldName(), "" ) );
wCreateDestinationFolder.setSelection( input.isCreateDestinationFolder() );
wRemoteFileName.setText( Const.NVL( input.getRemoteFilenameFieldName(), "" ) );
wStepname.selectAll();
wStepname.setFocus();
}
private void cancel() {
// Close open connections
closeFTPConnections();
stepname = null;
input.setChanged( changed );
dispose();
}
private void ok() {
if ( Const.isEmpty( wStepname.getText() ) ) {
return;
}
stepname = wStepname.getText(); // return value
input.setServerName( wServerName.getText() );
input.setServerPort( wServerPort.getText() );
input.setUserName( wUserName.getText() );
input.setPassword( wPassword.getText() );
input.setRemoteDirectoryFieldName( wRemoteDirectory.getText() );
input.setSourceFileFieldName( wSourceFileNameField.getText() );
input.setAddFilenameResut( wAddFilenameToResult.getSelection() );
input.setUseKeyFile( wusePublicKey.getSelection() );
input.setKeyFilename( wKeyFilename.getText() );
input.setKeyPassPhrase( wkeyfilePass.getText() );
input.setCompression( wCompression.getText() );
input.setProxyType( wProxyType.getText() );
input.setProxyHost( wProxyHost.getText() );
input.setProxyPort( wProxyPort.getText() );
input.setProxyUsername( wProxyUsername.getText() );
input.setProxyPassword( wProxyPassword.getText() );
input.setCreateRemoteFolder( wCreateRemoteFolder.getSelection() );
input.setAfterFTPS( JobEntrySFTPPUT.getAfterSFTPPutByDesc( wAfterFTPPut.getText() ) );
input.setCreateDestinationFolder( wCreateDestinationFolder.getSelection() );
input.setDestinationFolderFieldName( wDestinationFolderFieldName.getText() );
input.setInputStream( wInputIsStream.getSelection() );
input.setRemoteFilenameFieldName( wRemoteFileName.getText() );
dispose();
}
private void setDefaulProxyPort() {
if ( wProxyType.getText().equals( SFTPClient.PROXY_TYPE_HTTP ) ) {
if ( Const.isEmpty( wProxyPort.getText() )
|| ( !Const.isEmpty( wProxyPort.getText() ) && wProxyPort.getText().equals(
SFTPClient.SOCKS5_DEFAULT_PORT ) ) ) {
wProxyPort.setText( SFTPClient.HTTP_DEFAULT_PORT );
}
} else {
if ( Const.isEmpty( wProxyPort.getText() )
|| ( !Const.isEmpty( wProxyPort.getText() ) && wProxyPort
.getText().equals( SFTPClient.HTTP_DEFAULT_PORT ) ) ) {
wProxyPort.setText( SFTPClient.SOCKS5_DEFAULT_PORT );
}
}
}
private void AfterFTPPutActivate() {
boolean moveFile =
JobEntrySFTPPUT.getAfterSFTPPutByDesc( wAfterFTPPut.getText() ) == JobEntrySFTPPUT.AFTER_FTPSPUT_MOVE;
boolean doNothing =
JobEntrySFTPPUT.getAfterSFTPPutByDesc( wAfterFTPPut.getText() ) == JobEntrySFTPPUT.AFTER_FTPSPUT_NOTHING;
wlDestinationFolderFieldName.setEnabled( moveFile );
wDestinationFolderFieldName.setEnabled( moveFile );
wlCreateDestinationFolder.setEnabled( moveFile );
wCreateDestinationFolder.setEnabled( moveFile );
wlAddFilenameToResult.setEnabled( doNothing );
wAddFilenameToResult.setEnabled( doNothing );
}
private void activeUseKey() {
wlKeyFilename.setEnabled( wusePublicKey.getSelection() );
wKeyFilename.setEnabled( wusePublicKey.getSelection() );
wbKeyFilename.setEnabled( wusePublicKey.getSelection() );
wkeyfilePass.setEnabled( wusePublicKey.getSelection() );
}
private void test() {
if ( connectToSFTP( false, null ) ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage( BaseMessages.getString( PKG, "SFTPPUT.Connected.OK", wServerName.getText() ) + Const.CR );
mb.setText( BaseMessages.getString( PKG, "SFTPPUT.Connected.Title.Ok" ) );
mb.open();
} else {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "SFTPPUT.Connected.NOK.ConnectionBad", wServerName.getText() )
+ Const.CR );
mb.setText( BaseMessages.getString( PKG, "SFTPPUT.Connected.Title.Bad" ) );
mb.open();
}
}
private boolean connectToSFTP( boolean checkFolder, String Remotefoldername ) {
boolean retval = false;
try {
if ( sftpclient == null ) {
// Create sftp client to host ...
sftpclient =
new SFTPClient(
InetAddress.getByName(
transMeta.environmentSubstitute( wServerName.getText() ) ),
Const.toInt( transMeta.environmentSubstitute( wServerPort.getText() ), 22 ),
transMeta.environmentSubstitute( wUserName.getText() ),
transMeta.environmentSubstitute( wKeyFilename.getText() ),
transMeta.environmentSubstitute( wkeyfilePass.getText() ) );
// Set proxy?
String realProxyHost = transMeta.environmentSubstitute( wProxyHost.getText() );
if ( !Const.isEmpty( realProxyHost ) ) {
// Set proxy
sftpclient.setProxy(
realProxyHost,
transMeta.environmentSubstitute( wProxyPort.getText() ),
transMeta.environmentSubstitute( wProxyUsername.getText() ),
transMeta.environmentSubstitute( wProxyPassword.getText() ),
wProxyType.getText() );
}
// login to ftp host ...
sftpclient.login( transMeta.environmentSubstitute( wPassword.getText() ) );
retval = true;
}
if ( checkFolder ) {
retval = sftpclient.folderExists( Remotefoldername );
}
} catch ( Exception e ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "SFTPPUT.ErrorConnect.NOK", wServerName.getText(), e
.getMessage() )
+ Const.CR );
mb.setText( BaseMessages.getString( PKG, "SFTPPUT.ErrorConnect.Title.Bad" ) );
mb.open();
}
return retval;
}
private void getFields() {
if ( !gotPreviousFields ) {
gotPreviousFields = true;
try {
String source = wSourceFileNameField.getText();
String rep = wRemoteDirectory.getText();
String after = wDestinationFolderFieldName.getText();
String remote = wRemoteFileName.getText();
wSourceFileNameField.removeAll();
wRemoteDirectory.removeAll();
wDestinationFolderFieldName.removeAll();
wRemoteFileName.removeAll();
RowMetaInterface r = transMeta.getPrevStepFields( stepname );
if ( r != null ) {
String[] fields = r.getFieldNames();
wSourceFileNameField.setItems( fields );
wRemoteDirectory.setItems( fields );
wDestinationFolderFieldName.setItems( fields );
wRemoteFileName.setItems( fields );
if ( source != null ) {
wSourceFileNameField.setText( source );
}
if ( rep != null ) {
wRemoteDirectory.setText( rep );
}
if ( after != null ) {
wDestinationFolderFieldName.setText( after );
}
if ( remote != null ) {
wRemoteFileName.setText( remote );
}
}
} catch ( KettleException ke ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "SFTPPUTDialog.FailedToGetFields.DialogTitle" ), BaseMessages
.getString( PKG, "SFTPPUTDialog.FailedToGetFields.DialogMessage" ), ke );
}
}
}
private void closeFTPConnections() {
// Close SecureFTP connection if necessary
if ( sftpclient != null ) {
try {
sftpclient.disconnect();
sftpclient = null;
} catch ( Exception e ) {
// Ignore errors
}
}
}
private void setInputStream() {
wAddFilenameToResult.setEnabled( !wInputIsStream.getSelection() );
wlAddFilenameToResult.setEnabled( !wInputIsStream.getSelection() );
if ( wInputIsStream.getSelection() ) {
wAddFilenameToResult.setSelection( false );
}
wlAfterFTPPut.setEnabled( !wInputIsStream.getSelection() );
wAfterFTPPut.setEnabled( !wInputIsStream.getSelection() );
wDestinationFolderFieldName.setEnabled( !wInputIsStream.getSelection() );
wlDestinationFolderFieldName.setEnabled( !wInputIsStream.getSelection() );
wlCreateDestinationFolder.setEnabled( !wInputIsStream.getSelection() );
wCreateDestinationFolder.setEnabled( !wInputIsStream.getSelection() );
}
}
| {
"content_hash": "d631143b47dbe1455904889832786e22",
"timestamp": "",
"source": "github",
"line_count": 1202,
"max_line_length": 115,
"avg_line_length": 41.80116472545757,
"alnum_prop": 0.6993332669917405,
"repo_name": "ma459006574/pentaho-kettle",
"id": "4c181b89204a0fa92f0afe99d160bf77c0483dee",
"size": "51149",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ui/src/org/pentaho/di/ui/trans/steps/sftpput/SFTPPutDialog.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "13747"
},
{
"name": "CSS",
"bytes": "20530"
},
{
"name": "GAP",
"bytes": "4005"
},
{
"name": "HTML",
"bytes": "69726"
},
{
"name": "Java",
"bytes": "34074369"
},
{
"name": "JavaScript",
"bytes": "16314"
},
{
"name": "Shell",
"bytes": "16968"
},
{
"name": "XSLT",
"bytes": "5600"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dip">
<com.google.android.material.button.MaterialButton
android:id="@+id/mute_volume_button"
android:layout_width="0dip"
android:layout_height="35dip"
android:layout_weight="1"
android:gravity="center"
android:text="Mute"
android:textColor="@android:color/white"
android:textAppearance="@android:style/TextAppearance.Medium"
android:background="@drawable/buttonshape"
app:backgroundTint="#a865f3"/>
<wseemann.media.romote.view.RepeatingImageButton
android:id="@+id/decrease_volume_button"
android:layout_width="0dip"
android:layout_height="35dip"
android:layout_weight="1"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:gravity="center"
android:text="-"
android:textColor="@android:color/white"
android:textAppearance="@android:style/TextAppearance.Medium"
android:background="@drawable/buttonshape"
app:backgroundTint="#a865f3"/>
<wseemann.media.romote.view.RepeatingImageButton
android:id="@+id/increase_volume_button"
android:layout_width="0dip"
android:layout_height="35dip"
android:layout_weight="1"
android:gravity="center"
android:text="+"
android:textColor="@android:color/white"
android:textAppearance="@android:style/TextAppearance.Medium"
android:background="@drawable/buttonshape"
app:backgroundTint="#a865f3"/>
</LinearLayout> | {
"content_hash": "0263afcf22b9448441ad6f1848aeefed",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 72,
"avg_line_length": 39.340425531914896,
"alnum_prop": 0.6722552731206057,
"repo_name": "wseemann/RoMote",
"id": "b220ba9d0e9557c8927f91d2fb26cad82182afb4",
"size": "1849",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/dialog_fragment_volume.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AIDL",
"bytes": "172"
},
{
"name": "Java",
"bytes": "350293"
},
{
"name": "Kotlin",
"bytes": "4345"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using Signum.Utilities;
using System.Linq.Expressions;
using Signum.Services;
namespace Signum.Entities.Files
{
[Serializable, EntityKind(EntityKind.SharedPart, EntityData.Transactional)]
public class FilePathEntity : Entity, IFile, IFilePath
{
public static string? ForceExtensionIfEmpty = ".dat";
public FilePathEntity() { }
public FilePathEntity(FileTypeSymbol fileType)
{
this.FileType = fileType;
}
public FilePathEntity(FileTypeSymbol fileType, string path)
: this(fileType)
{
this.FileName = Path.GetFileName(path)!;
this.BinaryFile = File.ReadAllBytes(path);
}
public FilePathEntity(FileTypeSymbol fileType, string fileName, byte[] fileData)
: this(fileType)
{
this.FileName = fileName;
this.BinaryFile = fileData;
}
public DateTime CreationDate { get; private set; } = TimeZoneManager.Now;
string fileName;
[StringLengthValidator(Min = 1, Max = 260), FileNameValidator]
public string FileName
{
get { return fileName; }
set
{
var newValue = fileName;
if (ForceExtensionIfEmpty.HasText() && !Path.GetExtension(value).HasText())
value += ForceExtensionIfEmpty;
Set(ref fileName, value);
}
}
[Ignore]
byte[] binaryFile;
[NotNullValidator(Disabled = true)]
public byte[] BinaryFile
{
get { return binaryFile; }
set
{
if (Set(ref binaryFile, value) && binaryFile != null)
{
FileLength = binaryFile.Length;
Hash = CryptorEngine.CalculateMD5Hash(binaryFile);
}
}
}
public string? Hash { get; private set; }
public int FileLength { get; internal set; }
[AutoExpressionField]
public string FileLengthString => As.Expression(() => ((long)FileLength).ToComputerSize());
[StringLengthValidator(Min = 3, Max = 260), NotNullValidator(DisabledInModelBinder = true)]
public string Suffix { get; set; }
[Ignore]
public string? CalculatedDirectory { get; set; }
public FileTypeSymbol FileType { get; internal set; }
[Ignore]
internal PrefixPair _prefixPair;
public void SetPrefixPair(PrefixPair prefixPair)
{
this._prefixPair = prefixPair;
}
public PrefixPair GetPrefixPair()
{
if (this._prefixPair != null)
return this._prefixPair;
if (CalculatePrefixPair == null)
throw new InvalidOperationException("OnCalculatePrefixPair not set");
this._prefixPair = CalculatePrefixPair(this);
return this._prefixPair;
}
public static Func<FilePathEntity, PrefixPair> CalculatePrefixPair;
public string FullPhysicalPath()
{
var pp = this.GetPrefixPair();
return FilePathUtils.SafeCombine(pp.PhysicalPrefix, Suffix);
}
public static Func<string, string> ToAbsolute = str => str;
public string? FullWebPath()
{
var pp = this.GetPrefixPair();
if (string.IsNullOrEmpty(pp.WebPrefix))
return null;
var result = ToAbsolute(pp.WebPrefix + "/" + FilePathUtils.UrlPathEncode(Suffix.Replace("\\", "/")));
return result;
}
public override string ToString()
{
return "{0} - {1}".FormatWith(FileName, ((long)FileLength).ToComputerSize());
}
protected override void PostRetrieving(PostRetrievingContext ctx)
{
if (CalculatePrefixPair == null)
throw new InvalidOperationException("OnCalculatePrefixPair not set");
this.GetPrefixPair();
}
}
[Serializable]
public class PrefixPair
{
string? physicalPrefix;
public string PhysicalPrefix => physicalPrefix ?? throw new InvalidOperationException("No PhysicalPrefix defined");
public string? WebPrefix { get; set; }
private PrefixPair()
{
this.physicalPrefix = null;
}
public PrefixPair(string physicalPrefix)
{
this.physicalPrefix = physicalPrefix;
}
public static PrefixPair None()
{
return new PrefixPair();
}
public static PrefixPair WebOnly(string webPrefix)
{
return new PrefixPair { WebPrefix = webPrefix };
}
}
[AutoInit]
public static class FilePathOperation
{
public static ExecuteSymbol<FilePathEntity> Save;
}
}
| {
"content_hash": "81de0fdb4169f193bd46f052aebc10d3",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 123,
"avg_line_length": 29.46551724137931,
"alnum_prop": 0.5521747610688512,
"repo_name": "signumsoftware/extensions",
"id": "3ea9281128371ba5e834b420562e3a66c0a8b189",
"size": "5127",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Signum.Entities.Extensions/Files/FilePathEntity.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2759846"
},
{
"name": "CSS",
"bytes": "23517"
},
{
"name": "TypeScript",
"bytes": "1887675"
}
],
"symlink_target": ""
} |
ace.define("ace/ext/whitespace", ["require", "exports", "module", "ace/lib/lang"], function(require, exports, module) {
"use strict";
var lang = require("../lib/lang");
exports.$detectIndentation = function(lines, fallback) {
var stats = [];
var changes = [];
var tabIndents = 0;
var prevSpaces = 0;
var max = Math.min(lines.length, 1000);
for (var i = 0; i < max; i++) {
var line = lines[i];
if (!/^\s*[^*+\-\s]/.test(line))
continue;
if (line[0] == "\t") {
tabIndents++;
prevSpaces = -Number.MAX_VALUE;
}
else {
var spaces = line.match(/^ */)[0].length;
if (spaces && line[spaces] != "\t") {
var diff = spaces - prevSpaces;
if (diff > 0 && !(prevSpaces % diff) && !(spaces % diff))
changes[diff] = (changes[diff] || 0) + 1;
stats[spaces] = (stats[spaces] || 0) + 1;
}
prevSpaces = spaces;
}
while (i < max && line[line.length - 1] == "\\")
line = lines[i++];
}
function getScore(indent) {
var score = 0;
for (var i = indent; i < stats.length; i += indent)
score += stats[i] || 0;
return score;
}
var changesTotal = changes.reduce(function(a, b) {
return a + b;
}, 0);
var first = {
score: 0,
length: 0
};
var spaceIndents = 0;
for (var i = 1; i < 12; i++) {
var score = getScore(i);
if (i == 1) {
spaceIndents = score;
score = stats[1] ? 0.9 : 0.8;
if (!stats.length)
score = 0;
}
else
score /= spaceIndents;
if (changes[i])
score += changes[i] / changesTotal;
if (score > first.score)
first = {
score: score,
length: i
};
}
if (first.score && first.score > 1.4)
var tabLength = first.length;
if (tabIndents > spaceIndents + 1) {
if (tabLength == 1 || spaceIndents < tabIndents / 4 || first.score < 1.8)
tabLength = undefined;
return {
ch: "\t",
length: tabLength
};
}
if (spaceIndents > tabIndents + 1)
return {
ch: " ",
length: tabLength
};
};
exports.detectIndentation = function(session) {
var lines = session.getLines(0, 1000);
var indent = exports.$detectIndentation(lines) || {};
if (indent.ch)
session.setUseSoftTabs(indent.ch == " ");
if (indent.length)
session.setTabSize(indent.length);
return indent;
};
exports.trimTrailingSpace = function(session, options) {
var doc = session.getDocument();
var lines = doc.getAllLines();
var min = options && options.trimEmpty ? -1 : 0;
var cursors = [],
ci = -1;
if (options && options.keepCursorPosition) {
if (session.selection.rangeCount) {
session.selection.rangeList.ranges.forEach(function(x, i, ranges) {
var next = ranges[i + 1];
if (next && next.cursor.row == x.cursor.row)
return;
cursors.push(x.cursor);
});
}
else {
cursors.push(session.selection.getCursor());
}
ci = 0;
}
var cursorRow = cursors[ci] && cursors[ci].row;
for (var i = 0, l = lines.length; i < l; i++) {
var line = lines[i];
var index = line.search(/\s+$/);
if (i == cursorRow) {
if (index < cursors[ci].column && index > min)
index = cursors[ci].column;
ci++;
cursorRow = cursors[ci] ? cursors[ci].row : -1;
}
if (index > min)
doc.removeInLine(i, index, line.length);
}
};
exports.convertIndentation = function(session, ch, len) {
var oldCh = session.getTabString()[0];
var oldLen = session.getTabSize();
if (!len) len = oldLen;
if (!ch) ch = oldCh;
var tab = ch == "\t" ? ch : lang.stringRepeat(ch, len);
var doc = session.doc;
var lines = doc.getAllLines();
var cache = {};
var spaceCache = {};
for (var i = 0, l = lines.length; i < l; i++) {
var line = lines[i];
var match = line.match(/^\s*/)[0];
if (match) {
var w = session.$getStringScreenWidth(match)[0];
var tabCount = Math.floor(w / oldLen);
var reminder = w % oldLen;
var toInsert = cache[tabCount] || (cache[tabCount] = lang.stringRepeat(tab, tabCount));
toInsert += spaceCache[reminder] || (spaceCache[reminder] = lang.stringRepeat(" ", reminder));
if (toInsert != match) {
doc.removeInLine(i, 0, match.length);
doc.insertInLine({
row: i,
column: 0
}, toInsert);
}
}
}
session.setTabSize(len);
session.setUseSoftTabs(ch == " ");
};
exports.$parseStringArg = function(text) {
var indent = {};
if (/t/.test(text))
indent.ch = "\t";
else if (/s/.test(text))
indent.ch = " ";
var m = text.match(/\d+/);
if (m)
indent.length = parseInt(m[0], 10);
return indent;
};
exports.$parseArg = function(arg) {
if (!arg)
return {};
if (typeof arg == "string")
return exports.$parseStringArg(arg);
if (typeof arg.text == "string")
return exports.$parseStringArg(arg.text);
return arg;
};
exports.commands = [{
name: "detectIndentation",
description: "Detect indentation from content",
exec: function(editor) {
exports.detectIndentation(editor.session);
}
}, {
name: "trimTrailingSpace",
description: "Trim trailing whitespace",
exec: function(editor, args) {
exports.trimTrailingSpace(editor.session, args);
}
}, {
name: "convertIndentation",
description: "Convert indentation to ...",
exec: function(editor, arg) {
var indent = exports.$parseArg(arg);
exports.convertIndentation(editor.session, indent.ch, indent.length);
}
}, {
name: "setIndentation",
description: "Set indentation",
exec: function(editor, arg) {
var indent = exports.$parseArg(arg);
indent.length && editor.session.setTabSize(indent.length);
indent.ch && editor.session.setUseSoftTabs(indent.ch == " ");
}
}];
});
(function() {
ace.require(["ace/ext/whitespace"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})(); | {
"content_hash": "cf42df5a77f1bc4e19790c157c254786",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 119,
"avg_line_length": 27.27777777777778,
"alnum_prop": 0.5404981983393389,
"repo_name": "TeamSPoon/logicmoo_workspace",
"id": "6d9d965365c8b3dbeec55c95fec2f9d46f120f2e",
"size": "6383",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packs_web/swish/web/node_modules/ace/build/src-noconflict/ext-whitespace.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "342"
},
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "CSS",
"bytes": "126627"
},
{
"name": "HTML",
"bytes": "839172"
},
{
"name": "Java",
"bytes": "11116"
},
{
"name": "JavaScript",
"bytes": "238700"
},
{
"name": "PHP",
"bytes": "42253"
},
{
"name": "Perl 6",
"bytes": "23"
},
{
"name": "Prolog",
"bytes": "440882"
},
{
"name": "PureBasic",
"bytes": "1334"
},
{
"name": "Rich Text Format",
"bytes": "3436542"
},
{
"name": "Roff",
"bytes": "42"
},
{
"name": "Shell",
"bytes": "61603"
},
{
"name": "TeX",
"bytes": "99504"
}
],
"symlink_target": ""
} |
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: demo/demo_service.proto
/*
Package demo is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package demo
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var (
filter_HelloWorld_SendGet_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_HelloWorld_SendGet_0(ctx context.Context, marshaler runtime.Marshaler, client HelloWorldClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HelloRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_HelloWorld_SendGet_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.SendGet(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_HelloWorld_SendPost_0(ctx context.Context, marshaler runtime.Marshaler, client HelloWorldClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HelloRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.SendPost(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
// RegisterHelloWorldHandlerFromEndpoint is same as RegisterHelloWorldHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterHelloWorldHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterHelloWorldHandler(ctx, mux, conn)
}
// RegisterHelloWorldHandler registers the http handlers for service HelloWorld to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterHelloWorldHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterHelloWorldHandlerClient(ctx, mux, NewHelloWorldClient(conn))
}
// RegisterHelloWorldHandlerClient registers the http handlers for service HelloWorld
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "HelloWorldClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "HelloWorldClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "HelloWorldClient" to call the correct interceptors.
func RegisterHelloWorldHandlerClient(ctx context.Context, mux *runtime.ServeMux, client HelloWorldClient) error {
mux.Handle("GET", pattern_HelloWorld_SendGet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_HelloWorld_SendGet_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_HelloWorld_SendGet_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_HelloWorld_SendPost_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_HelloWorld_SendPost_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_HelloWorld_SendPost_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_HelloWorld_SendGet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"get"}, ""))
pattern_HelloWorld_SendPost_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"post"}, ""))
)
var (
forward_HelloWorld_SendGet_0 = runtime.ForwardResponseMessage
forward_HelloWorld_SendPost_0 = runtime.ForwardResponseMessage
)
| {
"content_hash": "a0e215a440a7e5635402be7c81341783",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 207,
"avg_line_length": 35.3,
"alnum_prop": 0.7253791034827529,
"repo_name": "niasand/how_to_go",
"id": "7b31a3e7c53c55db19c3873efed64c65586741d6",
"size": "6001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "playground/proto_demo/demo/demo_service.pb.gw.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "138830"
},
{
"name": "Groovy",
"bytes": "248"
},
{
"name": "HTML",
"bytes": "390"
},
{
"name": "Python",
"bytes": "4774"
},
{
"name": "Shell",
"bytes": "219"
}
],
"symlink_target": ""
} |
<a href='https://github.com/angular/angular.js/edit/v1.4.x/src/ng/directive/form.js?message=docs(ngForm)%3A%20describe%20your%20change...#L286' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.4.0-rc.0/src/ng/directive/form.js#L286' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">ngForm</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
- directive in module <a href="api/ng">ng</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>Nestable alias of <a href="api/ng/directive/form"><code>form</code></a> directive. HTML
does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
sub-group of controls needs to be determined.</p>
<p>Note: the purpose of <code>ngForm</code> is to group controls,
but not to be a replacement for the <code><form></code> tag with all of its capabilities
(e.g. posting to the server, ...).</p>
</div>
<div>
<h2>Directive Info</h2>
<ul>
<li>This directive executes at priority level 0.</li>
</ul>
<h2 id="usage">Usage</h2>
<div class="usage">
<ul>
<li>as element:
(This directive can be used as custom element, but be aware of <a href="guide/ie">IE restrictions</a>).
<pre><code><ng-form [name=""]> ... </ng-form></code></pre>
</li>
<li>as attribute:
<pre><code><ANY [ng-form=""]> ... </ANY></code></pre>
</li>
<li>as CSS class:
<pre><code><ANY class="[ng-form: ;]"> ... </ANY></code></pre>
</li>
</div>
<section class="api-section">
<h3>Arguments</h3>
<table class="variables-matrix input-arguments">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
ngForm
| name
<div><em>(optional)</em></div>
</td>
<td>
<a href="" class="label type-hint type-hint-string">string</a>
</td>
<td>
<p>Name of the form. If specified, the form controller will be published into
related scope, under this name.</p>
</td>
</tr>
</tbody>
</table>
</section>
</div>
| {
"content_hash": "df0456427851974fde872541a1872f93",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 247,
"avg_line_length": 24.75,
"alnum_prop": 0.5947940947940948,
"repo_name": "dolymood/angular-packages",
"id": "281ded35ca8f3e4450903481f8189dc1136e36b7",
"size": "2574",
"binary": false,
"copies": "3",
"ref": "refs/heads/gh-pages",
"path": "angular-1.4.0-rc.0/docs/partials/api/ng/directive/ngForm.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1454701"
},
{
"name": "HTML",
"bytes": "82151465"
},
{
"name": "JavaScript",
"bytes": "15628922"
}
],
"symlink_target": ""
} |
"""
Cass storage backend
"""
import pycassa
from matra.openstack.common import log
from matra.openstack.common import network_utils
from matra.storage import base
LOG = log.getLogger(__name__)
class CassStorage(base.StorageEngine):
'''
Put data into cassandra
'''
@staticmethod
def get_connection(conf):
'''
Return a connection instance based on configuration
'''
return Connection(conf)
class Connection(base.Connection):
'''
Cassandra connection
'''
# TODO (lakshmi): Fetch these from configs
CASS_KEYSPACE='DATA'
METRICS_FULL_CF='metrics_5m'
def __init__(self, conf):
# TODO (lakshmi): Support in memory connections for testing
opts = self._parse_connection_url(conf.database.connection)
self.conn_pool = self._get_connection_pool(opts)
def _get_connection_pool(conf):
return pycassa.ConnectionPool(CASS_KEYSPACE, server_list=':'.join([opts.host, str(opts.port)]))
@staticmethod
def _get_connection(conf):
'''
Return a connection to the database
'''
return self.conn_pool.get()
@staticmethod
def _parse_connection_url(url):
'''
Parse connection parameters from a database url.
'''
opts = {}
result = network_utils.urlsplit(url)
if ':' in result.netloc:
opts['host'], port = result.netloc.split(':')
else:
opts['host'] = result.netloc
port = 9160
opts['port'] = port and int(port) or 9160
return opts
def ingest_metrics(self, data):
pass
| {
"content_hash": "d4a97ba19db31cd105e02ebcf45d521d",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 103,
"avg_line_length": 23.768115942028984,
"alnum_prop": 0.6085365853658536,
"repo_name": "lakshmi-kannan/matra",
"id": "49293d7bbe67cd9edca8e923db4d58b3c370a50a",
"size": "2213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "matra/storage/impl_cass.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "535"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>File: model.rb</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
// ]]>
</script>
</head>
<body>
<div id="fileHeader">
<h1>model.rb</h1>
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Path:</strong></td>
<td>lib/authorize_me/model.rb
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Last Update:</strong></td>
<td>Fri Dec 10 15:51:35 -0500 2010</td>
</tr>
</table>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
<div id="requires-list">
<h3 class="section-bar">Required files</h3>
<div class="name-list">
active_support/core_ext
</div>
</div>
</div>
</div>
<!-- if includes -->
<div id="section">
<!-- if method_list -->
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html> | {
"content_hash": "d32e376aef39d34afb84b4202a08b869",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 102,
"avg_line_length": 20.175925925925927,
"alnum_prop": 0.5842129417163837,
"repo_name": "edgecase/authorize_me",
"id": "3274a77682804d76e21b311995e1a8396a0efa15",
"size": "2179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rdoc/files/lib/authorize_me/model_rb.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "9806"
}
],
"symlink_target": ""
} |
package sbahjsic.util;
/** Math utilities.*/
public final class MathUtils {
private MathUtils() {}
/** Calculates the int factorial of some number.
* @param n the number
* @return n!*/
public static int fact(int n) {
int result = 1;
for(int i = 1; i <= n; i++)
result *= i;
return result;
}
/** Calculates the long factorial of some number.
* @param n the number
* @return n!*/
public static long fact(long n) {
long result = 1;
for(long i = 1; i <= n; i++)
result *= i;
return result;
}
/** Returns whether a+b overflows.*/
public static boolean additionOverflows(int a, int b) {
int c = a + b;
return ((a ^ c) & (b ^ c)) < 0;
}
/** Returns whether a-b overflows.*/
public static boolean subtractionOverflows(int a, int b) {
int c = a - b;
return ((a ^ b) & (a ^ c)) < 0;
}
/** Returns whether ab overflows.*/
public static boolean multiplicationOverflows(int a, int b) {
int c = a * b;
return a != 0 && c/a != b;
}
/** Returns whether a+b overflows.*/
public static boolean additionOverflows(long a, long b) {
long c = a + b;
return ((a ^ c) & (b ^ c)) < 0;
}
/** Returns whether a-b overflows.*/
public static boolean subtractionOverflows(long a, long b) {
long c = a - b;
return ((a ^ b) & (a ^ c)) < 0;
}
/** Returns whether ab overflows.*/
public static boolean multiplicationOverflows(long a, long b) {
long c = a * b;
return a != 0 && c/a != b;
}
} | {
"content_hash": "b975beb31caf935271d30c9b13ec31a6",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 64,
"avg_line_length": 23.015873015873016,
"alnum_prop": 0.596551724137931,
"repo_name": "expositionrabbit/Sbahjsic-runtime",
"id": "252470d622149e2ceb41042a3aaf736c766dd7a5",
"size": "1450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sbahjsic/util/MathUtils.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1961"
},
{
"name": "Java",
"bytes": "459821"
}
],
"symlink_target": ""
} |
from __future__ import with_statement
import os.path
import time
import urllib
import re
import threading
import datetime
import random
import locale
from Cheetah.Template import Template
import cherrypy.lib
import sickbeard
from sickbeard import config, sab
from sickbeard import clients
from sickbeard import history, notifiers, processTV
from sickbeard import ui
from sickbeard import logger, helpers, exceptions, classes, db
from sickbeard import encodingKludge as ek
from sickbeard import search_queue
from sickbeard import image_cache
from sickbeard import scene_exceptions
from sickbeard import naming
from sickbeard import subtitles
from sickbeard.providers import newznab
from sickbeard.common import Quality, Overview, statusStrings
from sickbeard.common import SNATCHED, SKIPPED, UNAIRED, IGNORED, ARCHIVED, WANTED
from sickbeard.exceptions import ex
from sickbeard.webapi import Api
from lib.tvdb_api import tvdb_api
from lib.dateutil import tz
import network_timezones
import subliminal
try:
import json
except ImportError:
from lib import simplejson as json
try:
import xml.etree.cElementTree as etree
except ImportError:
import xml.etree.ElementTree as etree
from sickbeard import browser
class PageTemplate (Template):
def __init__(self, *args, **KWs):
KWs['file'] = os.path.join(sickbeard.PROG_DIR, "data/interfaces/default/", KWs['file'])
super(PageTemplate, self).__init__(*args, **KWs)
self.sbRoot = sickbeard.WEB_ROOT
self.sbHttpPort = sickbeard.WEB_PORT
self.sbHttpsPort = sickbeard.WEB_PORT
self.sbHttpsEnabled = sickbeard.ENABLE_HTTPS
if cherrypy.request.headers['Host'][0] == '[':
self.sbHost = re.match("^\[.*\]", cherrypy.request.headers['Host'], re.X|re.M|re.S).group(0)
else:
self.sbHost = re.match("^[^:]+", cherrypy.request.headers['Host'], re.X|re.M|re.S).group(0)
self.projectHomePage = "http://code.google.com/p/sickbeard/"
if sickbeard.NZBS and sickbeard.NZBS_UID and sickbeard.NZBS_HASH:
logger.log(u"NZBs.org has been replaced, please check the config to configure the new provider!", logger.ERROR)
ui.notifications.error("NZBs.org Config Update", "NZBs.org has a new site. Please <a href=\""+sickbeard.WEB_ROOT+"/config/providers\">update your config</a> with the api key from <a href=\"http://nzbs.org/login\">http://nzbs.org</a> and then disable the old NZBs.org provider.")
if "X-Forwarded-Host" in cherrypy.request.headers:
self.sbHost = cherrypy.request.headers['X-Forwarded-Host']
if "X-Forwarded-Port" in cherrypy.request.headers:
self.sbHttpPort = cherrypy.request.headers['X-Forwarded-Port']
self.sbHttpsPort = self.sbHttpPort
if "X-Forwarded-Proto" in cherrypy.request.headers:
self.sbHttpsEnabled = True if cherrypy.request.headers['X-Forwarded-Proto'] == 'https' else False
logPageTitle = 'Logs & Errors'
if len(classes.ErrorViewer.errors):
logPageTitle += ' ('+str(len(classes.ErrorViewer.errors))+')'
self.logPageTitle = logPageTitle
self.sbPID = str(sickbeard.PID)
self.menu = [
{ 'title': 'Home', 'key': 'home' },
{ 'title': 'Coming Episodes', 'key': 'comingEpisodes' },
{ 'title': 'History', 'key': 'history' },
{ 'title': 'Manage', 'key': 'manage' },
{ 'title': 'Config', 'key': 'config' },
{ 'title': logPageTitle, 'key': 'errorlogs' },
]
def redirect(abspath, *args, **KWs):
assert abspath[0] == '/'
raise cherrypy.HTTPRedirect(sickbeard.WEB_ROOT + abspath, *args, **KWs)
class TVDBWebUI:
def __init__(self, config, log=None):
self.config = config
self.log = log
def selectSeries(self, allSeries):
searchList = ",".join([x['id'] for x in allSeries])
showDirList = ""
for curShowDir in self.config['_showDir']:
showDirList += "showDir="+curShowDir+"&"
redirect("/home/addShows/addShow?" + showDirList + "seriesList=" + searchList)
def _munge(string):
return unicode(string).encode('utf-8', 'xmlcharrefreplace')
def _genericMessage(subject, message):
t = PageTemplate(file="genericMessage.tmpl")
t.submenu = HomeMenu()
t.subject = subject
t.message = message
return _munge(t)
def _getEpisode(show, season, episode):
if show == None or season == None or episode == None:
return "Invalid parameters"
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return "Show not in show list"
epObj = showObj.getEpisode(int(season), int(episode))
if epObj == None:
return "Episode couldn't be retrieved"
return epObj
ManageMenu = [
{ 'title': 'Backlog Overview', 'path': 'manage/backlogOverview' },
{ 'title': 'Manage Searches', 'path': 'manage/manageSearches' },
{ 'title': 'Episode Status Management', 'path': 'manage/episodeStatuses' },
{ 'title': 'Manage Missed Subtitles', 'path': 'manage/subtitleMissed' },
]
if sickbeard.USE_SUBTITLES:
ManageMenu.append({ 'title': 'Missed Subtitle Management', 'path': 'manage/subtitleMissed' })
class ManageSearches:
@cherrypy.expose
def index(self):
t = PageTemplate(file="manage_manageSearches.tmpl")
#t.backlogPI = sickbeard.backlogSearchScheduler.action.getProgressIndicator()
t.backlogPaused = sickbeard.searchQueueScheduler.action.is_backlog_paused() #@UndefinedVariable
t.backlogRunning = sickbeard.searchQueueScheduler.action.is_backlog_in_progress() #@UndefinedVariable
t.searchStatus = sickbeard.currentSearchScheduler.action.amActive #@UndefinedVariable
t.submenu = ManageMenu
return _munge(t)
@cherrypy.expose
def forceSearch(self):
# force it to run the next time it looks
result = sickbeard.currentSearchScheduler.forceRun()
if result:
logger.log(u"Search forced")
ui.notifications.message('Episode search started',
'Note: RSS feeds may not be updated if retrieved recently')
redirect("/manage/manageSearches")
@cherrypy.expose
def pauseBacklog(self, paused=None):
if paused == "1":
sickbeard.searchQueueScheduler.action.pause_backlog() #@UndefinedVariable
else:
sickbeard.searchQueueScheduler.action.unpause_backlog() #@UndefinedVariable
redirect("/manage/manageSearches")
@cherrypy.expose
def forceVersionCheck(self):
# force a check to see if there is a new version
result = sickbeard.versionCheckScheduler.action.check_for_new_version(force=True) #@UndefinedVariable
if result:
logger.log(u"Forcing version check")
redirect("/manage/manageSearches")
class Manage:
manageSearches = ManageSearches()
@cherrypy.expose
def index(self):
t = PageTemplate(file="manage.tmpl")
t.submenu = ManageMenu
return _munge(t)
@cherrypy.expose
def showEpisodeStatuses(self, tvdb_id, whichStatus):
myDB = db.DBConnection()
status_list = [int(whichStatus)]
if status_list[0] == SNATCHED:
status_list = Quality.SNATCHED + Quality.SNATCHED_PROPER + Quality.SNATCHED_FRENCH
cur_show_results = myDB.select("SELECT season, episode, name FROM tv_episodes WHERE showid = ? AND season != 0 AND status IN ("+','.join(['?']*len(status_list))+")", [int(tvdb_id)] + status_list)
result = {}
for cur_result in cur_show_results:
cur_season = int(cur_result["season"])
cur_episode = int(cur_result["episode"])
if cur_season not in result:
result[cur_season] = {}
result[cur_season][cur_episode] = cur_result["name"]
return json.dumps(result)
@cherrypy.expose
def episodeStatuses(self, whichStatus=None):
if whichStatus:
whichStatus = int(whichStatus)
status_list = [whichStatus]
if status_list[0] == SNATCHED:
status_list = Quality.SNATCHED + Quality.SNATCHED_PROPER + Quality.SNATCHED_FRENCH
else:
status_list = []
t = PageTemplate(file="manage_episodeStatuses.tmpl")
t.submenu = ManageMenu
t.whichStatus = whichStatus
# if we have no status then this is as far as we need to go
if not status_list:
return _munge(t)
myDB = db.DBConnection()
status_results = myDB.select("SELECT show_name, tv_shows.tvdb_id as tvdb_id FROM tv_episodes, tv_shows WHERE tv_episodes.status IN ("+','.join(['?']*len(status_list))+") AND season != 0 AND tv_episodes.showid = tv_shows.tvdb_id ORDER BY show_name", status_list)
ep_counts = {}
show_names = {}
sorted_show_ids = []
for cur_status_result in status_results:
cur_tvdb_id = int(cur_status_result["tvdb_id"])
if cur_tvdb_id not in ep_counts:
ep_counts[cur_tvdb_id] = 1
else:
ep_counts[cur_tvdb_id] += 1
show_names[cur_tvdb_id] = cur_status_result["show_name"]
if cur_tvdb_id not in sorted_show_ids:
sorted_show_ids.append(cur_tvdb_id)
t.show_names = show_names
t.ep_counts = ep_counts
t.sorted_show_ids = sorted_show_ids
return _munge(t)
@cherrypy.expose
def changeEpisodeStatuses(self, oldStatus, newStatus, *args, **kwargs):
status_list = [int(oldStatus)]
if status_list[0] == SNATCHED:
status_list = Quality.SNATCHED + Quality.SNATCHED_PROPER + Quality.SNATCHED_FRENCH
to_change = {}
# make a list of all shows and their associated args
for arg in kwargs:
tvdb_id, what = arg.split('-')
# we don't care about unchecked checkboxes
if kwargs[arg] != 'on':
continue
if tvdb_id not in to_change:
to_change[tvdb_id] = []
to_change[tvdb_id].append(what)
myDB = db.DBConnection()
for cur_tvdb_id in to_change:
# get a list of all the eps we want to change if they just said "all"
if 'all' in to_change[cur_tvdb_id]:
all_eps_results = myDB.select("SELECT season, episode FROM tv_episodes WHERE status IN ("+','.join(['?']*len(status_list))+") AND season != 0 AND showid = ?", status_list + [cur_tvdb_id])
all_eps = [str(x["season"])+'x'+str(x["episode"]) for x in all_eps_results]
to_change[cur_tvdb_id] = all_eps
Home().setStatus(cur_tvdb_id, '|'.join(to_change[cur_tvdb_id]), newStatus, direct=True)
redirect('/manage/episodeStatuses')
@cherrypy.expose
def showSubtitleMissed(self, tvdb_id, whichSubs):
myDB = db.DBConnection()
cur_show_results = myDB.select("SELECT season, episode, name, subtitles FROM tv_episodes WHERE showid = ? AND season != 0 AND status LIKE '%4'", [int(tvdb_id)])
result = {}
for cur_result in cur_show_results:
if whichSubs == 'all':
if len(set(cur_result["subtitles"].split(',')).intersection(set(subtitles.wantedLanguages()))) >= len(subtitles.wantedLanguages()):
continue
elif whichSubs in cur_result["subtitles"].split(','):
continue
cur_season = int(cur_result["season"])
cur_episode = int(cur_result["episode"])
if cur_season not in result:
result[cur_season] = {}
if cur_episode not in result[cur_season]:
result[cur_season][cur_episode] = {}
result[cur_season][cur_episode]["name"] = cur_result["name"]
result[cur_season][cur_episode]["subtitles"] = ",".join(subliminal.language.Language(subtitle).alpha2 for subtitle in cur_result["subtitles"].split(',')) if not cur_result["subtitles"] == '' else ''
return json.dumps(result)
@cherrypy.expose
def subtitleMissed(self, whichSubs=None):
t = PageTemplate(file="manage_subtitleMissed.tmpl")
t.submenu = ManageMenu
t.whichSubs = whichSubs
if not whichSubs:
return _munge(t)
myDB = db.DBConnection()
status_results = myDB.select("SELECT show_name, tv_shows.tvdb_id as tvdb_id, tv_episodes.subtitles subtitles FROM tv_episodes, tv_shows WHERE tv_shows.subtitles = 1 AND tv_episodes.status LIKE '%4' AND tv_episodes.season != 0 AND tv_episodes.showid = tv_shows.tvdb_id ORDER BY show_name")
ep_counts = {}
show_names = {}
sorted_show_ids = []
for cur_status_result in status_results:
if whichSubs == 'all':
if len(set(cur_status_result["subtitles"].split(',')).intersection(set(subtitles.wantedLanguages()))) >= len(subtitles.wantedLanguages()):
continue
elif whichSubs in cur_status_result["subtitles"].split(','):
continue
cur_tvdb_id = int(cur_status_result["tvdb_id"])
if cur_tvdb_id not in ep_counts:
ep_counts[cur_tvdb_id] = 1
else:
ep_counts[cur_tvdb_id] += 1
show_names[cur_tvdb_id] = cur_status_result["show_name"]
if cur_tvdb_id not in sorted_show_ids:
sorted_show_ids.append(cur_tvdb_id)
t.show_names = show_names
t.ep_counts = ep_counts
t.sorted_show_ids = sorted_show_ids
return _munge(t)
@cherrypy.expose
def downloadSubtitleMissed(self, *args, **kwargs):
to_download = {}
# make a list of all shows and their associated args
for arg in kwargs:
tvdb_id, what = arg.split('-')
# we don't care about unchecked checkboxes
if kwargs[arg] != 'on':
continue
if tvdb_id not in to_download:
to_download[tvdb_id] = []
to_download[tvdb_id].append(what)
for cur_tvdb_id in to_download:
# get a list of all the eps we want to download subtitles if they just said "all"
if 'all' in to_download[cur_tvdb_id]:
myDB = db.DBConnection()
all_eps_results = myDB.select("SELECT season, episode FROM tv_episodes WHERE status LIKE '%4' AND season != 0 AND showid = ?", [cur_tvdb_id])
to_download[cur_tvdb_id] = [str(x["season"])+'x'+str(x["episode"]) for x in all_eps_results]
for epResult in to_download[cur_tvdb_id]:
season, episode = epResult.split('x');
show = sickbeard.helpers.findCertainShow(sickbeard.showList, int(cur_tvdb_id))
subtitles = show.getEpisode(int(season), int(episode)).downloadSubtitles()
redirect('/manage/subtitleMissed')
@cherrypy.expose
def backlogShow(self, tvdb_id):
show_obj = helpers.findCertainShow(sickbeard.showList, int(tvdb_id))
if show_obj:
sickbeard.backlogSearchScheduler.action.searchBacklog([show_obj]) #@UndefinedVariable
redirect("/manage/backlogOverview")
@cherrypy.expose
def backlogOverview(self):
t = PageTemplate(file="manage_backlogOverview.tmpl")
t.submenu = ManageMenu
myDB = db.DBConnection()
showCounts = {}
showCats = {}
showSQLResults = {}
for curShow in sickbeard.showList:
epCounts = {}
epCats = {}
epCounts[Overview.SKIPPED] = 0
epCounts[Overview.WANTED] = 0
epCounts[Overview.QUAL] = 0
epCounts[Overview.GOOD] = 0
epCounts[Overview.UNAIRED] = 0
epCounts[Overview.SNATCHED] = 0
sqlResults = myDB.select("SELECT * FROM tv_episodes WHERE showid = ? ORDER BY season DESC, episode DESC", [curShow.tvdbid])
for curResult in sqlResults:
curEpCat = curShow.getOverview(int(curResult["status"]))
epCats[str(curResult["season"]) + "x" + str(curResult["episode"])] = curEpCat
epCounts[curEpCat] += 1
showCounts[curShow.tvdbid] = epCounts
showCats[curShow.tvdbid] = epCats
showSQLResults[curShow.tvdbid] = sqlResults
t.showCounts = showCounts
t.showCats = showCats
t.showSQLResults = showSQLResults
return _munge(t)
@cherrypy.expose
def massEdit(self, toEdit=None):
t = PageTemplate(file="manage_massEdit.tmpl")
t.submenu = ManageMenu
if not toEdit:
redirect("/manage")
showIDs = toEdit.split("|")
showList = []
for curID in showIDs:
curID = int(curID)
showObj = helpers.findCertainShow(sickbeard.showList, curID)
if showObj:
showList.append(showObj)
flatten_folders_all_same = True
last_flatten_folders = None
paused_all_same = True
last_paused = None
frenched_all_same = True
last_frenched = None
quality_all_same = True
last_quality = None
subtitles_all_same = True
last_subtitles = None
lang_all_same = True
last_lang_metadata= None
lang_audio_all_same = True
last_lang_audio = None
root_dir_list = []
for curShow in showList:
cur_root_dir = ek.ek(os.path.dirname, curShow._location)
if cur_root_dir not in root_dir_list:
root_dir_list.append(cur_root_dir)
# if we know they're not all the same then no point even bothering
if paused_all_same:
# if we had a value already and this value is different then they're not all the same
if last_paused not in (curShow.paused, None):
paused_all_same = False
else:
last_paused = curShow.paused
if frenched_all_same:
# if we had a value already and this value is different then they're not all the same
if last_frenched not in (curShow.frenchsearch, None):
frenched_all_same = False
else:
last_frenched = curShow.frenchsearch
if flatten_folders_all_same:
if last_flatten_folders not in (None, curShow.flatten_folders):
flatten_folders_all_same = False
else:
last_flatten_folders = curShow.flatten_folders
if quality_all_same:
if last_quality not in (None, curShow.quality):
quality_all_same = False
else:
last_quality = curShow.quality
if subtitles_all_same:
if last_subtitles not in (None, curShow.subtitles):
subtitles_all_same = False
else:
last_subtitles = curShow.subtitles
if lang_all_same:
if last_lang_metadata not in (None, curShow.lang):
lang_all_same = False
else:
last_lang_metadata = curShow.lang
if lang_audio_all_same:
if last_lang_audio not in (None, curShow.audio_lang):
lang_audio_all_same = False
else:
last_lang_audio = curShow.audio_lang
t.showList = toEdit
t.paused_value = last_paused if paused_all_same else None
t.frenched_value = last_frenched if frenched_all_same else None
t.flatten_folders_value = last_flatten_folders if flatten_folders_all_same else None
t.quality_value = last_quality if quality_all_same else None
t.subtitles_value = last_subtitles if subtitles_all_same else None
t.root_dir_list = root_dir_list
t.lang_value = last_lang_metadata if lang_all_same else None
t.audio_value = last_lang_audio if lang_audio_all_same else None
return _munge(t)
@cherrypy.expose
def massEditSubmit(self, paused=None, frenched=None, flatten_folders=None, quality_preset=False, subtitles=None,
anyQualities=[], bestQualities=[], tvdbLang=None, audioLang = None, toEdit=None, *args, **kwargs):
dir_map = {}
for cur_arg in kwargs:
if not cur_arg.startswith('orig_root_dir_'):
continue
which_index = cur_arg.replace('orig_root_dir_', '')
end_dir = kwargs['new_root_dir_'+which_index]
dir_map[kwargs[cur_arg]] = end_dir
showIDs = toEdit.split("|")
errors = []
for curShow in showIDs:
curErrors = []
showObj = helpers.findCertainShow(sickbeard.showList, int(curShow))
if not showObj:
continue
cur_root_dir = ek.ek(os.path.dirname, showObj._location)
cur_show_dir = ek.ek(os.path.basename, showObj._location)
if cur_root_dir in dir_map and cur_root_dir != dir_map[cur_root_dir]:
new_show_dir = ek.ek(os.path.join, dir_map[cur_root_dir], cur_show_dir)
logger.log(u"For show "+showObj.name+" changing dir from "+showObj._location+" to "+new_show_dir)
else:
new_show_dir = showObj._location
if paused == 'keep':
new_paused = showObj.paused
else:
new_paused = True if paused == 'enable' else False
new_paused = 'on' if new_paused else 'off'
if frenched == 'keep':
new_frenched = showObj.frenchsearch
else:
new_frenched = True if frenched == 'enable' else False
new_frenched = 'on' if new_frenched else 'off'
if flatten_folders == 'keep':
new_flatten_folders = showObj.flatten_folders
else:
new_flatten_folders = True if flatten_folders == 'enable' else False
new_flatten_folders = 'on' if new_flatten_folders else 'off'
if subtitles == 'keep':
new_subtitles = showObj.subtitles
else:
new_subtitles = True if subtitles == 'enable' else False
new_subtitles = 'on' if new_subtitles else 'off'
if quality_preset == 'keep':
anyQualities, bestQualities = Quality.splitQuality(showObj.quality)
if tvdbLang == 'None':
new_lang = 'en'
else:
new_lang = tvdbLang
if audioLang == 'keep':
new_audio_lang = showObj.audio_lang;
else:
new_audio_lang = audioLang
exceptions_list = []
curErrors += Home().editShow(curShow, new_show_dir, anyQualities, bestQualities, exceptions_list, new_flatten_folders, new_paused, new_frenched, subtitles=new_subtitles, tvdbLang=new_lang, audio_lang=new_audio_lang, directCall=True)
if curErrors:
logger.log(u"Errors: "+str(curErrors), logger.ERROR)
errors.append('<b>%s:</b>\n<ul>' % showObj.name + ' '.join(['<li>%s</li>' % error for error in curErrors]) + "</ul>")
if len(errors) > 0:
ui.notifications.error('%d error%s while saving changes:' % (len(errors), "" if len(errors) == 1 else "s"),
" ".join(errors))
redirect("/manage")
@cherrypy.expose
def massUpdate(self, toUpdate=None, toRefresh=None, toRename=None, toDelete=None, toMetadata=None, toSubtitle=None):
if toUpdate != None:
toUpdate = toUpdate.split('|')
else:
toUpdate = []
if toRefresh != None:
toRefresh = toRefresh.split('|')
else:
toRefresh = []
if toRename != None:
toRename = toRename.split('|')
else:
toRename = []
if toSubtitle != None:
toSubtitle = toSubtitle.split('|')
else:
toSubtitle = []
if toDelete != None:
toDelete = toDelete.split('|')
else:
toDelete = []
if toMetadata != None:
toMetadata = toMetadata.split('|')
else:
toMetadata = []
errors = []
refreshes = []
updates = []
renames = []
subtitles = []
for curShowID in set(toUpdate+toRefresh+toRename+toSubtitle+toDelete+toMetadata):
if curShowID == '':
continue
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(curShowID))
if showObj == None:
continue
if curShowID in toDelete:
showObj.deleteShow()
# don't do anything else if it's being deleted
continue
if curShowID in toUpdate:
try:
sickbeard.showQueueScheduler.action.updateShow(showObj, True) #@UndefinedVariable
updates.append(showObj.name)
except exceptions.CantUpdateException, e:
errors.append("Unable to update show "+showObj.name+": "+ex(e))
# don't bother refreshing shows that were updated anyway
if curShowID in toRefresh and curShowID not in toUpdate:
try:
sickbeard.showQueueScheduler.action.refreshShow(showObj) #@UndefinedVariable
refreshes.append(showObj.name)
except exceptions.CantRefreshException, e:
errors.append("Unable to refresh show "+showObj.name+": "+ex(e))
if curShowID in toRename:
sickbeard.showQueueScheduler.action.renameShowEpisodes(showObj) #@UndefinedVariable
renames.append(showObj.name)
if curShowID in toSubtitle:
sickbeard.showQueueScheduler.action.downloadSubtitles(showObj) #@UndefinedVariable
subtitles.append(showObj.name)
if len(errors) > 0:
ui.notifications.error("Errors encountered",
'<br >\n'.join(errors))
messageDetail = ""
if len(updates) > 0:
messageDetail += "<br /><b>Updates</b><br /><ul><li>"
messageDetail += "</li><li>".join(updates)
messageDetail += "</li></ul>"
if len(refreshes) > 0:
messageDetail += "<br /><b>Refreshes</b><br /><ul><li>"
messageDetail += "</li><li>".join(refreshes)
messageDetail += "</li></ul>"
if len(renames) > 0:
messageDetail += "<br /><b>Renames</b><br /><ul><li>"
messageDetail += "</li><li>".join(renames)
messageDetail += "</li></ul>"
if len(subtitles) > 0:
messageDetail += "<br /><b>Subtitles</b><br /><ul><li>"
messageDetail += "</li><li>".join(subtitles)
messageDetail += "</li></ul>"
if len(updates+refreshes+renames+subtitles) > 0:
ui.notifications.message("The following actions were queued:",
messageDetail)
redirect("/manage")
class History:
@cherrypy.expose
def index(self, limit=100):
myDB = db.DBConnection()
# sqlResults = myDB.select("SELECT h.*, show_name, name FROM history h, tv_shows s, tv_episodes e WHERE h.showid=s.tvdb_id AND h.showid=e.showid AND h.season=e.season AND h.episode=e.episode ORDER BY date DESC LIMIT "+str(numPerPage*(p-1))+", "+str(numPerPage))
if limit == "0":
sqlResults = myDB.select("SELECT h.*, show_name FROM history h, tv_shows s WHERE h.showid=s.tvdb_id ORDER BY date DESC")
else:
sqlResults = myDB.select("SELECT h.*, show_name FROM history h, tv_shows s WHERE h.showid=s.tvdb_id ORDER BY date DESC LIMIT ?", [limit])
t = PageTemplate(file="history.tmpl")
t.historyResults = sqlResults
t.limit = limit
t.submenu = [
{ 'title': 'Clear History', 'path': 'history/clearHistory' },
{ 'title': 'Trim History', 'path': 'history/trimHistory' },
{ 'title': 'Trunc Episode Links', 'path': 'history/truncEplinks' },
{ 'title': 'Trunc Episode List Processed', 'path': 'history/truncEpListProc' },
]
return _munge(t)
@cherrypy.expose
def clearHistory(self):
myDB = db.DBConnection()
myDB.action("DELETE FROM history WHERE 1=1")
ui.notifications.message('History cleared')
redirect("/history")
@cherrypy.expose
def trimHistory(self):
myDB = db.DBConnection()
myDB.action("DELETE FROM history WHERE date < "+str((datetime.datetime.today()-datetime.timedelta(days=30)).strftime(history.dateFormat)))
ui.notifications.message('Removed history entries greater than 30 days old')
redirect("/history")
@cherrypy.expose
def truncEplinks(self):
myDB = db.DBConnection()
nbep=myDB.select("SELECT count(*) from episode_links")
myDB.action("DELETE FROM episode_links WHERE 1=1")
messnum = str(nbep[0][0]) + ' history links deleted'
ui.notifications.message('All Episode Links Removed', messnum)
redirect("/history")
@cherrypy.expose
def truncEpListProc(self):
myDB = db.DBConnection()
nbep=myDB.select("SELECT count(*) from processed_files")
myDB.action("DELETE FROM processed_files WHERE 1=1")
messnum = str(nbep[0][0]) + ' record for file processed delete'
ui.notifications.message('Clear list of file processed', messnum)
redirect("/history")
ConfigMenu = [
{ 'title': 'General', 'path': 'config/general/' },
{ 'title': 'Search Settings', 'path': 'config/search/' },
{ 'title': 'Search Providers', 'path': 'config/providers/' },
{ 'title': 'Subtitles Settings','path': 'config/subtitles/' },
{ 'title': 'Post Processing', 'path': 'config/postProcessing/' },
{ 'title': 'Notifications', 'path': 'config/notifications/' },
]
class ConfigGeneral:
@cherrypy.expose
def index(self):
t = PageTemplate(file="config_general.tmpl")
t.submenu = ConfigMenu
return _munge(t)
@cherrypy.expose
def saveRootDirs(self, rootDirString=None):
sickbeard.ROOT_DIRS = rootDirString
sickbeard.save_config()
@cherrypy.expose
def saveAddShowDefaults(self, defaultFlattenFolders, defaultStatus, anyQualities, bestQualities, audio_lang, subtitles=None):
if anyQualities:
anyQualities = anyQualities.split(',')
else:
anyQualities = []
if bestQualities:
bestQualities = bestQualities.split(',')
else:
bestQualities = []
newQuality = Quality.combineQualities(map(int, anyQualities), map(int, bestQualities))
sickbeard.STATUS_DEFAULT = int(defaultStatus)
sickbeard.QUALITY_DEFAULT = int(newQuality)
sickbeard.AUDIO_SHOW_DEFAULT = str(audio_lang)
if defaultFlattenFolders == "true":
defaultFlattenFolders = 1
else:
defaultFlattenFolders = 0
sickbeard.FLATTEN_FOLDERS_DEFAULT = int(defaultFlattenFolders)
if subtitles == "true":
subtitles = 1
else:
subtitles = 0
sickbeard.SUBTITLES_DEFAULT = int(subtitles)
sickbeard.save_config()
@cherrypy.expose
def generateKey(self):
""" Return a new randomized API_KEY
"""
try:
from hashlib import md5
except ImportError:
from md5 import md5
# Create some values to seed md5
t = str(time.time())
r = str(random.random())
# Create the md5 instance and give it the current time
m = md5(t)
# Update the md5 instance with the random variable
m.update(r)
# Return a hex digest of the md5, eg 49f68a5c8493ec2c0bf489821c21fc3b
logger.log(u"New API generated")
return m.hexdigest()
@cherrypy.expose
def saveGeneral(self, log_dir=None, web_port=None, web_log=None, web_ipv6=None,
update_shows_on_start=None,launch_browser=None, web_username=None, use_api=None, api_key=None,
web_password=None, version_notify=None, enable_https=None, https_cert=None, https_key=None, sort_article=None, french_column=None):
results = []
if web_ipv6 == "on":
web_ipv6 = 1
else:
web_ipv6 = 0
if web_log == "on":
web_log = 1
else:
web_log = 0
if launch_browser == "on":
launch_browser = 1
else:
launch_browser = 0
if update_shows_on_start == "on":
update_shows_on_start = 1
else:
update_shows_on_start = 0
if sort_article == "on":
sort_article = 1
else:
sort_article = 0
if french_column == "on":
french_column = 1
else:
french_column= 0
if version_notify == "on":
version_notify = 1
else:
version_notify = 0
if not config.change_LOG_DIR(log_dir):
results += ["Unable to create directory " + os.path.normpath(log_dir) + ", log dir not changed."]
sickbeard.UPDATE_SHOWS_ON_START = update_shows_on_start
sickbeard.LAUNCH_BROWSER = launch_browser
sickbeard.SORT_ARTICLE = sort_article
sickbeard.FRENCH_COLUMN = french_column
sickbeard.WEB_PORT = int(web_port)
sickbeard.WEB_IPV6 = web_ipv6
sickbeard.WEB_LOG = web_log
sickbeard.WEB_USERNAME = web_username
sickbeard.WEB_PASSWORD = web_password
if use_api == "on":
use_api = 1
else:
use_api = 0
sickbeard.USE_API = use_api
sickbeard.API_KEY = api_key
if enable_https == "on":
enable_https = 1
else:
enable_https = 0
sickbeard.ENABLE_HTTPS = enable_https
if not config.change_HTTPS_CERT(https_cert):
results += ["Unable to create directory " + os.path.normpath(https_cert) + ", https cert dir not changed."]
if not config.change_HTTPS_KEY(https_key):
results += ["Unable to create directory " + os.path.normpath(https_key) + ", https key dir not changed."]
config.change_VERSION_NOTIFY(version_notify)
sickbeard.save_config()
if len(results) > 0:
for x in results:
logger.log(x, logger.ERROR)
ui.notifications.error('Error(s) Saving Configuration',
'<br />\n'.join(results))
else:
ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) )
redirect("/config/general/")
class ConfigSearch:
@cherrypy.expose
def index(self):
t = PageTemplate(file="config_search.tmpl")
t.submenu = ConfigMenu
return _munge(t)
@cherrypy.expose
def saveSearch(self, use_nzbs=None, use_torrents=None, nzb_dir=None, sab_username=None, sab_password=None,
sab_apikey=None, sab_category=None, sab_host=None, nzbget_password=None, nzbget_category=None, nzbget_host=None,
torrent_dir=None,torrent_method=None, nzb_method=None, usenet_retention=None, search_frequency=None, french_delay=None,
download_propers=None, download_french=None, torrent_username=None, torrent_password=None, torrent_host=None,
torrent_label=None, torrent_path=None, torrent_custom_url=None, torrent_ratio=None, torrent_paused=None, ignore_words=None,
prefered_method=None, torrent_use_ftp = None, ftp_host=None, ftp_port=None, ftp_timeout=None, ftp_passive = None, ftp_login=None,
ftp_password=None, ftp_remotedir=None):
results = []
if not config.change_NZB_DIR(nzb_dir):
results += ["Unable to create directory " + os.path.normpath(nzb_dir) + ", dir not changed."]
if not config.change_TORRENT_DIR(torrent_dir):
results += ["Unable to create directory " + os.path.normpath(torrent_dir) + ", dir not changed."]
config.change_SEARCH_FREQUENCY(search_frequency)
if download_propers == "on":
download_propers = 1
else:
download_propers = 0
if download_french == "on":
download_french = 1
else:
download_french = 0
if use_nzbs == "on":
use_nzbs = 1
else:
use_nzbs = 0
if use_torrents == "on":
use_torrents = 1
else:
use_torrents = 0
if usenet_retention == None:
usenet_retention = 200
if french_delay == None:
french_delay = 120
if ignore_words == None:
ignore_words = ""
if ftp_port == None:
ftp_port = 21
if ftp_timeout == None:
ftp_timeout = 120
sickbeard.USE_NZBS = use_nzbs
sickbeard.USE_TORRENTS = use_torrents
sickbeard.NZB_METHOD = nzb_method
sickbeard.PREFERED_METHOD = prefered_method
sickbeard.TORRENT_METHOD = torrent_method
sickbeard.USENET_RETENTION = int(usenet_retention)
sickbeard.FRENCH_DELAY = int(french_delay)
sickbeard.IGNORE_WORDS = ignore_words
sickbeard.DOWNLOAD_PROPERS = download_propers
sickbeard.DOWNLOAD_FRENCH = download_french
sickbeard.SAB_USERNAME = sab_username
sickbeard.SAB_PASSWORD = sab_password
sickbeard.SAB_APIKEY = sab_apikey.strip()
sickbeard.SAB_CATEGORY = sab_category
if sab_host and not re.match('https?://.*', sab_host):
sab_host = 'http://' + sab_host
if not sab_host.endswith('/'):
sab_host = sab_host + '/'
sickbeard.SAB_HOST = sab_host
sickbeard.NZBGET_PASSWORD = nzbget_password
sickbeard.NZBGET_CATEGORY = nzbget_category
sickbeard.NZBGET_HOST = nzbget_host
sickbeard.TORRENT_USERNAME = torrent_username
sickbeard.TORRENT_PASSWORD = torrent_password
sickbeard.TORRENT_LABEL = torrent_label
sickbeard.TORRENT_PATH = torrent_path
if torrent_custom_url == "on":
torrent_custom_url = 1
else:
torrent_custom_url = 0
sickbeard.TORRENT_CUSTOM_URL = torrent_custom_url
sickbeard.TORRENT_RATIO = torrent_ratio
if torrent_paused == "on":
torrent_paused = 1
else:
torrent_paused = 0
sickbeard.TORRENT_PAUSED = torrent_paused
if torrent_host and not re.match('https?://.*', torrent_host):
torrent_host = 'http://' + torrent_host
if not torrent_host.endswith('/'):
torrent_host = torrent_host + '/'
sickbeard.TORRENT_HOST = torrent_host
if torrent_use_ftp == "on":
torrent_use_ftp = 1
else:
torrent_use_ftp = 0
sickbeard.USE_TORRENT_FTP = torrent_use_ftp
sickbeard.FTP_HOST = ftp_host
sickbeard.FTP_PORT = ftp_port
sickbeard.FTP_TIMEOUT = ftp_timeout
if ftp_passive == "on":
ftp_passive = 1
else:
ftp_passive = 0
sickbeard.FTP_PASSIVE = ftp_passive
sickbeard.FTP_LOGIN = ftp_login
sickbeard.FTP_PASSWORD = ftp_password
sickbeard.FTP_DIR = ftp_remotedir
sickbeard.save_config()
if len(results) > 0:
for x in results:
logger.log(x, logger.ERROR)
ui.notifications.error('Error(s) Saving Configuration',
'<br />\n'.join(results))
else:
ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) )
redirect("/config/search/")
class ConfigPostProcessing:
@cherrypy.expose
def index(self):
t = PageTemplate(file="config_postProcessing.tmpl")
t.submenu = ConfigMenu
return _munge(t)
@cherrypy.expose
def savePostProcessing(self, naming_pattern=None, naming_multi_ep=None,
xbmc_data=None, xbmc__frodo__data=None, mediabrowser_data=None, synology_data=None, sony_ps3_data=None, wdtv_data=None, tivo_data=None,
use_banner=None, keep_processed_dir=None, process_method=None, process_automatically=None, process_automatically_torrent=None, rename_episodes=None,
move_associated_files=None, tv_download_dir=None, torrent_download_dir=None, naming_custom_abd=None, naming_abd_pattern=None):
results = []
if not config.change_TV_DOWNLOAD_DIR(tv_download_dir):
results += ["Unable to create directory " + os.path.normpath(tv_download_dir) + ", dir not changed."]
if not config.change_TORRENT_DOWNLOAD_DIR(torrent_download_dir):
results += ["Unable to create directory " + os.path.normpath(torrent_download_dir) + ", dir not changed."]
if use_banner == "on":
use_banner = 1
else:
use_banner = 0
if process_automatically == "on":
process_automatically = 1
else:
process_automatically = 0
if process_automatically_torrent == "on":
process_automatically_torrent = 1
else:
process_automatically_torrent = 0
if rename_episodes == "on":
rename_episodes = 1
else:
rename_episodes = 0
if keep_processed_dir == "on":
keep_processed_dir = 1
else:
keep_processed_dir = 0
if move_associated_files == "on":
move_associated_files = 1
else:
move_associated_files = 0
if naming_custom_abd == "on":
naming_custom_abd = 1
else:
naming_custom_abd = 0
sickbeard.PROCESS_AUTOMATICALLY = process_automatically
sickbeard.PROCESS_AUTOMATICALLY_TORRENT = process_automatically_torrent
sickbeard.KEEP_PROCESSED_DIR = keep_processed_dir
sickbeard.PROCESS_METHOD = process_method
sickbeard.RENAME_EPISODES = rename_episodes
sickbeard.MOVE_ASSOCIATED_FILES = move_associated_files
sickbeard.NAMING_CUSTOM_ABD = naming_custom_abd
sickbeard.metadata_provider_dict['XBMC'].set_config(xbmc_data)
sickbeard.metadata_provider_dict['XBMC (Frodo)'].set_config(xbmc__frodo__data)
sickbeard.metadata_provider_dict['MediaBrowser'].set_config(mediabrowser_data)
sickbeard.metadata_provider_dict['Synology'].set_config(synology_data)
sickbeard.metadata_provider_dict['Sony PS3'].set_config(sony_ps3_data)
sickbeard.metadata_provider_dict['WDTV'].set_config(wdtv_data)
sickbeard.metadata_provider_dict['TIVO'].set_config(tivo_data)
if self.isNamingValid(naming_pattern, naming_multi_ep) != "invalid":
sickbeard.NAMING_PATTERN = naming_pattern
sickbeard.NAMING_MULTI_EP = int(naming_multi_ep)
sickbeard.NAMING_FORCE_FOLDERS = naming.check_force_season_folders()
else:
results.append("You tried saving an invalid naming config, not saving your naming settings")
if self.isNamingValid(naming_abd_pattern, None, True) != "invalid":
sickbeard.NAMING_ABD_PATTERN = naming_abd_pattern
elif naming_custom_abd:
results.append("You tried saving an invalid air-by-date naming config, not saving your air-by-date settings")
sickbeard.USE_BANNER = use_banner
sickbeard.save_config()
if len(results) > 0:
for x in results:
logger.log(x, logger.ERROR)
ui.notifications.error('Error(s) Saving Configuration',
'<br />\n'.join(results))
else:
ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) )
redirect("/config/postProcessing/")
@cherrypy.expose
def testNaming(self, pattern=None, multi=None, abd=False):
if multi != None:
multi = int(multi)
result = naming.test_name(pattern, multi, abd)
result = ek.ek(os.path.join, result['dir'], result['name'])
return result
@cherrypy.expose
def isNamingValid(self, pattern=None, multi=None, abd=False):
if pattern == None:
return "invalid"
# air by date shows just need one check, we don't need to worry about season folders
if abd:
is_valid = naming.check_valid_abd_naming(pattern)
require_season_folders = False
else:
# check validity of single and multi ep cases for the whole path
is_valid = naming.check_valid_naming(pattern, multi)
# check validity of single and multi ep cases for only the file name
require_season_folders = naming.check_force_season_folders(pattern, multi)
if is_valid and not require_season_folders:
return "valid"
elif is_valid and require_season_folders:
return "seasonfolders"
else:
return "invalid"
class ConfigProviders:
@cherrypy.expose
def index(self):
t = PageTemplate(file="config_providers.tmpl")
t.submenu = ConfigMenu
return _munge(t)
@cherrypy.expose
def canAddNewznabProvider(self, name):
if not name:
return json.dumps({'error': 'Invalid name specified'})
providerDict = dict(zip([x.getID() for x in sickbeard.newznabProviderList], sickbeard.newznabProviderList))
tempProvider = newznab.NewznabProvider(name, '')
if tempProvider.getID() in providerDict:
return json.dumps({'error': 'Exists as '+providerDict[tempProvider.getID()].name})
else:
return json.dumps({'success': tempProvider.getID()})
@cherrypy.expose
def saveNewznabProvider(self, name, url, key=''):
if not name or not url:
return '0'
if not url.endswith('/'):
url = url + '/'
providerDict = dict(zip([x.name for x in sickbeard.newznabProviderList], sickbeard.newznabProviderList))
if name in providerDict:
if not providerDict[name].default:
providerDict[name].name = name
providerDict[name].url = url
providerDict[name].key = key
return providerDict[name].getID() + '|' + providerDict[name].configStr()
else:
newProvider = newznab.NewznabProvider(name, url, key)
sickbeard.newznabProviderList.append(newProvider)
return newProvider.getID() + '|' + newProvider.configStr()
@cherrypy.expose
def deleteNewznabProvider(self, id):
providerDict = dict(zip([x.getID() for x in sickbeard.newznabProviderList], sickbeard.newznabProviderList))
if id not in providerDict or providerDict[id].default:
return '0'
# delete it from the list
sickbeard.newznabProviderList.remove(providerDict[id])
if id in sickbeard.PROVIDER_ORDER:
sickbeard.PROVIDER_ORDER.remove(id)
return '1'
@cherrypy.expose
def saveProviders(self, nzbmatrix_username=None, nzbmatrix_apikey=None,
nzbs_r_us_uid=None, nzbs_r_us_hash=None, newznab_string='',
omgwtfnzbs_uid=None, omgwtfnzbs_key=None,
tvtorrents_digest=None, tvtorrents_hash=None,
torrentleech_key=None,
btn_api_key=None,
newzbin_username=None, newzbin_password=None,t411_username=None,t411_password=None,ftdb_username=None,ftdb_password=None,addict_username=None,addict_password=None,fnt_username=None,fnt_password=None,libertalia_username=None,libertalia_password=None,xthor_username=None,xthor_password=None,thinkgeek_username=None,thinkgeek_password=None,
ethor_key=None,
provider_order=None):
results = []
provider_str_list = provider_order.split()
provider_list = []
newznabProviderDict = dict(zip([x.getID() for x in sickbeard.newznabProviderList], sickbeard.newznabProviderList))
finishedNames = []
# add all the newznab info we got into our list
for curNewznabProviderStr in newznab_string.split('!!!'):
if not curNewznabProviderStr:
continue
curName, curURL, curKey = curNewznabProviderStr.split('|')
newProvider = newznab.NewznabProvider(curName, curURL, curKey)
curID = newProvider.getID()
# if it already exists then update it
if curID in newznabProviderDict:
newznabProviderDict[curID].name = curName
newznabProviderDict[curID].url = curURL
newznabProviderDict[curID].key = curKey
else:
sickbeard.newznabProviderList.append(newProvider)
finishedNames.append(curID)
# delete anything that is missing
for curProvider in sickbeard.newznabProviderList:
if curProvider.getID() not in finishedNames:
sickbeard.newznabProviderList.remove(curProvider)
# do the enable/disable
for curProviderStr in provider_str_list:
curProvider, curEnabled = curProviderStr.split(':')
curEnabled = int(curEnabled)
provider_list.append(curProvider)
if curProvider == 'nzbs_r_us':
sickbeard.NZBSRUS = curEnabled
elif curProvider == 'nzbs_org_old':
sickbeard.NZBS = curEnabled
elif curProvider == 'nzbmatrix':
sickbeard.NZBMATRIX = curEnabled
elif curProvider == 'newzbin':
sickbeard.NEWZBIN = curEnabled
elif curProvider == 'bin_req':
sickbeard.BINREQ = curEnabled
elif curProvider == 'womble_s_index':
sickbeard.WOMBLE = curEnabled
elif curProvider == 'nzbx':
sickbeard.NZBX = curEnabled
elif curProvider == 'omgwtfnzbs':
sickbeard.OMGWTFNZBS = curEnabled
elif curProvider == 'ezrss':
sickbeard.EZRSS = curEnabled
elif curProvider == 'tvtorrents':
sickbeard.TVTORRENTS = curEnabled
elif curProvider == 'torrentleech':
sickbeard.TORRENTLEECH = curEnabled
elif curProvider == 'btn':
sickbeard.BTN = curEnabled
elif curProvider == 'binnewz':
sickbeard.BINNEWZ = curEnabled
elif curProvider == 't411':
sickbeard.T411 = curEnabled
elif curProvider == 'ftdb':
sickbeard.FTDB = curEnabled
elif curProvider == 'addict':
sickbeard.ADDICT = curEnabled
elif curProvider == 'fnt':
sickbeard.FNT = curEnabled
elif curProvider == 'libertalia':
sickbeard.LIBERTALIA = curEnabled
elif curProvider == 'xthor':
sickbeard.XTHOR = curEnabled
elif curProvider == 'thinkgeek':
sickbeard.THINKGEEK = curEnabled
elif curProvider == 'cpasbien':
sickbeard.Cpasbien = curEnabled
elif curProvider == 'kat':
sickbeard.kat = curEnabled
elif curProvider == 'piratebay':
sickbeard.THEPIRATEBAY = curEnabled
elif curProvider == 'ethor':
sickbeard.ETHOR = curEnabled
elif curProvider in newznabProviderDict:
newznabProviderDict[curProvider].enabled = bool(curEnabled)
else:
logger.log(u"don't know what " + curProvider + " is, skipping")
sickbeard.TVTORRENTS_DIGEST = tvtorrents_digest.strip()
sickbeard.TVTORRENTS_HASH = tvtorrents_hash.strip()
sickbeard.TORRENTLEECH_KEY = torrentleech_key.strip()
sickbeard.ETHOR_KEY = ethor_key.strip()
sickbeard.BTN_API_KEY = btn_api_key.strip()
sickbeard.T411_USERNAME = t411_username
sickbeard.T411_PASSWORD = t411_password
sickbeard.FTDB_USERNAME = ftdb_username
sickbeard.FTDB_PASSWORD = ftdb_password
sickbeard.ADDICT_USERNAME = addict_username
sickbeard.ADDICT_PASSWORD = addict_password
sickbeard.FNT_USERNAME = fnt_username
sickbeard.FNT_PASSWORD = fnt_password
sickbeard.LIBERTALIA_USERNAME = libertalia_username
sickbeard.LIBERTALIA_PASSWORD = libertalia_password
sickbeard.XTHOR_USERNAME = xthor_username
sickbeard.XTHOR_PASSWORD = xthor_password
sickbeard.THINKGEEK_USERNAME = thinkgeek_username
sickbeard.THINKGEEK_PASSWORD = thinkgeek_password
sickbeard.NZBSRUS_UID = nzbs_r_us_uid.strip()
sickbeard.NZBSRUS_HASH = nzbs_r_us_hash.strip()
sickbeard.OMGWTFNZBS_UID = omgwtfnzbs_uid.strip()
sickbeard.OMGWTFNZBS_KEY = omgwtfnzbs_key.strip()
sickbeard.PROVIDER_ORDER = provider_list
sickbeard.save_config()
if len(results) > 0:
for x in results:
logger.log(x, logger.ERROR)
ui.notifications.error('Error(s) Saving Configuration',
'<br />\n'.join(results))
else:
ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) )
redirect("/config/providers/")
class ConfigNotifications:
@cherrypy.expose
def index(self):
t = PageTemplate(file="config_notifications.tmpl")
t.submenu = ConfigMenu
return _munge(t)
@cherrypy.expose
def saveNotifications(self, use_xbmc=None, xbmc_notify_onsnatch=None, xbmc_notify_ondownload=None, xbmc_update_onlyfirst=None, xbmc_notify_onsubtitledownload=None,
xbmc_update_library=None, xbmc_update_full=None, xbmc_host=None, xbmc_username=None, xbmc_password=None,
use_plex=None, plex_notify_onsnatch=None, plex_notify_ondownload=None, plex_notify_onsubtitledownload=None, plex_update_library=None,
plex_server_host=None, plex_host=None, plex_username=None, plex_password=None,
use_growl=None, growl_notify_onsnatch=None, growl_notify_ondownload=None, growl_notify_onsubtitledownload=None, growl_host=None, growl_password=None,
use_prowl=None, prowl_notify_onsnatch=None, prowl_notify_ondownload=None, prowl_notify_onsubtitledownload=None, prowl_api=None, prowl_priority=0,
use_twitter=None, twitter_notify_onsnatch=None, twitter_notify_ondownload=None, twitter_notify_onsubtitledownload=None,
use_boxcar=None, boxcar_notify_onsnatch=None, boxcar_notify_ondownload=None, boxcar_notify_onsubtitledownload=None, boxcar_username=None,
use_boxcar2=None, boxcar2_notify_onsnatch=None, boxcar2_notify_ondownload=None, boxcar2_notify_onsubtitledownload=None, boxcar2_access_token=None, boxcar2_sound=None,
use_pushover=None, pushover_notify_onsnatch=None, pushover_notify_ondownload=None, pushover_notify_onsubtitledownload=None, pushover_userkey=None, pushover_prio=None,
use_libnotify=None, libnotify_notify_onsnatch=None, libnotify_notify_ondownload=None, libnotify_notify_onsubtitledownload=None,
use_nmj=None, nmj_host=None, nmj_database=None, nmj_mount=None, use_synoindex=None,
use_nmjv2=None, nmjv2_host=None, nmjv2_dbloc=None, nmjv2_database=None,
use_trakt=None, trakt_username=None, trakt_password=None, trakt_api=None,trakt_remove_watchlist=None,trakt_use_watchlist=None,trakt_start_paused=None,trakt_method_add=None,
use_betaseries=None, betaseries_username=None, betaseries_password=None,
use_synologynotifier=None, synologynotifier_notify_onsnatch=None, synologynotifier_notify_ondownload=None, synologynotifier_notify_onsubtitledownload=None,
use_pytivo=None, pytivo_notify_onsnatch=None, pytivo_notify_ondownload=None, pytivo_notify_onsubtitledownload=None, pytivo_update_library=None,
pytivo_host=None, pytivo_share_name=None, pytivo_tivo_name=None,
use_nma=None, nma_notify_onsnatch=None, nma_notify_ondownload=None, nma_notify_onsubtitledownload=None, nma_api=None, nma_priority=0,
use_pushalot=None, pushalot_notify_onsnatch=None, pushalot_notify_ondownload=None, pushalot_notify_onsubtitledownload=None, pushalot_authorizationtoken=None,
use_pushbullet=None, pushbullet_notify_onsnatch=None, pushbullet_notify_ondownload=None, pushbullet_notify_onsubtitledownload=None, pushbullet_api=None, pushbullet_device=None, pushbullet_device_list=None, pushbullet_channel_list=None,
use_mail=None, mail_username=None, mail_password=None, mail_server=None, mail_ssl=None, mail_from=None, mail_to=None, mail_notify_onsnatch=None ):
results = []
if xbmc_notify_onsnatch == "on":
xbmc_notify_onsnatch = 1
else:
xbmc_notify_onsnatch = 0
if xbmc_notify_ondownload == "on":
xbmc_notify_ondownload = 1
else:
xbmc_notify_ondownload = 0
if xbmc_notify_onsubtitledownload == "on":
xbmc_notify_onsubtitledownload = 1
else:
xbmc_notify_onsubtitledownload = 0
if xbmc_update_library == "on":
xbmc_update_library = 1
else:
xbmc_update_library = 0
if xbmc_update_full == "on":
xbmc_update_full = 1
else:
xbmc_update_full = 0
if xbmc_update_onlyfirst == "on":
xbmc_update_onlyfirst = 1
else:
xbmc_update_onlyfirst = 0
if use_xbmc == "on":
use_xbmc = 1
else:
use_xbmc = 0
if plex_update_library == "on":
plex_update_library = 1
else:
plex_update_library = 0
if plex_notify_onsnatch == "on":
plex_notify_onsnatch = 1
else:
plex_notify_onsnatch = 0
if plex_notify_ondownload == "on":
plex_notify_ondownload = 1
else:
plex_notify_ondownload = 0
if plex_notify_onsubtitledownload == "on":
plex_notify_onsubtitledownload = 1
else:
plex_notify_onsubtitledownload = 0
if use_plex == "on":
use_plex = 1
else:
use_plex = 0
if growl_notify_onsnatch == "on":
growl_notify_onsnatch = 1
else:
growl_notify_onsnatch = 0
if growl_notify_ondownload == "on":
growl_notify_ondownload = 1
else:
growl_notify_ondownload = 0
if growl_notify_onsubtitledownload == "on":
growl_notify_onsubtitledownload = 1
else:
growl_notify_onsubtitledownload = 0
if use_growl == "on":
use_growl = 1
else:
use_growl = 0
if prowl_notify_onsnatch == "on":
prowl_notify_onsnatch = 1
else:
prowl_notify_onsnatch = 0
if prowl_notify_ondownload == "on":
prowl_notify_ondownload = 1
else:
prowl_notify_ondownload = 0
if prowl_notify_onsubtitledownload == "on":
prowl_notify_onsubtitledownload = 1
else:
prowl_notify_onsubtitledownload = 0
if use_prowl == "on":
use_prowl = 1
else:
use_prowl = 0
if twitter_notify_onsnatch == "on":
twitter_notify_onsnatch = 1
else:
twitter_notify_onsnatch = 0
if twitter_notify_ondownload == "on":
twitter_notify_ondownload = 1
else:
twitter_notify_ondownload = 0
if twitter_notify_onsubtitledownload == "on":
twitter_notify_onsubtitledownload = 1
else:
twitter_notify_onsubtitledownload = 0
if use_twitter == "on":
use_twitter = 1
else:
use_twitter = 0
if boxcar_notify_onsnatch == "on":
boxcar_notify_onsnatch = 1
else:
boxcar_notify_onsnatch = 0
if boxcar_notify_ondownload == "on":
boxcar_notify_ondownload = 1
else:
boxcar_notify_ondownload = 0
if boxcar_notify_onsubtitledownload == "on":
boxcar_notify_onsubtitledownload = 1
else:
boxcar_notify_onsubtitledownload = 0
if use_boxcar == "on":
use_boxcar = 1
else:
use_boxcar = 0
if pushover_notify_onsnatch == "on":
pushover_notify_onsnatch = 1
else:
pushover_notify_onsnatch = 0
if pushover_notify_ondownload == "on":
pushover_notify_ondownload = 1
else:
pushover_notify_ondownload = 0
if pushover_notify_onsubtitledownload == "on":
pushover_notify_onsubtitledownload = 1
else:
pushover_notify_onsubtitledownload = 0
if use_pushover == "on":
use_pushover = 1
else:
use_pushover = 0
if use_nmj == "on":
use_nmj = 1
else:
use_nmj = 0
if use_synoindex == "on":
use_synoindex = 1
else:
use_synoindex = 0
if use_synologynotifier == "on":
use_synologynotifier = 1
else:
use_synologynotifier = 0
if synologynotifier_notify_onsnatch == "on":
synologynotifier_notify_onsnatch = 1
else:
synologynotifier_notify_onsnatch = 0
if synologynotifier_notify_ondownload == "on":
synologynotifier_notify_ondownload = 1
else:
synologynotifier_notify_ondownload = 0
if synologynotifier_notify_onsubtitledownload == "on":
synologynotifier_notify_onsubtitledownload = 1
else:
synologynotifier_notify_onsubtitledownload = 0
if use_nmjv2 == "on":
use_nmjv2 = 1
else:
use_nmjv2 = 0
if use_trakt == "on":
use_trakt = 1
else:
use_trakt = 0
if trakt_remove_watchlist == "on":
trakt_remove_watchlist = 1
else:
trakt_remove_watchlist = 0
if trakt_use_watchlist == "on":
trakt_use_watchlist = 1
else:
trakt_use_watchlist = 0
if trakt_start_paused == "on":
trakt_start_paused = 1
else:
trakt_start_paused = 0
if use_betaseries == "on":
use_betaseries = 1
else:
use_betaseries = 0
if use_pytivo == "on":
use_pytivo = 1
else:
use_pytivo = 0
if pytivo_notify_onsnatch == "on":
pytivo_notify_onsnatch = 1
else:
pytivo_notify_onsnatch = 0
if pytivo_notify_ondownload == "on":
pytivo_notify_ondownload = 1
else:
pytivo_notify_ondownload = 0
if pytivo_notify_onsubtitledownload == "on":
pytivo_notify_onsubtitledownload = 1
else:
pytivo_notify_onsubtitledownload = 0
if pytivo_update_library == "on":
pytivo_update_library = 1
else:
pytivo_update_library = 0
if use_nma == "on":
use_nma = 1
else:
use_nma = 0
if nma_notify_onsnatch == "on":
nma_notify_onsnatch = 1
else:
nma_notify_onsnatch = 0
if nma_notify_ondownload == "on":
nma_notify_ondownload = 1
else:
nma_notify_ondownload = 0
if nma_notify_onsubtitledownload == "on":
nma_notify_onsubtitledownload = 1
else:
nma_notify_onsubtitledownload = 0
if use_mail == "on":
use_mail = 1
else:
use_mail = 0
if mail_ssl == "on":
mail_ssl = 1
else:
mail_ssl = 0
if mail_notify_onsnatch == "on":
mail_notify_onsnatch = 1
else:
mail_notify_onsnatch = 0
if use_pushalot == "on":
use_pushalot = 1
else:
use_pushalot = 0
if pushalot_notify_onsnatch == "on":
pushalot_notify_onsnatch = 1
else:
pushalot_notify_onsnatch = 0
if pushalot_notify_ondownload == "on":
pushalot_notify_ondownload = 1
else:
pushalot_notify_ondownload = 0
if pushalot_notify_onsubtitledownload == "on":
pushalot_notify_onsubtitledownload = 1
else:
pushalot_notify_onsubtitledownload = 0
if use_pushbullet == "on":
use_pushbullet = 1
else:
use_pushbullet = 0
if pushbullet_notify_onsnatch == "on":
pushbullet_notify_onsnatch = 1
else:
pushbullet_notify_onsnatch = 0
if pushbullet_notify_ondownload == "on":
pushbullet_notify_ondownload = 1
else:
pushbullet_notify_ondownload = 0
if pushbullet_notify_onsubtitledownload == "on":
pushbullet_notify_onsubtitledownload = 1
else:
pushbullet_notify_onsubtitledownload = 0
if use_boxcar2=="on":
use_boxcar2=1
else:
use_boxcar2=0
if boxcar2_notify_onsnatch == "on":
boxcar2_notify_onsnatch = 1
else:
boxcar2_notify_onsnatch = 0
if boxcar2_notify_ondownload == "on":
boxcar2_notify_ondownload = 1
else:
boxcar2_notify_ondownload = 0
if boxcar2_notify_onsubtitledownload == "on":
boxcar2_notify_onsubtitledownload = 1
else:
boxcar2_notify_onsubtitledownload = 0
sickbeard.USE_XBMC = use_xbmc
sickbeard.XBMC_NOTIFY_ONSNATCH = xbmc_notify_onsnatch
sickbeard.XBMC_NOTIFY_ONDOWNLOAD = xbmc_notify_ondownload
sickbeard.XBMC_NOTIFY_ONSUBTITLEDOWNLOAD = xbmc_notify_onsubtitledownload
sickbeard.XBMC_UPDATE_LIBRARY = xbmc_update_library
sickbeard.XBMC_UPDATE_FULL = xbmc_update_full
sickbeard.XBMC_UPDATE_ONLYFIRST = xbmc_update_onlyfirst
sickbeard.XBMC_HOST = xbmc_host
sickbeard.XBMC_USERNAME = xbmc_username
sickbeard.XBMC_PASSWORD = xbmc_password
sickbeard.USE_PLEX = use_plex
sickbeard.PLEX_NOTIFY_ONSNATCH = plex_notify_onsnatch
sickbeard.PLEX_NOTIFY_ONDOWNLOAD = plex_notify_ondownload
sickbeard.PLEX_NOTIFY_ONSUBTITLEDOWNLOAD = plex_notify_onsubtitledownload
sickbeard.PLEX_UPDATE_LIBRARY = plex_update_library
sickbeard.PLEX_HOST = plex_host
sickbeard.PLEX_SERVER_HOST = plex_server_host
sickbeard.PLEX_USERNAME = plex_username
sickbeard.PLEX_PASSWORD = plex_password
sickbeard.USE_GROWL = use_growl
sickbeard.GROWL_NOTIFY_ONSNATCH = growl_notify_onsnatch
sickbeard.GROWL_NOTIFY_ONDOWNLOAD = growl_notify_ondownload
sickbeard.GROWL_NOTIFY_ONSUBTITLEDOWNLOAD = growl_notify_onsubtitledownload
sickbeard.GROWL_HOST = growl_host
sickbeard.GROWL_PASSWORD = growl_password
sickbeard.USE_PROWL = use_prowl
sickbeard.PROWL_NOTIFY_ONSNATCH = prowl_notify_onsnatch
sickbeard.PROWL_NOTIFY_ONDOWNLOAD = prowl_notify_ondownload
sickbeard.PROWL_NOTIFY_ONSUBTITLEDOWNLOAD = prowl_notify_onsubtitledownload
sickbeard.PROWL_API = prowl_api
sickbeard.PROWL_PRIORITY = prowl_priority
sickbeard.USE_TWITTER = use_twitter
sickbeard.TWITTER_NOTIFY_ONSNATCH = twitter_notify_onsnatch
sickbeard.TWITTER_NOTIFY_ONDOWNLOAD = twitter_notify_ondownload
sickbeard.TWITTER_NOTIFY_ONSUBTITLEDOWNLOAD = twitter_notify_onsubtitledownload
sickbeard.USE_BOXCAR = use_boxcar
sickbeard.BOXCAR_NOTIFY_ONSNATCH = boxcar_notify_onsnatch
sickbeard.BOXCAR_NOTIFY_ONDOWNLOAD = boxcar_notify_ondownload
sickbeard.BOXCAR_NOTIFY_ONSUBTITLEDOWNLOAD = boxcar_notify_onsubtitledownload
sickbeard.BOXCAR_USERNAME = boxcar_username
sickbeard.USE_BOXCAR2 = use_boxcar2
sickbeard.BOXCAR2_NOTIFY_ONSNATCH = boxcar2_notify_onsnatch
sickbeard.BOXCAR2_NOTIFY_ONDOWNLOAD = boxcar2_notify_ondownload
sickbeard.BOXCAR2_NOTIFY_ONSUBTITLEDOWNLOAD = boxcar2_notify_onsubtitledownload
sickbeard.BOXCAR2_ACCESS_TOKEN = boxcar2_access_token
sickbeard.BOXCAR2_SOUND = boxcar2_sound
sickbeard.USE_PUSHOVER = use_pushover
sickbeard.PUSHOVER_NOTIFY_ONSNATCH = pushover_notify_onsnatch
sickbeard.PUSHOVER_NOTIFY_ONDOWNLOAD = pushover_notify_ondownload
sickbeard.PUSHOVER_NOTIFY_ONSUBTITLEDOWNLOAD = pushover_notify_onsubtitledownload
sickbeard.PUSHOVER_USERKEY = pushover_userkey
sickbeard.PUSHOVER_PRIO = pushover_prio
sickbeard.USE_LIBNOTIFY = use_libnotify == "on"
sickbeard.LIBNOTIFY_NOTIFY_ONSNATCH = libnotify_notify_onsnatch == "on"
sickbeard.LIBNOTIFY_NOTIFY_ONDOWNLOAD = libnotify_notify_ondownload == "on"
sickbeard.LIBNOTIFY_NOTIFY_ONSUBTITLEDOWNLOAD = libnotify_notify_onsubtitledownload == "on"
sickbeard.USE_NMJ = use_nmj
sickbeard.NMJ_HOST = nmj_host
sickbeard.NMJ_DATABASE = nmj_database
sickbeard.NMJ_MOUNT = nmj_mount
sickbeard.USE_SYNOINDEX = use_synoindex
sickbeard.USE_SYNOLOGYNOTIFIER = use_synologynotifier
sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONSNATCH = synologynotifier_notify_onsnatch
sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONDOWNLOAD = synologynotifier_notify_ondownload
sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONSUBTITLEDOWNLOAD = synologynotifier_notify_onsubtitledownload
sickbeard.USE_NMJv2 = use_nmjv2
sickbeard.NMJv2_HOST = nmjv2_host
sickbeard.NMJv2_DATABASE = nmjv2_database
sickbeard.NMJv2_DBLOC = nmjv2_dbloc
sickbeard.USE_TRAKT = use_trakt
sickbeard.TRAKT_USERNAME = trakt_username
sickbeard.TRAKT_PASSWORD = trakt_password
sickbeard.TRAKT_API = trakt_api
sickbeard.TRAKT_REMOVE_WATCHLIST = trakt_remove_watchlist
sickbeard.TRAKT_USE_WATCHLIST = trakt_use_watchlist
sickbeard.TRAKT_METHOD_ADD = trakt_method_add
sickbeard.TRAKT_START_PAUSED = trakt_start_paused
sickbeard.USE_BETASERIES = use_betaseries
sickbeard.BETASERIES_USERNAME = betaseries_username
sickbeard.BETASERIES_PASSWORD = betaseries_password
sickbeard.USE_PYTIVO = use_pytivo
sickbeard.PYTIVO_NOTIFY_ONSNATCH = pytivo_notify_onsnatch == "off"
sickbeard.PYTIVO_NOTIFY_ONDOWNLOAD = pytivo_notify_ondownload == "off"
sickbeard.PYTIVO_NOTIFY_ONSUBTITLEDOWNLOAD = pytivo_notify_onsubtitledownload == "off"
sickbeard.PYTIVO_UPDATE_LIBRARY = pytivo_update_library
sickbeard.PYTIVO_HOST = pytivo_host
sickbeard.PYTIVO_SHARE_NAME = pytivo_share_name
sickbeard.PYTIVO_TIVO_NAME = pytivo_tivo_name
sickbeard.USE_NMA = use_nma
sickbeard.NMA_NOTIFY_ONSNATCH = nma_notify_onsnatch
sickbeard.NMA_NOTIFY_ONDOWNLOAD = nma_notify_ondownload
sickbeard.NMA_NOTIFY_ONSUBTITLEDOWNLOAD = nma_notify_onsubtitledownload
sickbeard.NMA_API = nma_api
sickbeard.NMA_PRIORITY = nma_priority
sickbeard.USE_MAIL = use_mail
sickbeard.MAIL_USERNAME = mail_username
sickbeard.MAIL_PASSWORD = mail_password
sickbeard.MAIL_SERVER = mail_server
sickbeard.MAIL_SSL = mail_ssl
sickbeard.MAIL_FROM = mail_from
sickbeard.MAIL_TO = mail_to
sickbeard.MAIL_NOTIFY_ONSNATCH = mail_notify_onsnatch
sickbeard.USE_PUSHALOT = use_pushalot
sickbeard.PUSHALOT_NOTIFY_ONSNATCH = pushalot_notify_onsnatch
sickbeard.PUSHALOT_NOTIFY_ONDOWNLOAD = pushalot_notify_ondownload
sickbeard.PUSHALOT_NOTIFY_ONSUBTITLEDOWNLOAD = pushalot_notify_onsubtitledownload
sickbeard.PUSHALOT_AUTHORIZATIONTOKEN = pushalot_authorizationtoken
sickbeard.USE_PUSHBULLET = use_pushbullet
sickbeard.PUSHBULLET_NOTIFY_ONSNATCH = pushbullet_notify_onsnatch
sickbeard.PUSHBULLET_NOTIFY_ONDOWNLOAD = pushbullet_notify_ondownload
sickbeard.PUSHBULLET_NOTIFY_ONSUBTITLEDOWNLOAD = pushbullet_notify_onsubtitledownload
sickbeard.PUSHBULLET_API = pushbullet_api
sickbeard.PUSHBULLET_DEVICE = pushbullet_device_list
sickbeard.PUSHBULLET_CHANNEL = pushbullet_channel_list
sickbeard.save_config()
if len(results) > 0:
for x in results:
logger.log(x, logger.ERROR)
ui.notifications.error('Error(s) Saving Configuration',
'<br />\n'.join(results))
else:
ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) )
redirect("/config/notifications/")
class ConfigSubtitles:
@cherrypy.expose
def index(self):
t = PageTemplate(file="config_subtitles.tmpl")
t.submenu = ConfigMenu
return _munge(t)
@cherrypy.expose
def saveSubtitles(self, use_subtitles=None, subsnewasold=None, subtitles_plugins=None, subtitles_languages=None, subtitles_dir=None, subtitles_dir_sub=None, subsnolang = None, service_order=None, subtitles_history=None, subtitles_clean_hi=None, subtitles_clean_team=None, subtitles_clean_music=None, subtitles_clean_punc=None):
results = []
if use_subtitles == "on":
use_subtitles = 1
if sickbeard.subtitlesFinderScheduler.thread == None or not sickbeard.subtitlesFinderScheduler.thread.isAlive():
sickbeard.subtitlesFinderScheduler.initThread()
else:
use_subtitles = 0
sickbeard.subtitlesFinderScheduler.abort = True
logger.log(u"Waiting for the SUBTITLESFINDER thread to exit")
try:
sickbeard.subtitlesFinderScheduler.thread.join(5)
except:
pass
if subtitles_history == "on":
subtitles_history = 1
else:
subtitles_history = 0
if subtitles_dir_sub == "on":
subtitles_dir_sub = 1
else:
subtitles_dir_sub = 0
if subsnewasold == "on":
subsnewasold = 1
else:
subsnewasold = 0
if subsnolang == "on":
subsnolang = 1
else:
subsnolang = 0
sickbeard.USE_SUBTITLES = use_subtitles
sickbeard.SUBSNEWASOLD = subsnewasold
sickbeard.SUBTITLES_LANGUAGES = [lang.alpha2 for lang in subtitles.isValidLanguage(subtitles_languages.replace(' ', '').split(','))] if subtitles_languages != '' else ''
sickbeard.SUBTITLES_DIR = subtitles_dir
sickbeard.SUBTITLES_DIR_SUB = subtitles_dir_sub
sickbeard.SUBSNOLANG = subsnolang
sickbeard.SUBTITLES_HISTORY = subtitles_history
# Subtitles services
services_str_list = service_order.split()
subtitles_services_list = []
subtitles_services_enabled = []
for curServiceStr in services_str_list:
curService, curEnabled = curServiceStr.split(':')
subtitles_services_list.append(curService)
subtitles_services_enabled.append(int(curEnabled))
sickbeard.SUBTITLES_SERVICES_LIST = subtitles_services_list
sickbeard.SUBTITLES_SERVICES_ENABLED = subtitles_services_enabled
#Subtitles Cleansing
if subtitles_clean_hi == "on":
subtitles_clean_hi = 1
else:
subtitles_clean_hi = 0
if subtitles_clean_team == "on":
subtitles_clean_team = 1
else:
subtitles_clean_team = 0
if subtitles_clean_music == "on":
subtitles_clean_music = 1
else:
subtitles_clean_music = 0
if subtitles_clean_punc == "on":
subtitles_clean_punc = 1
else:
subtitles_clean_punc = 0
sickbeard.SUBTITLES_CLEAN_HI = subtitles_clean_hi
sickbeard.SUBTITLES_CLEAN_TEAM = subtitles_clean_team
sickbeard.SUBTITLES_CLEAN_MUSIC = subtitles_clean_music
sickbeard.SUBTITLES_CLEAN_PUNC = subtitles_clean_punc
sickbeard.save_config()
if len(results) > 0:
for x in results:
logger.log(x, logger.ERROR)
ui.notifications.error('Error(s) Saving Configuration',
'<br />\n'.join(results))
else:
ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) )
redirect("/config/subtitles/")
class Config:
@cherrypy.expose
def index(self):
t = PageTemplate(file="config.tmpl")
t.submenu = ConfigMenu
return _munge(t)
general = ConfigGeneral()
search = ConfigSearch()
postProcessing = ConfigPostProcessing()
providers = ConfigProviders()
notifications = ConfigNotifications()
subtitles = ConfigSubtitles()
def haveXBMC():
return sickbeard.USE_XBMC and sickbeard.XBMC_UPDATE_LIBRARY
def havePLEX():
return sickbeard.USE_PLEX and sickbeard.PLEX_UPDATE_LIBRARY
def HomeMenu():
return [
{ 'title': 'Add Shows', 'path': 'home/addShows/', },
{ 'title': 'Manual Post-Processing', 'path': 'home/postprocess/' },
{ 'title': 'Update XBMC', 'path': 'home/updateXBMC/', 'requires': haveXBMC },
{ 'title': 'Update Plex', 'path': 'home/updatePLEX/', 'requires': havePLEX },
{ 'title': 'Update', 'path': 'manage/manageSearches/forceVersionCheck', 'confirm': True},
{ 'title': 'Restart', 'path': 'home/restart/?pid='+str(sickbeard.PID), 'confirm': True },
{ 'title': 'Shutdown', 'path': 'home/shutdown/?pid='+str(sickbeard.PID), 'confirm': True },
]
class HomePostProcess:
@cherrypy.expose
def index(self):
t = PageTemplate(file="home_postprocess.tmpl")
t.submenu = HomeMenu()
return _munge(t)
@cherrypy.expose
def processEpisode(self, dir=None, nzbName=None, jobName=None, quiet=None):
if not dir:
redirect("/home/postprocess")
else:
result = processTV.processDir(dir, nzbName)
if quiet != None and int(quiet) == 1:
return result
result = result.replace("\n","<br />\n")
return _genericMessage("Postprocessing results", result)
class NewHomeAddShows:
@cherrypy.expose
def index(self):
t = PageTemplate(file="home_addShows.tmpl")
t.submenu = HomeMenu()
return _munge(t)
@cherrypy.expose
def getTVDBLanguages(self):
result = tvdb_api.Tvdb().config['valid_languages']
# Make sure list is sorted alphabetically but 'fr' is in front
if 'fr' in result:
del result[result.index('fr')]
result.sort()
result.insert(0, 'fr')
return json.dumps({'results': result})
@cherrypy.expose
def sanitizeFileName(self, name):
return helpers.sanitizeFileName(name)
@cherrypy.expose
def searchTVDBForShowName(self, name, lang="fr"):
if not lang or lang == 'null':
lang = "fr"
baseURL = "http://thetvdb.com/api/GetSeries.php?"
nameUTF8 = name.encode('utf-8')
logger.log(u"Trying to find Show on thetvdb.com with: " + nameUTF8.decode('utf-8'), logger.DEBUG)
# Use each word in the show's name as a possible search term
keywords = nameUTF8.split(' ')
# Insert the whole show's name as the first search term so best results are first
# ex: keywords = ['Some Show Name', 'Some', 'Show', 'Name']
if len(keywords) > 1:
keywords.insert(0, nameUTF8)
# Query the TVDB for each search term and build the list of results
results = []
for searchTerm in keywords:
params = {'seriesname': searchTerm,
'language': lang}
finalURL = baseURL + urllib.urlencode(params)
logger.log(u"Searching for Show with searchterm: \'" + searchTerm.decode('utf-8') + u"\' on URL " + finalURL, logger.DEBUG)
urlData = helpers.getURL(finalURL)
if urlData is None:
# When urlData is None, trouble connecting to TVDB, don't try the rest of the keywords
logger.log(u"Unable to get URL: " + finalURL, logger.ERROR)
break
else:
try:
seriesXML = etree.ElementTree(etree.XML(urlData))
series = seriesXML.getiterator('Series')
except Exception, e:
# use finalURL in log, because urlData can be too much information
logger.log(u"Unable to parse XML for some reason: " + ex(e) + " from XML: " + finalURL, logger.ERROR)
series = ''
# add each result to our list
for curSeries in series:
tvdb_id = int(curSeries.findtext('seriesid'))
# don't add duplicates
if tvdb_id in [x[0] for x in results]:
continue
results.append((tvdb_id, curSeries.findtext('SeriesName'), curSeries.findtext('FirstAired')))
lang_id = tvdb_api.Tvdb().config['langabbv_to_id'][lang]
return json.dumps({'results': results, 'langid': lang_id})
@cherrypy.expose
def massAddTable(self, rootDir=None):
t = PageTemplate(file="home_massAddTable.tmpl")
t.submenu = HomeMenu()
myDB = db.DBConnection()
if not rootDir:
return "No folders selected."
elif type(rootDir) != list:
root_dirs = [rootDir]
else:
root_dirs = rootDir
root_dirs = [urllib.unquote_plus(x) for x in root_dirs]
default_index = int(sickbeard.ROOT_DIRS.split('|')[0])
if len(root_dirs) > default_index:
tmp = root_dirs[default_index]
if tmp in root_dirs:
root_dirs.remove(tmp)
root_dirs = [tmp]+root_dirs
dir_list = []
for root_dir in root_dirs:
try:
file_list = ek.ek(os.listdir, root_dir)
except:
continue
for cur_file in file_list:
cur_path = ek.ek(os.path.normpath, ek.ek(os.path.join, root_dir, cur_file))
if not ek.ek(os.path.isdir, cur_path):
continue
cur_dir = {
'dir': cur_path,
'display_dir': '<b>'+ek.ek(os.path.dirname, cur_path)+os.sep+'</b>'+ek.ek(os.path.basename, cur_path),
}
# see if the folder is in XBMC already
dirResults = myDB.select("SELECT * FROM tv_shows WHERE location = ?", [cur_path])
if dirResults:
cur_dir['added_already'] = True
else:
cur_dir['added_already'] = False
dir_list.append(cur_dir)
tvdb_id = ''
show_name = ''
for cur_provider in sickbeard.metadata_provider_dict.values():
(tvdb_id, show_name) = cur_provider.retrieveShowMetadata(cur_path)
if tvdb_id and show_name:
break
cur_dir['existing_info'] = (tvdb_id, show_name)
if tvdb_id and helpers.findCertainShow(sickbeard.showList, tvdb_id):
cur_dir['added_already'] = True
t.dirList = dir_list
return _munge(t)
@cherrypy.expose
def newShow(self, show_to_add=None, other_shows=None):
"""
Display the new show page which collects a tvdb id, folder, and extra options and
posts them to addNewShow
"""
t = PageTemplate(file="home_newShow.tmpl")
t.submenu = HomeMenu()
show_dir, tvdb_id, show_name = self.split_extra_show(show_to_add)
if tvdb_id and show_name:
use_provided_info = True
else:
use_provided_info = False
# tell the template whether we're giving it show name & TVDB ID
t.use_provided_info = use_provided_info
# use the given show_dir for the tvdb search if available
if not show_dir:
t.default_show_name = ''
elif not show_name:
t.default_show_name = ek.ek(os.path.basename, ek.ek(os.path.normpath, show_dir)).replace('.',' ')
else:
t.default_show_name = show_name
# carry a list of other dirs if given
if not other_shows:
other_shows = []
elif type(other_shows) != list:
other_shows = [other_shows]
if use_provided_info:
t.provided_tvdb_id = tvdb_id
t.provided_tvdb_name = show_name
t.provided_show_dir = show_dir
t.other_shows = other_shows
return _munge(t)
@cherrypy.expose
def addNewShow(self, whichSeries=None, tvdbLang="fr", rootDir=None, defaultStatus=None,
anyQualities=None, bestQualities=None, flatten_folders=None, subtitles=None, fullShowPath=None,
other_shows=None, skipShow=None, audio_lang=None):
"""
Receive tvdb id, dir, and other options and create a show from them. If extra show dirs are
provided then it forwards back to newShow, if not it goes to /home.
"""
# grab our list of other dirs if given
if not other_shows:
other_shows = []
elif type(other_shows) != list:
other_shows = [other_shows]
def finishAddShow():
# if there are no extra shows then go home
if not other_shows:
redirect('/home')
# peel off the next one
next_show_dir = other_shows[0]
rest_of_show_dirs = other_shows[1:]
# go to add the next show
return self.newShow(next_show_dir, rest_of_show_dirs)
# if we're skipping then behave accordingly
if skipShow:
return finishAddShow()
# sanity check on our inputs
if (not rootDir and not fullShowPath) or not whichSeries:
return "Missing params, no tvdb id or folder:"+repr(whichSeries)+" and "+repr(rootDir)+"/"+repr(fullShowPath)
# figure out what show we're adding and where
series_pieces = whichSeries.partition('|')
if len(series_pieces) < 3:
return "Error with show selection."
tvdb_id = int(series_pieces[0])
show_name = series_pieces[2]
# use the whole path if it's given, or else append the show name to the root dir to get the full show path
if fullShowPath:
show_dir = ek.ek(os.path.normpath, fullShowPath)
else:
show_dir = ek.ek(os.path.join, rootDir, helpers.sanitizeFileName(show_name))
# blanket policy - if the dir exists you should have used "add existing show" numbnuts
if ek.ek(os.path.isdir, show_dir) and not fullShowPath:
ui.notifications.error("Unable to add show", "Folder "+show_dir+" exists already")
redirect('/home/addShows/existingShows')
# don't create show dir if config says not to
if sickbeard.ADD_SHOWS_WO_DIR:
logger.log(u"Skipping initial creation of "+show_dir+" due to config.ini setting")
else:
dir_exists = helpers.makeDir(show_dir)
if not dir_exists:
logger.log(u"Unable to create the folder "+show_dir+", can't add the show", logger.ERROR)
ui.notifications.error("Unable to add show", "Unable to create the folder "+show_dir+", can't add the show")
redirect("/home")
else:
helpers.chmodAsParent(show_dir)
# prepare the inputs for passing along
if flatten_folders == "on":
flatten_folders = 1
else:
flatten_folders = 0
if subtitles == "on":
subtitles = 1
else:
subtitles = 0
if not anyQualities:
anyQualities = []
if not bestQualities:
bestQualities = []
if type(anyQualities) != list:
anyQualities = [anyQualities]
if type(bestQualities) != list:
bestQualities = [bestQualities]
newQuality = Quality.combineQualities(map(int, anyQualities), map(int, bestQualities))
# add the show
sickbeard.showQueueScheduler.action.addShow(tvdb_id, show_dir, int(defaultStatus), newQuality, flatten_folders, tvdbLang, subtitles, audio_lang) #@UndefinedVariable
ui.notifications.message('Show added', 'Adding the specified show into '+show_dir)
return finishAddShow()
@cherrypy.expose
def existingShows(self):
"""
Prints out the page to add existing shows from a root dir
"""
t = PageTemplate(file="home_addExistingShow.tmpl")
t.submenu = HomeMenu()
return _munge(t)
def split_extra_show(self, extra_show):
if not extra_show:
return (None, None, None)
split_vals = extra_show.split('|')
if len(split_vals) < 3:
return (extra_show, None, None)
show_dir = split_vals[0]
tvdb_id = split_vals[1]
show_name = '|'.join(split_vals[2:])
return (show_dir, tvdb_id, show_name)
@cherrypy.expose
def addExistingShows(self, shows_to_add=None, promptForSettings=None):
"""
Receives a dir list and add them. Adds the ones with given TVDB IDs first, then forwards
along to the newShow page.
"""
# grab a list of other shows to add, if provided
if not shows_to_add:
shows_to_add = []
elif type(shows_to_add) != list:
shows_to_add = [shows_to_add]
shows_to_add = [urllib.unquote_plus(x) for x in shows_to_add]
if promptForSettings == "on":
promptForSettings = 1
else:
promptForSettings = 0
tvdb_id_given = []
dirs_only = []
# separate all the ones with TVDB IDs
for cur_dir in shows_to_add:
if not '|' in cur_dir:
dirs_only.append(cur_dir)
else:
show_dir, tvdb_id, show_name = self.split_extra_show(cur_dir)
if not show_dir or not tvdb_id or not show_name:
continue
tvdb_id_given.append((show_dir, int(tvdb_id), show_name))
# if they want me to prompt for settings then I will just carry on to the newShow page
if promptForSettings and shows_to_add:
return self.newShow(shows_to_add[0], shows_to_add[1:])
# if they don't want me to prompt for settings then I can just add all the nfo shows now
num_added = 0
for cur_show in tvdb_id_given:
show_dir, tvdb_id, show_name = cur_show
# add the show
sickbeard.showQueueScheduler.action.addShow(tvdb_id, show_dir, int(sickbeard.STATUS_DEFAULT), sickbeard.QUALITY_DEFAULT, sickbeard.FLATTEN_FOLDERS_DEFAULT,"fr", sickbeard.SUBTITLES_DEFAULT, sickbeard.AUDIO_SHOW_DEFAULT) #@UndefinedVariable
num_added += 1
if num_added:
ui.notifications.message("Shows Added", "Automatically added "+str(num_added)+" from their existing metadata files")
# if we're done then go home
if not dirs_only:
redirect('/home')
# for the remaining shows we need to prompt for each one, so forward this on to the newShow page
return self.newShow(dirs_only[0], dirs_only[1:])
ErrorLogsMenu = [
{ 'title': 'Clear Errors', 'path': 'errorlogs/clearerrors' },
#{ 'title': 'View Log', 'path': 'errorlogs/viewlog' },
]
class ErrorLogs:
@cherrypy.expose
def index(self):
t = PageTemplate(file="errorlogs.tmpl")
t.submenu = ErrorLogsMenu
return _munge(t)
@cherrypy.expose
def clearerrors(self):
classes.ErrorViewer.clear()
redirect("/errorlogs")
@cherrypy.expose
def viewlog(self, minLevel=logger.MESSAGE, maxLines=500):
t = PageTemplate(file="viewlogs.tmpl")
t.submenu = ErrorLogsMenu
minLevel = int(minLevel)
data = []
if os.path.isfile(logger.sb_log_instance.log_file):
f = open(logger.sb_log_instance.log_file)
data = f.readlines()
f.close()
regex = "^(\w+).?\-(\d\d)\s+(\d\d)\:(\d\d):(\d\d)\s+([A-Z]+)\s+(.*)$"
finalData = []
numLines = 0
lastLine = False
numToShow = min(maxLines, len(data))
for x in reversed(data):
x = x.decode('utf-8')
match = re.match(regex, x)
if match:
level = match.group(6)
if level not in logger.reverseNames:
lastLine = False
continue
if logger.reverseNames[level] >= minLevel:
lastLine = True
finalData.append(x)
else:
lastLine = False
continue
elif lastLine:
finalData.append("AA"+x)
numLines += 1
if numLines >= numToShow:
break
result = "".join(finalData)
t.logLines = result
t.minLevel = minLevel
return _munge(t)
class Home:
@cherrypy.expose
def is_alive(self, *args, **kwargs):
if 'callback' in kwargs and '_' in kwargs:
callback, _ = kwargs['callback'], kwargs['_']
else:
return "Error: Unsupported Request. Send jsonp request with 'callback' variable in the query stiring."
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
cherrypy.response.headers['Content-Type'] = 'text/javascript'
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
cherrypy.response.headers['Access-Control-Allow-Headers'] = 'x-requested-with'
if sickbeard.started:
return callback+'('+json.dumps({"msg": str(sickbeard.PID)})+');'
else:
return callback+'('+json.dumps({"msg": "nope"})+');'
@cherrypy.expose
def index(self):
t = PageTemplate(file="home.tmpl")
t.submenu = HomeMenu()
return _munge(t)
addShows = NewHomeAddShows()
postprocess = HomePostProcess()
@cherrypy.expose
def testSABnzbd(self, host=None, username=None, password=None, apikey=None):
if not host.endswith("/"):
host = host + "/"
connection, accesMsg = sab.getSabAccesMethod(host, username, password, apikey)
if connection:
authed, authMsg = sab.testAuthentication(host, username, password, apikey) #@UnusedVariable
if authed:
return "Success. Connected and authenticated"
else:
return "Authentication failed. SABnzbd expects '"+accesMsg+"' as authentication method"
else:
return "Unable to connect to host"
@cherrypy.expose
def testTorrent(self, torrent_method=None, host=None, username=None, password=None):
if not host.endswith("/"):
host = host + "/"
client = clients.getClientIstance(torrent_method)
connection, accesMsg = client(host, username, password).testAuthentication()
return accesMsg
@cherrypy.expose
def testGrowl(self, host=None, password=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.growl_notifier.test_notify(host, password)
if password==None or password=='':
pw_append = ''
else:
pw_append = " with password: " + password
if result:
return "Registered and Tested growl successfully "+urllib.unquote_plus(host)+pw_append
else:
return "Registration and Testing of growl failed "+urllib.unquote_plus(host)+pw_append
@cherrypy.expose
def testProwl(self, prowl_api=None, prowl_priority=0):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.prowl_notifier.test_notify(prowl_api, prowl_priority)
if result:
return "Test prowl notice sent successfully"
else:
return "Test prowl notice failed"
@cherrypy.expose
def testBoxcar(self, username=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.boxcar_notifier.test_notify(username)
if result:
return "Boxcar notification succeeded. Check your Boxcar clients to make sure it worked"
else:
return "Error sending Boxcar notification"
@cherrypy.expose
def testBoxcar2(self, accessToken=None, sound=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.boxcar2_notifier.test_notify(accessToken, sound)
if result:
return "Boxcar2 notification succeeded. Check your Boxcar2 clients to make sure it worked"
else:
return "Error sending Boxcar2 notification"
@cherrypy.expose
def testPushover(self, userKey=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.pushover_notifier.test_notify(userKey)
if result:
return "Pushover notification succeeded. Check your Pushover clients to make sure it worked"
else:
return "Error sending Pushover notification"
@cherrypy.expose
def twitterStep1(self):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
return notifiers.twitter_notifier._get_authorization()
@cherrypy.expose
def twitterStep2(self, key):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.twitter_notifier._get_credentials(key)
logger.log(u"result: "+str(result))
if result:
return "Key verification successful"
else:
return "Unable to verify key"
@cherrypy.expose
def testTwitter(self):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.twitter_notifier.test_notify()
if result:
return "Tweet successful, check your twitter to make sure it worked"
else:
return "Error sending tweet"
@cherrypy.expose
def testXBMC(self, host=None, username=None, password=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
finalResult = ''
for curHost in [x.strip() for x in host.split(",")]:
curResult = notifiers.xbmc_notifier.test_notify(urllib.unquote_plus(curHost), username, password)
if len(curResult.split(":")) > 2 and 'OK' in curResult.split(":")[2]:
finalResult += "Test XBMC notice sent successfully to " + urllib.unquote_plus(curHost)
else:
finalResult += "Test XBMC notice failed to " + urllib.unquote_plus(curHost)
finalResult += "<br />\n"
return finalResult
@cherrypy.expose
def testPLEX(self, host=None, username=None, password=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
finalResult = ''
for curHost in [x.strip() for x in host.split(",")]:
curResult = notifiers.plex_notifier.test_notify(urllib.unquote_plus(curHost), username, password)
if len(curResult.split(":")) > 2 and 'OK' in curResult.split(":")[2]:
finalResult += "Test Plex notice sent successfully to " + urllib.unquote_plus(curHost)
else:
finalResult += "Test Plex notice failed to " + urllib.unquote_plus(curHost)
finalResult += "<br />\n"
return finalResult
@cherrypy.expose
def testLibnotify(self):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
if notifiers.libnotify_notifier.test_notify():
return "Tried sending desktop notification via libnotify"
else:
return notifiers.libnotify.diagnose()
@cherrypy.expose
def testNMJ(self, host=None, database=None, mount=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.nmj_notifier.test_notify(urllib.unquote_plus(host), database, mount)
if result:
return "Successfull started the scan update"
else:
return "Test failed to start the scan update"
@cherrypy.expose
def settingsNMJ(self, host=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.nmj_notifier.notify_settings(urllib.unquote_plus(host))
if result:
return '{"message": "Got settings from %(host)s", "database": "%(database)s", "mount": "%(mount)s"}' % {"host": host, "database": sickbeard.NMJ_DATABASE, "mount": sickbeard.NMJ_MOUNT}
else:
return '{"message": "Failed! Make sure your Popcorn is on and NMJ is running. (see Log & Errors -> Debug for detailed info)", "database": "", "mount": ""}'
@cherrypy.expose
def testNMJv2(self, host=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.nmjv2_notifier.test_notify(urllib.unquote_plus(host))
if result:
return "Test notice sent successfully to " + urllib.unquote_plus(host)
else:
return "Test notice failed to " + urllib.unquote_plus(host)
@cherrypy.expose
def settingsNMJv2(self, host=None, dbloc=None, instance=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.nmjv2_notifier.notify_settings(urllib.unquote_plus(host), dbloc, instance)
if result:
return '{"message": "NMJ Database found at: %(host)s", "database": "%(database)s"}' % {"host": host, "database": sickbeard.NMJv2_DATABASE}
else:
return '{"message": "Unable to find NMJ Database at location: %(dbloc)s. Is the right location selected and PCH running?", "database": ""}' % {"dbloc": dbloc}
@cherrypy.expose
def testTrakt(self, api=None, username=None, password=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.trakt_notifier.test_notify(api, username, password)
if result:
return "Test notice sent successfully to Trakt"
else:
return "Test notice failed to Trakt"
@cherrypy.expose
def testBetaSeries(self, username=None, password=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.betaseries_notifier.test_notify(username, password)
if result:
return "Test notice sent successfully to BetaSeries"
else:
return "Test notice failed to BetaSeries"
@cherrypy.expose
def testMail(self, mail_from=None, mail_to=None, mail_server=None, mail_ssl=None, mail_user=None, mail_password=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.mail_notifier.test_notify(mail_from, mail_to, mail_server, mail_ssl, mail_user, mail_password)
if result:
return "Mail sent"
else:
return "Can't sent mail."
@cherrypy.expose
def testNMA(self, nma_api=None, nma_priority=0):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.nma_notifier.test_notify(nma_api, nma_priority)
if result:
return "Test NMA notice sent successfully"
else:
return "Test NMA notice failed"
@cherrypy.expose
def testPushalot(self, authorizationToken=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.pushalot_notifier.test_notify(authorizationToken)
if result:
return "Pushalot notification succeeded. Check your Pushalot clients to make sure it worked"
else:
return "Error sending Pushalot notification"
@cherrypy.expose
def testPushbullet(self, api=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.pushbullet_notifier.test_notify(api)
if result:
return "Pushbullet notification succeeded. Check your device to make sure it worked"
else:
return "Error sending Pushbullet notification"
@cherrypy.expose
def getPushbulletDevices(self, api=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.pushbullet_notifier.get_devices(api)
if result:
return result
else:
return "Error sending Pushbullet notification"
@cherrypy.expose
#get channels
def getPushbulletChannels(self, api=None):
cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store"
result = notifiers.pushbullet_notifier.get_channels(api)
if result:
return result
else:
return "Error sending Pushbullet notification"
@cherrypy.expose
def shutdown(self, pid=None):
if str(pid) != str(sickbeard.PID):
redirect("/home")
threading.Timer(2, sickbeard.invoke_shutdown).start()
title = "Shutting down"
message = "Sick Beard is shutting down..."
return _genericMessage(title, message)
@cherrypy.expose
def restart(self, pid=None):
if str(pid) != str(sickbeard.PID):
redirect("/home")
t = PageTemplate(file="restart.tmpl")
t.submenu = HomeMenu()
# do a soft restart
threading.Timer(2, sickbeard.invoke_restart, [False]).start()
return _munge(t)
@cherrypy.expose
def update(self, pid=None):
if str(pid) != str(sickbeard.PID):
redirect("/home")
updated = sickbeard.versionCheckScheduler.action.update() #@UndefinedVariable
if updated:
# do a hard restart
threading.Timer(2, sickbeard.invoke_restart, [False]).start()
t = PageTemplate(file="restart_bare.tmpl")
return _munge(t)
else:
return _genericMessage("Update Failed","Update wasn't successful, not restarting. Check your log for more information.")
@cherrypy.expose
def displayShow(self, show=None):
if show == None:
return _genericMessage("Error", "Invalid show ID")
else:
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return _genericMessage("Error", "Show not in show list")
showObj.exceptions = scene_exceptions.get_scene_exceptions(showObj.tvdbid)
myDB = db.DBConnection()
seasonResults = myDB.select(
"SELECT DISTINCT season FROM tv_episodes WHERE showid = ? ORDER BY season desc",
[showObj.tvdbid]
)
sqlResults = myDB.select(
"SELECT * FROM tv_episodes WHERE showid = ? ORDER BY season DESC, episode DESC",
[showObj.tvdbid]
)
t = PageTemplate(file="displayShow.tmpl")
t.submenu = [ { 'title': 'Edit', 'path': 'home/editShow?show=%d'%showObj.tvdbid } ]
try:
t.showLoc = (showObj.location, True)
except sickbeard.exceptions.ShowDirNotFoundException:
t.showLoc = (showObj._location, False)
show_message = ''
if sickbeard.showQueueScheduler.action.isBeingAdded(showObj): #@UndefinedVariable
show_message = 'This show is in the process of being downloaded from theTVDB.com - the info below is incomplete.'
elif sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): #@UndefinedVariable
show_message = 'The information below is in the process of being updated.'
elif sickbeard.showQueueScheduler.action.isBeingRefreshed(showObj): #@UndefinedVariable
show_message = 'The episodes below are currently being refreshed from disk'
elif sickbeard.showQueueScheduler.action.isBeingSubtitled(showObj): #@UndefinedVariable
show_message = 'Currently downloading subtitles for this show'
elif sickbeard.showQueueScheduler.action.isBeingCleanedSubtitle(showObj): #@UndefinedVariable
show_message = 'Currently cleaning subtitles for this show'
elif sickbeard.showQueueScheduler.action.isInRefreshQueue(showObj): #@UndefinedVariable
show_message = 'This show is queued to be refreshed.'
elif sickbeard.showQueueScheduler.action.isInUpdateQueue(showObj): #@UndefinedVariable
show_message = 'This show is queued and awaiting an update.'
elif sickbeard.showQueueScheduler.action.isInSubtitleQueue(showObj): #@UndefinedVariable
show_message = 'This show is queued and awaiting subtitles download.'
if not sickbeard.showQueueScheduler.action.isBeingAdded(showObj): #@UndefinedVariable
if not sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): #@UndefinedVariable
t.submenu.append({ 'title': 'Delete', 'path': 'home/deleteShow?show=%d'%showObj.tvdbid, 'confirm': True })
t.submenu.append({ 'title': 'Re-scan files', 'path': 'home/refreshShow?show=%d'%showObj.tvdbid })
t.submenu.append({ 'title': 'Force Full Update', 'path': 'home/updateShow?show=%d&force=1'%showObj.tvdbid })
t.submenu.append({ 'title': 'Update show in XBMC', 'path': 'home/updateXBMC?showName=%s'%urllib.quote_plus(showObj.name.encode('utf-8')), 'requires': haveXBMC })
t.submenu.append({ 'title': 'Preview Rename', 'path': 'home/testRename?show=%d'%showObj.tvdbid })
t.submenu.append({ 'title': 'French Search', 'path': 'home/frenchSearch?show=%d'%showObj.tvdbid })
if sickbeard.USE_SUBTITLES and not sickbeard.showQueueScheduler.action.isBeingSubtitled(showObj) and not sickbeard.showQueueScheduler.action.isBeingCleanedSubtitle(showObj) and showObj.subtitles:
t.submenu.append({ 'title': 'Download Subtitles', 'path': 'home/subtitleShow?show=%d'%showObj.tvdbid })
t.submenu.append({ 'title': 'Clean Subtitles', 'path': 'home/subtitleShowClean?show=%d'%showObj.tvdbid })
t.show = showObj
t.sqlResults = sqlResults
t.seasonResults = seasonResults
t.show_message = show_message
epCounts = {}
epCats = {}
epCounts[Overview.SKIPPED] = 0
epCounts[Overview.WANTED] = 0
epCounts[Overview.QUAL] = 0
epCounts[Overview.GOOD] = 0
epCounts[Overview.UNAIRED] = 0
epCounts[Overview.SNATCHED] = 0
showSceneNumberColum = False
for curResult in sqlResults:
if not showSceneNumberColum and (isinstance(curResult["scene_season"], int) and isinstance(curResult["scene_episode"], int)):
showSceneNumberColum = True
curEpCat = showObj.getOverview(int(curResult["status"]))
epCats[str(curResult["season"])+"x"+str(curResult["episode"])] = curEpCat
epCounts[curEpCat] += 1
t.showSceneNumberColum = showSceneNumberColum
def titler(x):
if not x:
return x
if x.lower().startswith('a '):
x = x[2:]
elif x.lower().startswith('the '):
x = x[4:]
return x
t.sortedShowList = sorted(sickbeard.showList, lambda x, y: cmp(titler(x.name), titler(y.name)))
t.epCounts = epCounts
t.epCats = epCats
return _munge(t)
@cherrypy.expose
def plotDetails(self, show, season, episode):
result = db.DBConnection().action("SELECT description FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ?", (show, season, episode)).fetchone()
return result['description'] if result else 'Episode not found.'
@cherrypy.expose
def editShow(self, show=None, location=None, anyQualities=[], bestQualities=[], exceptions_list=[], flatten_folders=None, paused=None, frenchsearch=None, directCall=False, air_by_date=None, tvdbLang=None, audio_lang=None, subtitles=None):
if show == None:
errString = "Invalid show ID: "+str(show)
if directCall:
return [errString]
else:
return _genericMessage("Error", errString)
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
errString = "Unable to find the specified show: "+str(show)
if directCall:
return [errString]
else:
return _genericMessage("Error", errString)
showObj.exceptions = scene_exceptions.get_scene_exceptions(showObj.tvdbid)
if not location and not anyQualities and not bestQualities and not flatten_folders:
t = PageTemplate(file="editShow.tmpl")
t.submenu = HomeMenu()
with showObj.lock:
t.show = showObj
return _munge(t)
if flatten_folders == "on":
flatten_folders = 1
else:
flatten_folders = 0
logger.log(u"flatten folders: "+str(flatten_folders))
if paused == "on":
paused = 1
else:
paused = 0
if frenchsearch == "on":
frenchsearch = 1
else:
frenchsearch = 0
if air_by_date == "on":
air_by_date = 1
else:
air_by_date = 0
if subtitles == "on":
subtitles = 1
else:
subtitles = 0
if tvdbLang and tvdbLang in tvdb_api.Tvdb().config['valid_languages']:
tvdb_lang = tvdbLang
else:
tvdb_lang = showObj.lang
# if we changed the language then kick off an update
if tvdb_lang == showObj.lang:
do_update = False
else:
do_update = True
if type(anyQualities) != list:
anyQualities = [anyQualities]
if type(bestQualities) != list:
bestQualities = [bestQualities]
if type(exceptions_list) != list:
exceptions_list = [exceptions_list]
#If directCall from mass_edit_update no scene exceptions handling
if directCall:
do_update_exceptions = False
else:
if set(exceptions_list) == set(showObj.exceptions):
do_update_exceptions = False
else:
do_update_exceptions = True
errors = []
with showObj.lock:
newQuality = Quality.combineQualities(map(int, anyQualities), map(int, bestQualities))
showObj.quality = newQuality
# reversed for now
if bool(showObj.flatten_folders) != bool(flatten_folders):
showObj.flatten_folders = flatten_folders
try:
sickbeard.showQueueScheduler.action.refreshShow(showObj) #@UndefinedVariable
except exceptions.CantRefreshException, e:
errors.append("Unable to refresh this show: "+ex(e))
showObj.paused = paused
showObj.air_by_date = air_by_date
showObj.subtitles = subtitles
showObj.frenchsearch = frenchsearch
showObj.lang = tvdb_lang
showObj.audio_lang = audio_lang
# if we change location clear the db of episodes, change it, write to db, and rescan
if os.path.normpath(showObj._location) != os.path.normpath(location):
logger.log(os.path.normpath(showObj._location)+" != "+os.path.normpath(location), logger.DEBUG)
if not ek.ek(os.path.isdir, location):
errors.append("New location <tt>%s</tt> does not exist" % location)
# don't bother if we're going to update anyway
elif not do_update:
# change it
try:
showObj.location = location
try:
sickbeard.showQueueScheduler.action.refreshShow(showObj) #@UndefinedVariable
except exceptions.CantRefreshException, e:
errors.append("Unable to refresh this show:"+ex(e))
# grab updated info from TVDB
#showObj.loadEpisodesFromTVDB()
# rescan the episodes in the new folder
except exceptions.NoNFOException:
errors.append("The folder at <tt>%s</tt> doesn't contain a tvshow.nfo - copy your files to that folder before you change the directory in Sick Beard." % location)
# save it to the DB
showObj.saveToDB()
# force the update
if do_update:
try:
sickbeard.showQueueScheduler.action.updateShow(showObj, True) #@UndefinedVariable
time.sleep(1)
except exceptions.CantUpdateException, e:
errors.append("Unable to force an update on the show.")
if do_update_exceptions:
try:
scene_exceptions.update_scene_exceptions(showObj.tvdbid, exceptions_list) #@UndefinedVariable
time.sleep(1)
except exceptions.CantUpdateException, e:
errors.append("Unable to force an update on scene exceptions of the show.")
if directCall:
return errors
if len(errors) > 0:
ui.notifications.error('%d error%s while saving changes:' % (len(errors), "" if len(errors) == 1 else "s"),
'<ul>' + '\n'.join(['<li>%s</li>' % error for error in errors]) + "</ul>")
redirect("/home/displayShow?show=" + show)
@cherrypy.expose
def deleteShow(self, show=None):
if show == None:
return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return _genericMessage("Error", "Unable to find the specified show")
if sickbeard.showQueueScheduler.action.isBeingAdded(showObj) or sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): #@UndefinedVariable
return _genericMessage("Error", "Shows can't be deleted while they're being added or updated.")
showObj.deleteShow()
ui.notifications.message('<b>%s</b> has been deleted' % showObj.name)
redirect("/home")
@cherrypy.expose
def refreshShow(self, show=None):
if show == None:
return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return _genericMessage("Error", "Unable to find the specified show")
# force the update from the DB
try:
sickbeard.showQueueScheduler.action.refreshShow(showObj) #@UndefinedVariable
except exceptions.CantRefreshException, e:
ui.notifications.error("Unable to refresh this show.",
ex(e))
time.sleep(3)
redirect("/home/displayShow?show="+str(showObj.tvdbid))
@cherrypy.expose
def updateShow(self, show=None, force=0):
if show == None:
return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return _genericMessage("Error", "Unable to find the specified show")
# force the update
try:
sickbeard.showQueueScheduler.action.updateShow(showObj, bool(force)) #@UndefinedVariable
except exceptions.CantUpdateException, e:
ui.notifications.error("Unable to update this show.",
ex(e))
# just give it some time
time.sleep(3)
redirect("/home/displayShow?show=" + str(showObj.tvdbid))
@cherrypy.expose
def subtitleShow(self, show=None, force=0):
if show == None:
return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return _genericMessage("Error", "Unable to find the specified show")
# search and download subtitles
sickbeard.showQueueScheduler.action.downloadSubtitles(showObj, bool(force)) #@UndefinedVariable
time.sleep(3)
redirect("/home/displayShow?show="+str(showObj.tvdbid))
@cherrypy.expose
def subtitleShowClean(self, show=None, force=0):
if show == None:
return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return _genericMessage("Error", "Unable to find the specified show")
# search and download subtitles
sickbeard.showQueueScheduler.action.cleanSubtitles(showObj, bool(force)) #@UndefinedVariable
time.sleep(3)
redirect("/home/displayShow?show="+str(showObj.tvdbid))
@cherrypy.expose
def frenchSearch(self, show=None, force=0):
if show == None:
return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return _genericMessage("Error", "Unable to find the specified show")
# search and download subtitles
sickbeard.showQueueScheduler.action.searchFrench(showObj, bool(force)) #@UndefinedVariable
time.sleep(3)
redirect("/home/displayShow?show="+str(showObj.tvdbid))
@cherrypy.expose
def updateXBMC(self, showName=None):
if sickbeard.XBMC_UPDATE_ONLYFIRST:
# only send update to first host in the list -- workaround for xbmc sql backend users
host = sickbeard.XBMC_HOST.split(",")[0].strip()
else:
host = sickbeard.XBMC_HOST
if notifiers.xbmc_notifier.update_library(showName=showName):
ui.notifications.message("Library update command sent to XBMC host(s): " + host)
else:
ui.notifications.error("Unable to contact one or more XBMC host(s): " + host)
redirect('/home')
@cherrypy.expose
def updatePLEX(self):
if notifiers.plex_notifier.update_library():
ui.notifications.message("Library update command sent to Plex Media Server host: " + sickbeard.PLEX_SERVER_HOST)
else:
ui.notifications.error("Unable to contact Plex Media Server host: " + sickbeard.PLEX_SERVER_HOST)
redirect('/home')
@cherrypy.expose
def setStatus(self, show=None, eps=None, status=None, direct=False):
if show == None or eps == None or status == None:
errMsg = "You must specify a show and at least one episode"
if direct:
ui.notifications.error('Error', errMsg)
return json.dumps({'result': 'error'})
else:
return _genericMessage("Error", errMsg)
if not statusStrings.has_key(int(status)):
errMsg = "Invalid status"
if direct:
ui.notifications.error('Error', errMsg)
return json.dumps({'result': 'error'})
else:
return _genericMessage("Error", errMsg)
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
errMsg = "Error", "Show not in show list"
if direct:
ui.notifications.error('Error', errMsg)
return json.dumps({'result': 'error'})
else:
return _genericMessage("Error", errMsg)
segment_list = []
if eps != None:
for curEp in eps.split('|'):
logger.log(u"Attempting to set status on episode "+curEp+" to "+status, logger.DEBUG)
epInfo = curEp.split('x')
epObj = showObj.getEpisode(int(epInfo[0]), int(epInfo[1]))
if int(status) == WANTED:
# figure out what segment the episode is in and remember it so we can backlog it
if epObj.show.air_by_date:
ep_segment = str(epObj.airdate)[:7]
else:
ep_segment = epObj.season
if ep_segment not in segment_list:
segment_list.append(ep_segment)
if epObj == None:
return _genericMessage("Error", "Episode couldn't be retrieved")
with epObj.lock:
# don't let them mess up UNAIRED episodes
if epObj.status == UNAIRED:
logger.log(u"Refusing to change status of "+curEp+" because it is UNAIRED", logger.ERROR)
continue
if int(status) in Quality.DOWNLOADED and epObj.status not in Quality.SNATCHED + Quality.SNATCHED_PROPER + Quality.SNATCHED_FRENCH + Quality.DOWNLOADED + [IGNORED] and not ek.ek(os.path.isfile, epObj.location):
logger.log(u"Refusing to change status of "+curEp+" to DOWNLOADED because it's not SNATCHED/DOWNLOADED", logger.ERROR)
continue
epObj.status = int(status)
epObj.saveToDB()
msg = "Backlog was automatically started for the following seasons of <b>"+showObj.name+"</b>:<br />"
for cur_segment in segment_list:
msg += "<li>Season "+str(cur_segment)+"</li>"
logger.log(u"Sending backlog for "+showObj.name+" season "+str(cur_segment)+" because some eps were set to wanted")
cur_backlog_queue_item = search_queue.BacklogQueueItem(showObj, cur_segment)
sickbeard.searchQueueScheduler.action.add_item(cur_backlog_queue_item) #@UndefinedVariable
msg += "</ul>"
if segment_list:
ui.notifications.message("Backlog started", msg)
if direct:
return json.dumps({'result': 'success'})
else:
redirect("/home/displayShow?show=" + show)
@cherrypy.expose
def setAudio(self, show=None, eps=None, audio_langs=None, direct=False):
if show == None or eps == None or audio_langs == None:
errMsg = "You must specify a show and at least one episode"
if direct:
ui.notifications.error('Error', errMsg)
return json.dumps({'result': 'error'})
else:
return _genericMessage("Error", errMsg)
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return _genericMessage("Error", "Show not in show list")
try:
show_loc = showObj.location #@UnusedVariable
except exceptions.ShowDirNotFoundException:
return _genericMessage("Error", "Can't rename episodes when the show dir is missing.")
ep_obj_rename_list = []
for curEp in eps.split('|'):
logger.log(u"Attempting to set audio on episode "+curEp+" to "+audio_langs, logger.DEBUG)
epInfo = curEp.split('x')
epObj = showObj.getEpisode(int(epInfo[0]), int(epInfo[1]))
epObj.audio_langs = str(audio_langs)
epObj.saveToDB()
if direct:
return json.dumps({'result': 'success'})
else:
redirect("/home/displayShow?show=" + show)
@cherrypy.expose
def testRename(self, show=None):
if show == None:
return _genericMessage("Error", "You must specify a show")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None:
return _genericMessage("Error", "Show not in show list")
try:
show_loc = showObj.location #@UnusedVariable
except exceptions.ShowDirNotFoundException:
return _genericMessage("Error", "Can't rename episodes when the show dir is missing.")
ep_obj_rename_list = []
ep_obj_list = showObj.getAllEpisodes(has_location=True)
for cur_ep_obj in ep_obj_list:
# Only want to rename if we have a location
if cur_ep_obj.location:
if cur_ep_obj.relatedEps:
# do we have one of multi-episodes in the rename list already
have_already = False
for cur_related_ep in cur_ep_obj.relatedEps + [cur_ep_obj]:
if cur_related_ep in ep_obj_rename_list:
have_already = True
break
if not have_already:
ep_obj_rename_list.append(cur_ep_obj)
else:
ep_obj_rename_list.append(cur_ep_obj)
if ep_obj_rename_list:
# present season DESC episode DESC on screen
ep_obj_rename_list.reverse()
t = PageTemplate(file="testRename.tmpl")
t.submenu = [{'title': 'Edit', 'path': 'home/editShow?show=%d' % showObj.tvdbid}]
t.ep_obj_list = ep_obj_rename_list
t.show = showObj
return _munge(t)
@cherrypy.expose
def doRename(self, show=None, eps=None):
if show == None or eps == None:
errMsg = "You must specify a show and at least one episode"
return _genericMessage("Error", errMsg)
show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if show_obj == None:
errMsg = "Error", "Show not in show list"
return _genericMessage("Error", errMsg)
try:
show_loc = show_obj.location #@UnusedVariable
except exceptions.ShowDirNotFoundException:
return _genericMessage("Error", "Can't rename episodes when the show dir is missing.")
myDB = db.DBConnection()
if eps == None:
redirect("/home/displayShow?show=" + show)
for curEp in eps.split('|'):
epInfo = curEp.split('x')
# this is probably the worst possible way to deal with double eps but I've kinda painted myself into a corner here with this stupid database
ep_result = myDB.select("SELECT * FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ? AND 5=5", [show, epInfo[0], epInfo[1]])
if not ep_result:
logger.log(u"Unable to find an episode for "+curEp+", skipping", logger.WARNING)
continue
related_eps_result = myDB.select("SELECT * FROM tv_episodes WHERE location = ? AND episode != ?", [ep_result[0]["location"], epInfo[1]])
root_ep_obj = show_obj.getEpisode(int(epInfo[0]), int(epInfo[1]))
for cur_related_ep in related_eps_result:
related_ep_obj = show_obj.getEpisode(int(cur_related_ep["season"]), int(cur_related_ep["episode"]))
if related_ep_obj not in root_ep_obj.relatedEps:
root_ep_obj.relatedEps.append(related_ep_obj)
root_ep_obj.rename()
redirect("/home/displayShow?show=" + show)
@cherrypy.expose
def trunchistory(self, epid):
myDB = db.DBConnection()
nbep = myDB.select("Select count(*) from episode_links where episode_id=?",[epid])
myDB.action("DELETE from episode_links where episode_id=?",[epid])
messnum = str(nbep[0][0]) + ' history links deleted'
ui.notifications.message('Episode History Truncated' , messnum)
return json.dumps({'result': 'ok'})
@cherrypy.expose
def searchEpisode(self, show=None, season=None, episode=None):
# retrieve the episode object and fail if we can't get one
ep_obj = _getEpisode(show, season, episode)
if isinstance(ep_obj, str):
return json.dumps({'result': 'failure'})
# make a queue item for it and put it on the queue
ep_queue_item = search_queue.ManualSearchQueueItem(ep_obj)
sickbeard.searchQueueScheduler.action.add_item(ep_queue_item) #@UndefinedVariable
# wait until the queue item tells us whether it worked or not
while ep_queue_item.success == None: #@UndefinedVariable
time.sleep(1)
# return the correct json value
if ep_queue_item.success:
return json.dumps({'result': statusStrings[ep_obj.status]})
return json.dumps({'result': 'failure'})
@cherrypy.expose
def searchEpisodeSubtitles(self, show=None, season=None, episode=None):
# retrieve the episode object and fail if we can't get one
ep_obj = _getEpisode(show, season, episode)
if isinstance(ep_obj, str):
return json.dumps({'result': 'failure'})
# try do download subtitles for that episode
previous_subtitles = ep_obj.subtitles
try:
subtitles = ep_obj.downloadSubtitles()
if sickbeard.SUBTITLES_DIR:
for video in subtitles:
subs_new_path = ek.ek(os.path.join, os.path.dirname(video.path), sickbeard.SUBTITLES_DIR)
dir_exists = helpers.makeDir(subs_new_path)
if not dir_exists:
logger.log(u"Unable to create subtitles folder "+subs_new_path, logger.ERROR)
else:
helpers.chmodAsParent(subs_new_path)
for subtitle in subtitles.get(video):
new_file_path = ek.ek(os.path.join, subs_new_path, os.path.basename(subtitle.path))
helpers.moveFile(subtitle.path, new_file_path)
if sickbeard.SUBSNOLANG:
helpers.copyFile(new_file_path,new_file_path[:-6]+"srt")
helpers.chmodAsParent(new_file_path[:-6]+"srt")
helpers.chmodAsParent(new_file_path)
else:
if sickbeard.SUBTITLES_DIR_SUB:
for video in subtitles:
subs_new_path = os.path.join(os.path.dirname(video.path),"Subs")
dir_exists = helpers.makeDir(subs_new_path)
if not dir_exists:
logger.log(u"Unable to create subtitles folder "+subs_new_path, logger.ERROR)
else:
helpers.chmodAsParent(subs_new_path)
for subtitle in subtitles.get(video):
new_file_path = ek.ek(os.path.join, subs_new_path, os.path.basename(subtitle.path))
helpers.moveFile(subtitle.path, new_file_path)
if sickbeard.SUBSNOLANG:
helpers.copyFile(new_file_path,new_file_path[:-6]+"srt")
helpers.chmodAsParent(new_file_path[:-6]+"srt")
helpers.chmodAsParent(new_file_path)
else:
for video in subtitles:
for subtitle in subtitles.get(video):
if sickbeard.SUBSNOLANG:
helpers.copyFile(subtitle.path,subtitle.path[:-6]+"srt")
helpers.chmodAsParent(subtitle.path[:-6]+"srt")
helpers.chmodAsParent(subtitle.path)
except:
return json.dumps({'result': 'failure'})
# return the correct json value
if previous_subtitles != ep_obj.subtitles:
status = 'New subtitles downloaded: %s' % ' '.join(["<img src='"+sickbeard.WEB_ROOT+"/images/flags/"+subliminal.language.Language(x).alpha2+".png' alt='"+subliminal.language.Language(x).name+"'/>" for x in sorted(list(set(ep_obj.subtitles).difference(previous_subtitles)))])
else:
status = 'No subtitles downloaded'
ui.notifications.message('Subtitles Search', status)
return json.dumps({'result': status, 'subtitles': ','.join([x for x in ep_obj.subtitles])})
@cherrypy.expose
def mergeEpisodeSubtitles(self, show=None, season=None, episode=None):
# retrieve the episode object and fail if we can't get one
ep_obj = _getEpisode(show, season, episode)
if isinstance(ep_obj, str):
return json.dumps({'result': 'failure'})
# try do merge subtitles for that episode
try:
ep_obj.mergeSubtitles()
except Exception as e:
return json.dumps({'result': 'failure', 'exception': str(e)})
# return the correct json value
status = 'Subtitles merged successfully '
ui.notifications.message('Merge Subtitles', status)
return json.dumps({'result': 'ok'})
class UI:
@cherrypy.expose
def add_message(self):
ui.notifications.message('Test 1', 'This is test number 1')
ui.notifications.error('Test 2', 'This is test number 2')
return "ok"
@cherrypy.expose
def get_messages(self):
messages = {}
cur_notification_num = 1
for cur_notification in ui.notifications.get_notifications():
messages['notification-'+str(cur_notification_num)] = {'title': cur_notification.title,
'message': cur_notification.message,
'type': cur_notification.type}
cur_notification_num += 1
return json.dumps(messages)
class WebInterface:
@cherrypy.expose
def index(self):
redirect("/home")
@cherrypy.expose
def showPoster(self, show=None, which=None):
#Redirect initial poster/banner thumb to default images
if which[0:6] == 'poster':
default_image_name = 'poster.png'
else:
default_image_name = 'banner.png'
default_image_path = ek.ek(os.path.join, sickbeard.PROG_DIR, 'data', 'images', default_image_name)
if show is None:
return cherrypy.lib.static.serve_file(default_image_path, content_type="image/png")
else:
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj is None:
return cherrypy.lib.static.serve_file(default_image_path, content_type="image/png")
cache_obj = image_cache.ImageCache()
if which == 'poster':
image_file_name = cache_obj.poster_path(showObj.tvdbid)
if which == 'poster_thumb':
image_file_name = cache_obj.poster_thumb_path(showObj.tvdbid)
if which == 'banner':
image_file_name = cache_obj.banner_path(showObj.tvdbid)
if which == 'banner_thumb':
image_file_name = cache_obj.banner_thumb_path(showObj.tvdbid)
if ek.ek(os.path.isfile, image_file_name):
return cherrypy.lib.static.serve_file(image_file_name, content_type="image/jpeg")
else:
return cherrypy.lib.static.serve_file(default_image_path, content_type="image/png")
@cherrypy.expose
def setHomeLayout(self, layout):
if layout not in ('poster', 'banner', 'simple'):
layout = 'poster'
sickbeard.HOME_LAYOUT = layout
redirect("/home")
@cherrypy.expose
def setHomeSearch(self, search):
if search not in ('True', 'False'):
search = 'False'
sickbeard.TOGGLE_SEARCH= search
redirect("/home")
@cherrypy.expose
def toggleDisplayShowSpecials(self, show):
sickbeard.DISPLAY_SHOW_SPECIALS = not sickbeard.DISPLAY_SHOW_SPECIALS
redirect("/home/displayShow?show=" + show)
@cherrypy.expose
def setComingEpsLayout(self, layout):
if layout not in ('poster', 'banner', 'list'):
layout = 'banner'
sickbeard.COMING_EPS_LAYOUT = layout
redirect("/comingEpisodes")
@cherrypy.expose
def toggleComingEpsDisplayPaused(self):
sickbeard.COMING_EPS_DISPLAY_PAUSED = not sickbeard.COMING_EPS_DISPLAY_PAUSED
redirect("/comingEpisodes")
@cherrypy.expose
def setComingEpsSort(self, sort):
if sort not in ('date', 'network', 'show'):
sort = 'date'
sickbeard.COMING_EPS_SORT = sort
redirect("/comingEpisodes")
@cherrypy.expose
def comingEpisodes(self, layout="None"):
# get local timezone and load network timezones
sb_timezone = tz.tzlocal()
network_dict = network_timezones.load_network_dict()
myDB = db.DBConnection()
today1 = datetime.date.today()
today = today1.toordinal()
next_week1 = (datetime.date.today() + datetime.timedelta(days=7))
next_week = next_week1.toordinal()
recently = (datetime.date.today() - datetime.timedelta(days=sickbeard.COMING_EPS_MISSED_RANGE)).toordinal()
done_show_list = []
qualList = Quality.DOWNLOADED + Quality.SNATCHED + [ARCHIVED, IGNORED]
sql_results1 = myDB.select("SELECT *, 0 as localtime, tv_shows.status as show_status FROM tv_episodes, tv_shows WHERE season != 0 AND airdate >= ? AND airdate < ? AND tv_shows.tvdb_id = tv_episodes.showid AND tv_episodes.status NOT IN ("+','.join(['?']*len(qualList))+")", [today, next_week] + qualList)
for cur_result in sql_results1:
done_show_list.append(helpers.tryInt(cur_result["showid"]))
more_sql_results = myDB.select("SELECT *, tv_shows.status as show_status FROM tv_episodes outer_eps, tv_shows WHERE season != 0 AND showid NOT IN ("+','.join(['?']*len(done_show_list))+") AND tv_shows.tvdb_id = outer_eps.showid AND airdate IN (SELECT airdate FROM tv_episodes inner_eps WHERE inner_eps.showid = outer_eps.showid AND inner_eps.airdate >= ? AND inner_eps.status NOT IN ("+','.join(['?']*len(Quality.DOWNLOADED+Quality.SNATCHED))+") ORDER BY inner_eps.airdate ASC LIMIT 1)", done_show_list + [next_week] + Quality.DOWNLOADED + Quality.SNATCHED)
sql_results1 += more_sql_results
more_sql_results = myDB.select("SELECT *, 0 as localtime, tv_shows.status as show_status FROM tv_episodes, tv_shows WHERE season != 0 AND tv_shows.tvdb_id = tv_episodes.showid AND airdate < ? AND airdate >= ? AND tv_episodes.status = ? AND tv_episodes.status NOT IN ("+','.join(['?']*len(qualList))+")", [today, recently, WANTED] + qualList)
sql_results1 += more_sql_results
# sort by localtime
sorts = {
'date': (lambda x, y: cmp(x["localtime"], y["localtime"])),
'show': (lambda a, b: cmp((a["show_name"], a["localtime"]), (b["show_name"], b["localtime"]))),
'network': (lambda a, b: cmp((a["network"], a["localtime"]), (b["network"], b["localtime"]))),
}
# make a dict out of the sql results
sql_results = [dict(row) for row in sql_results1]
# regex to parse time (12/24 hour format)
time_regex = re.compile(r"(\d{1,2}):(\d{2,2})( [PA]M)?\b", flags=re.IGNORECASE)
# add localtime to the dict
for index, item in enumerate(sql_results1):
mo = time_regex.search(item['airs'])
if mo != None and len(mo.groups()) >= 2:
try:
hr = helpers.tryInt(mo.group(1))
m = helpers.tryInt(mo.group(2))
ap = mo.group(3)
# convert am/pm to 24 hour clock
if ap != None:
if ap.lower() == u" pm" and hr != 12:
hr += 12
elif ap.lower() == u" am" and hr == 12:
hr -= 12
except:
hr = 0
m = 0
else:
hr = 0
m = 0
if hr < 0 or hr > 23 or m < 0 or m > 59:
hr = 0
m = 0
te = datetime.datetime.fromordinal(helpers.tryInt(item['airdate']))
foreign_timezone = network_timezones.get_network_timezone(item['network'], network_dict, sb_timezone)
foreign_naive = datetime.datetime(te.year, te.month, te.day, hr, m,tzinfo=foreign_timezone)
sql_results[index]['localtime'] = foreign_naive.astimezone(sb_timezone)
#Normalize/Format the Airing Time
try:
locale.setlocale(locale.LC_TIME, 'us_US')
sql_results[index]['localtime_string'] = sql_results[index]['localtime'].strftime("%A %H:%M %p")
locale.setlocale(locale.LC_ALL, '') #Reseting to default locale
except:
sql_results[index]['localtime_string'] = sql_results[index]['localtime'].strftime("%A %H:%M %p")
sql_results.sort(sorts[sickbeard.COMING_EPS_SORT])
t = PageTemplate(file="comingEpisodes.tmpl")
# paused_item = { 'title': '', 'path': 'toggleComingEpsDisplayPaused' }
# paused_item['title'] = 'Hide Paused' if sickbeard.COMING_EPS_DISPLAY_PAUSED else 'Show Paused'
paused_item = { 'title': 'View Paused:', 'path': {'': ''} }
paused_item['path'] = {'Hide': 'toggleComingEpsDisplayPaused'} if sickbeard.COMING_EPS_DISPLAY_PAUSED else {'Show': 'toggleComingEpsDisplayPaused'}
t.submenu = [
{ 'title': 'Sort by:', 'path': {'Date': 'setComingEpsSort/?sort=date',
'Show': 'setComingEpsSort/?sort=show',
'Network': 'setComingEpsSort/?sort=network',
}},
{ 'title': 'Layout:', 'path': {'Banner': 'setComingEpsLayout/?layout=banner',
'Poster': 'setComingEpsLayout/?layout=poster',
'List': 'setComingEpsLayout/?layout=list',
}},
paused_item,
]
t.next_week = datetime.datetime.combine(next_week1, datetime.time(tzinfo=sb_timezone))
t.today = datetime.datetime.now().replace(tzinfo=sb_timezone)
t.sql_results = sql_results
# Allow local overriding of layout parameter
if layout and layout in ('poster', 'banner', 'list'):
t.layout = layout
else:
t.layout = sickbeard.COMING_EPS_LAYOUT
return _munge(t)
# Raw iCalendar implementation by Pedro Jose Pereira Vieito (@pvieito).
#
# iCalendar (iCal) - Standard RFC 5545 <http://tools.ietf.org/html/rfc5546>
# Works with iCloud, Google Calendar and Outlook.
@cherrypy.expose
def calendar(self):
""" Provides a subscribeable URL for iCal subscriptions
"""
logger.log(u"Receiving iCal request from %s" % cherrypy.request.remote.ip)
poster_url = cherrypy.url().replace('ical', '')
time_re = re.compile('([0-9]{1,2})\:([0-9]{2})(\ |)([AM|am|PM|pm]{2})')
# Create a iCal string
ical = 'BEGIN:VCALENDAR\n'
ical += 'VERSION:2.0\n'
ical += 'PRODID://Sick-Beard Upcoming Episodes//\n'
# Get shows info
myDB = db.DBConnection()
# Limit dates
past_date = (datetime.date.today() + datetime.timedelta(weeks=-2)).toordinal()
future_date = (datetime.date.today() + datetime.timedelta(weeks=52)).toordinal()
# Get all the shows that are not paused and are currently on air (from kjoconnor Fork)
calendar_shows = myDB.select("SELECT show_name, tvdb_id, network, airs, runtime FROM tv_shows WHERE status = 'Continuing' AND paused != '1'")
for show in calendar_shows:
# Get all episodes of this show airing between today and next month
episode_list = myDB.select("SELECT tvdbid, name, season, episode, description, airdate FROM tv_episodes WHERE airdate >= ? AND airdate < ? AND showid = ?", (past_date, future_date, int(show["tvdb_id"])))
# Get local timezone and load network timezones
local_zone = tz.tzlocal()
try:
network_zone = network_timezones.get_network_timezone(show['network'], network_timezones.load_network_dict(), local_zone)
except:
# Dummy network_zone for exceptions
network_zone = None
for episode in episode_list:
# Get the air date and time
air_date = datetime.datetime.fromordinal(int(episode['airdate']))
air_time = re.compile('([0-9]{1,2})\:([0-9]{2})(\ |)([AM|am|PM|pm]{2})').search(show["airs"])
# Parse out the air time
try:
if (air_time.group(4).lower() == 'pm' and int(air_time.group(1)) == 12):
t = datetime.time(12, int(air_time.group(2)), 0, tzinfo=network_zone)
elif (air_time.group(4).lower() == 'pm'):
t = datetime.time((int(air_time.group(1)) + 12), int(air_time.group(2)), 0, tzinfo=network_zone)
elif (air_time.group(4).lower() == 'am' and int(air_time.group(1)) == 12):
t = datetime.time(0, int(air_time.group(2)), 0, tzinfo=network_zone)
else:
t = datetime.time(int(air_time.group(1)), int(air_time.group(2)), 0, tzinfo=network_zone)
except:
# Dummy time for exceptions
t = datetime.time(22, 0, 0, tzinfo=network_zone)
# Combine air time and air date into one datetime object
air_date_time = datetime.datetime.combine(air_date, t).astimezone(local_zone)
# Create event for episode
ical = ical + 'BEGIN:VEVENT\n'
ical = ical + 'DTSTART:' + str(air_date_time.date()).replace("-", "") + '\n'
ical = ical + 'SUMMARY:' + show['show_name'] + ': ' + episode['name'] + '\n'
ical = ical + 'UID:' + str(datetime.date.today().isoformat()) + '-' + str(random.randint(10000,99999)) + '@Sick-Beard\n'
if (episode['description'] != ''):
ical = ical + 'DESCRIPTION:' + show['airs'] + ' on ' + show['network'] + '\\n\\n' + episode['description'] + '\n'
else:
ical = ical + 'DESCRIPTION:' + show['airs'] + ' on ' + show['network'] + '\n'
ical = ical + 'LOCATION:' + 'Episode ' + str(episode['episode']) + ' - Season ' + str(episode['season']) + '\n'
ical = ical + 'END:VEVENT\n'
# Ending the iCal
ical += 'END:VCALENDAR\n'
return ical
manage = Manage()
history = History()
config = Config()
home = Home()
api = Api()
browser = browser.WebFileBrowser()
errorlogs = ErrorLogs()
ui = UI()
| {
"content_hash": "5be9870a15847e379879c4f531847a58",
"timestamp": "",
"source": "github",
"line_count": 4025,
"max_line_length": 565,
"avg_line_length": 38.46608695652174,
"alnum_prop": 0.5864389701988039,
"repo_name": "Branlala/docker-sickbeardfr",
"id": "c11bf938b14614a77ff0293e6be3bc0d034596a4",
"size": "155575",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "sickbeard/sickbeard/webserve.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "83278"
},
{
"name": "CSS",
"bytes": "155616"
},
{
"name": "JavaScript",
"bytes": "248414"
},
{
"name": "Python",
"bytes": "8146521"
},
{
"name": "Ruby",
"bytes": "2461"
},
{
"name": "Shell",
"bytes": "8791"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Thu Dec 05 05:02:11 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.config.SingletonSupplier (BOM: * : All 2.6.0.Final API)</title>
<meta name="date" content="2019-12-05">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.wildfly.swarm.config.SingletonSupplier (BOM: * : All 2.6.0.Final API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/config/SingletonSupplier.html" title="interface in org.wildfly.swarm.config">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/class-use/SingletonSupplier.html" target="_top">Frames</a></li>
<li><a href="SingletonSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.config.SingletonSupplier" class="title">Uses of Interface<br>org.wildfly.swarm.config.SingletonSupplier</h2>
</div>
<div class="classUseContainer">No usage of org.wildfly.swarm.config.SingletonSupplier</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/config/SingletonSupplier.html" title="interface in org.wildfly.swarm.config">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/class-use/SingletonSupplier.html" target="_top">Frames</a></li>
<li><a href="SingletonSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "776c5382ea98f5d00f285aa327fb1f83",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 155,
"avg_line_length": 37.9765625,
"alnum_prop": 0.619214153466365,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "c33f0cd2dabe70a35984811be9a528cc0efaf9eb",
"size": "4861",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.6.0.Final/apidocs/org/wildfly/swarm/config/class-use/SingletonSupplier.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
/**
* ScenarioRepository.php
* 2013 Petr Dvorak, petr-dvorak.cz / 10.4.13 22:52
*/
namespace ITILSimulator\Repositories\Training;
use ITILSimulator\Repositories\BaseRepository;
/**
* Scenario repository.
* @package ITILSimulator\Repositories\Training
*/
class ScenarioRepository extends BaseRepository
{
} | {
"content_hash": "2efa55ac6507385d2441d5388c86c5f7",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 51,
"avg_line_length": 16.94736842105263,
"alnum_prop": 0.7608695652173914,
"repo_name": "petrolep/itilsimulator",
"id": "a9976f55fbbdaf7a24bafe395f91f0ee345e158f",
"size": "322",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/app/model/Repositories/Training/ScenarioRepository.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "1336953"
},
{
"name": "PHP",
"bytes": "697825"
},
{
"name": "Shell",
"bytes": "68"
}
],
"symlink_target": ""
} |
gem 'minitest'
require 'redis'
require 'redisabel'
require 'minitest/autorun'
path = File.dirname(__FILE__)
Dir.open(path).select{ |f| f =~ /spec/ }.each do |f|
load path + '/' + f.to_s
end
| {
"content_hash": "0b75b22308bddae16da5183cfe4271a5",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 52,
"avg_line_length": 19.4,
"alnum_prop": 0.6443298969072165,
"repo_name": "matthias-geier/redisabel",
"id": "1baae2d716779bf5ee19d7a8dfce5ee7705cc40d",
"size": "194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_runner.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ruby",
"bytes": "30677"
}
],
"symlink_target": ""
} |
package com.netflix.curator.framework.imps;
import com.netflix.curator.framework.api.CuratorWatcher;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
class NamespaceWatcher implements Watcher
{
private final CuratorFrameworkImpl client;
private final Watcher actualWatcher;
private final CuratorWatcher curatorWatcher;
NamespaceWatcher(CuratorFrameworkImpl client, Watcher actualWatcher)
{
this.client = client;
this.actualWatcher = actualWatcher;
this.curatorWatcher = null;
}
NamespaceWatcher(CuratorFrameworkImpl client, CuratorWatcher curatorWatcher)
{
this.client = client;
this.actualWatcher = null;
this.curatorWatcher = curatorWatcher;
}
@Override
public void process(WatchedEvent event)
{
if ( actualWatcher != null )
{
actualWatcher.process(new NamespaceWatchedEvent(client, event));
}
else if ( curatorWatcher != null )
{
try
{
curatorWatcher.process(new NamespaceWatchedEvent(client, event));
}
catch ( Exception e )
{
client.logError("Watcher exception", e);
}
}
}
}
| {
"content_hash": "efd640952389ab62ab2c89ea0d9f1c3f",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 81,
"avg_line_length": 26.6875,
"alnum_prop": 0.6362217017954723,
"repo_name": "box/curator",
"id": "3f1752fdf0011d87ab987635bde2d5a12a916bdb",
"size": "1920",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "curator-framework/src/main/java/com/netflix/curator/framework/imps/NamespaceWatcher.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.ignite.internal.processors.cache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.binary.BinaryObject;
import org.apache.ignite.cache.affinity.AffinityFunction;
import org.apache.ignite.cache.affinity.AffinityKeyMapper;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.internal.IgniteClientDisconnectedCheckedException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.processors.affinity.AffinityAssignment;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.affinity.GridAffinityAssignmentCache;
import org.apache.ignite.internal.util.GridLeanSet;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.lang.IgniteFuture;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* Cache affinity manager.
*/
public class GridCacheAffinityManager extends GridCacheManagerAdapter {
/** */
private static final AffinityTopologyVersion LOC_CACHE_TOP_VER = new AffinityTopologyVersion(1);
/** */
private static final String FAILED_TO_FIND_CACHE_ERR_MSG = "Failed to find cache (cache was not started " +
"yet or cache was already stopped): ";
/** Affinity cached function. */
private GridAffinityAssignmentCache aff;
/** */
private AffinityFunction affFunction;
/** */
private AffinityKeyMapper affMapper;
/** {@inheritDoc} */
@Override public void start0() throws IgniteCheckedException {
affFunction = cctx.config().getAffinity();
affMapper = cctx.config().getAffinityMapper();
aff = new GridAffinityAssignmentCache(cctx.kernalContext(),
cctx.namex(),
affFunction,
cctx.config().getNodeFilter(),
cctx.config().getBackups(),
cctx.isLocal());
}
/** {@inheritDoc} */
@Override protected void onKernalStart0() throws IgniteCheckedException {
if (cctx.isLocal())
// No discovery event needed for local affinity.
aff.calculate(LOC_CACHE_TOP_VER, null);
}
/** {@inheritDoc} */
@Override protected void onKernalStop0(boolean cancel) {
cancelFutures();
}
/**
*
*/
public void cancelFutures() {
IgniteCheckedException err =
new IgniteCheckedException("Failed to wait for topology update, cache (or node) is stopping.");
aff.cancelFutures(err);
}
/** {@inheritDoc} */
@Override public void onDisconnected(IgniteFuture reconnectFut) {
IgniteCheckedException err = new IgniteClientDisconnectedCheckedException(reconnectFut,
"Failed to wait for topology update, client disconnected.");
aff.cancelFutures(err);
}
/**
*
*/
public void onReconnected() {
aff.onReconnected();
}
/** {@inheritDoc} */
@Override protected void stop0(boolean cancel) {
aff = null;
}
/**
* Gets affinity ready future, a future that will be completed after affinity with given
* topology version is calculated.
*
* @param topVer Topology version to wait.
* @return Affinity ready future.
*/
public IgniteInternalFuture<AffinityTopologyVersion> affinityReadyFuture(long topVer) {
return affinityReadyFuture(new AffinityTopologyVersion(topVer));
}
/**
* Gets affinity ready future, a future that will be completed after affinity with given
* topology version is calculated.
*
* @param topVer Topology version to wait.
* @return Affinity ready future.
*/
public IgniteInternalFuture<AffinityTopologyVersion> affinityReadyFuture(AffinityTopologyVersion topVer) {
assert !cctx.isLocal();
IgniteInternalFuture<AffinityTopologyVersion> fut = aff.readyFuture(topVer);
return fut != null ? fut : new GridFinishedFuture<>(topVer);
}
/**
* Gets affinity ready future that will be completed after affinity with given topology version is calculated.
* Will return {@code null} if topology with given version is ready by the moment method is invoked.
*
* @param topVer Topology version to wait.
* @return Affinity ready future or {@code null}.
*/
@Nullable public IgniteInternalFuture<AffinityTopologyVersion> affinityReadyFuturex(AffinityTopologyVersion topVer) {
assert !cctx.isLocal();
return aff.readyFuture(topVer);
}
/**
* @param topVer Topology version.
* @return Affinity assignments.
*/
public List<List<ClusterNode>> assignments(AffinityTopologyVersion topVer) {
if (cctx.isLocal())
topVer = LOC_CACHE_TOP_VER;
return aff.assignments(topVer);
}
/**
* @return Assignment.
*/
public List<List<ClusterNode>> idealAssignment() {
assert !cctx.isLocal();
return aff.idealAssignment();
}
/**
* @return Partition count.
*/
public int partitions() {
GridAffinityAssignmentCache aff0 = aff;
if (aff0 == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
return aff0.partitions();
}
/**
* @param key Key.
* @return Partition.
*/
public int partition(Object key) {
return partition(key, true);
}
/**
* NOTE: Use this method always when you need to calculate partition id for
* a key provided by user. It's required since we should apply affinity mapper
* logic in order to find a key that will eventually be passed to affinity function.
*
* @param key Key.
* @param useKeyPart If {@code true} can use pre-calculated partition stored in KeyCacheObject.
* @return Partition.
*/
public int partition(Object key, boolean useKeyPart) {
GridAffinityAssignmentCache aff0 = aff;
if (aff0 == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
if (useKeyPart && (key instanceof KeyCacheObject)) {
int part = ((KeyCacheObject)key).partition();
if (part != -1)
return part;
}
return affFunction.partition(affinityKey(key));
}
/**
* If Key is {@link GridCacheInternal GridCacheInternal} entry when won't passed into user's mapper and
* will use {@link GridCacheDefaultAffinityKeyMapper default}.
*
* @param key Key.
* @return Affinity key.
*/
public Object affinityKey(Object key) {
if (key instanceof CacheObject && !(key instanceof BinaryObject))
key = ((CacheObject)key).value(cctx.cacheObjectContext(), false);
return (key instanceof GridCacheInternal ? cctx.defaultAffMapper() : affMapper).affinityKey(key);
}
/**
* @param key Key.
* @param topVer Topology version.
* @return Affinity nodes.
*/
public List<ClusterNode> nodesByKey(Object key, AffinityTopologyVersion topVer) {
return nodesByPartition(partition(key), topVer);
}
/**
* @param part Partition.
* @param topVer Topology version.
* @return Affinity nodes.
*/
public List<ClusterNode> nodesByPartition(int part, AffinityTopologyVersion topVer) {
if (cctx.isLocal())
topVer = LOC_CACHE_TOP_VER;
GridAffinityAssignmentCache aff0 = aff;
if (aff0 == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
return aff0.nodes(part, topVer);
}
/**
* Get affinity assignment for the given topology version.
*
* @param topVer Topology version.
* @return Affinity assignment.
*/
public AffinityAssignment assignment(AffinityTopologyVersion topVer) {
if (cctx.isLocal())
topVer = LOC_CACHE_TOP_VER;
GridAffinityAssignmentCache aff0 = aff;
if (aff0 == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
return aff0.cachedAffinity(topVer);
}
/**
* @param key Key to check.
* @param topVer Topology version.
* @return Primary node for given key.
*/
@Nullable public ClusterNode primaryByKey(Object key, AffinityTopologyVersion topVer) {
return primaryByPartition(partition(key), topVer);
}
/**
* @param part Partition.
* @param topVer Topology version.
* @return Primary node for given key.
*/
@Nullable public ClusterNode primaryByPartition(int part, AffinityTopologyVersion topVer) {
List<ClusterNode> nodes = nodesByPartition(part, topVer);
if (nodes.isEmpty())
return null;
return nodes.get(0);
}
/**
* @param n Node to check.
* @param key Key to check.
* @param topVer Topology version.
* @return {@code True} if checked node is primary for given key.
*/
public boolean primaryByKey(ClusterNode n, Object key, AffinityTopologyVersion topVer) {
return F.eq(primaryByKey(key, topVer), n);
}
/**
* @param n Node to check.
* @param part Partition.
* @param topVer Topology version.
* @return {@code True} if checked node is primary for given partition.
*/
public boolean primaryByPartition(ClusterNode n, int part, AffinityTopologyVersion topVer) {
return F.eq(primaryByPartition(part, topVer), n);
}
/**
* @param key Key to check.
* @param topVer Topology version.
* @return Backup nodes.
*/
public Collection<ClusterNode> backupsByKey(Object key, AffinityTopologyVersion topVer) {
return backupsByPartition(partition(key), topVer);
}
/**
* @param part Partition.
* @param topVer Topology version.
* @return Backup nodes.
*/
private Collection<ClusterNode> backupsByPartition(int part, AffinityTopologyVersion topVer) {
List<ClusterNode> nodes = nodesByPartition(part, topVer);
assert !F.isEmpty(nodes);
if (nodes.size() == 1)
return Collections.emptyList();
return F.view(nodes, F.notEqualTo(nodes.get(0)));
}
/**
* @param n Node to check.
* @param part Partition.
* @param topVer Topology version.
* @return {@code True} if checked node is a backup node for given partition.
*/
public boolean backupByPartition(ClusterNode n, int part, AffinityTopologyVersion topVer) {
List<ClusterNode> nodes = nodesByPartition(part, topVer);
assert !F.isEmpty(nodes);
return nodes.indexOf(n) > 0;
}
/**
* @param key Key to check.
* @param topVer Topology version.
* @return {@code true} if given key belongs to local node.
*/
public boolean keyLocalNode(Object key, AffinityTopologyVersion topVer) {
return partitionLocalNode(partition(key), topVer);
}
/**
* @param part Partition number to check.
* @param topVer Topology version.
* @return {@code true} if given partition belongs to local node.
*/
public boolean partitionLocalNode(int part, AffinityTopologyVersion topVer) {
assert part >= 0 : "Invalid partition: " + part;
return nodesByPartition(part, topVer).contains(cctx.localNode());
}
/**
* @param node Node.
* @param part Partition number to check.
* @param topVer Topology version.
* @return {@code true} if given partition belongs to specified node.
*/
public boolean partitionBelongs(ClusterNode node, int part, AffinityTopologyVersion topVer) {
assert node != null;
assert part >= 0 : "Invalid partition: " + part;
return nodesByPartition(part, topVer).contains(node);
}
/**
* @param nodeId Node ID.
* @param topVer Topology version to calculate affinity.
* @return Partitions for which given node is primary.
*/
public Set<Integer> primaryPartitions(UUID nodeId, AffinityTopologyVersion topVer) {
if (cctx.isLocal())
topVer = LOC_CACHE_TOP_VER;
GridAffinityAssignmentCache aff0 = aff;
if (aff0 == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
return aff0.primaryPartitions(nodeId, topVer);
}
/**
* @param nodeId Node ID.
* @param topVer Topology version to calculate affinity.
* @return Partitions for which given node is backup.
*/
public Set<Integer> backupPartitions(UUID nodeId, AffinityTopologyVersion topVer) {
if (cctx.isLocal())
topVer = LOC_CACHE_TOP_VER;
GridAffinityAssignmentCache aff0 = aff;
if (aff0 == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
return aff0.backupPartitions(nodeId, topVer);
}
/**
* @return Affinity-ready topology version.
*/
public AffinityTopologyVersion affinityTopologyVersion() {
GridAffinityAssignmentCache aff0 = aff;
if (aff0 == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
return aff0.lastVersion();
}
/**
* Dumps debug information.
*/
public void dumpDebugInfo() {
GridAffinityAssignmentCache aff0 = aff;
if (aff0 != null)
aff0.dumpDebugInfo();
}
/**
* @return Affinity cache.
*/
public GridAffinityAssignmentCache affinityCache() {
return aff;
}
/**
* @param part Partition.
* @param startVer Start version.
* @param endVer End version.
* @return {@code True} if primary changed or required affinity version not found in history.
*/
public boolean primaryChanged(int part, AffinityTopologyVersion startVer, AffinityTopologyVersion endVer) {
assert !cctx.isLocal() : cctx.name();
GridAffinityAssignmentCache aff0 = aff;
if (aff0 == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
return aff0.primaryChanged(part, startVer, endVer);
}
}
| {
"content_hash": "7dba3a6077d5821662594cadc86de352",
"timestamp": "",
"source": "github",
"line_count": 459,
"max_line_length": 121,
"avg_line_length": 31.296296296296298,
"alnum_prop": 0.6515837104072398,
"repo_name": "vldpyatkov/ignite",
"id": "d85e76e2bbd82ad1812f1dfb13410825a175bbae",
"size": "15167",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAffinityManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "41054"
},
{
"name": "C",
"bytes": "7504"
},
{
"name": "C#",
"bytes": "4484446"
},
{
"name": "C++",
"bytes": "2354759"
},
{
"name": "CSS",
"bytes": "110872"
},
{
"name": "Groovy",
"bytes": "15092"
},
{
"name": "HTML",
"bytes": "497146"
},
{
"name": "Java",
"bytes": "25766360"
},
{
"name": "JavaScript",
"bytes": "1075745"
},
{
"name": "M4",
"bytes": "5568"
},
{
"name": "Makefile",
"bytes": "102786"
},
{
"name": "Nginx",
"bytes": "3468"
},
{
"name": "PHP",
"bytes": "11079"
},
{
"name": "PowerShell",
"bytes": "13480"
},
{
"name": "Scala",
"bytes": "682934"
},
{
"name": "Shell",
"bytes": "586345"
},
{
"name": "Smalltalk",
"bytes": "1908"
}
],
"symlink_target": ""
} |
/*
* Spanning tree protocol; timer-related code
* Linux ethernet bridge
*
* Authors:
* Lennert Buytenhek <buytenh@gnu.org>
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/times.h>
#include "br_private.h"
#include "br_private_stp.h"
/* called under bridge lock */
static int br_is_designated_for_some_port(const struct net_bridge *br)
{
struct net_bridge_port *p;
list_for_each_entry(p, &br->port_list, list) {
if (p->state != BR_STATE_DISABLED &&
!memcmp(&p->designated_bridge, &br->bridge_id, 8))
return 1;
}
return 0;
}
static void br_hello_timer_expired(unsigned long arg)
{
struct net_bridge *br = (struct net_bridge *)arg;
br_debug(br, "hello timer expired\n");
spin_lock(&br->lock);
if (br->dev->flags & IFF_UP) {
br_config_bpdu_generation(br);
mod_timer(&br->hello_timer, round_jiffies(jiffies + br->hello_time));
}
spin_unlock(&br->lock);
}
static void br_message_age_timer_expired(unsigned long arg)
{
struct net_bridge_port *p = (struct net_bridge_port *) arg;
struct net_bridge *br = p->br;
const bridge_id *id = &p->designated_bridge;
int was_root;
if (p->state == BR_STATE_DISABLED)
return;
br_info(br, "port %u(%s) neighbor %.2x%.2x.%pM lost\n",
(unsigned int) p->port_no, p->dev->name,
id->prio[0], id->prio[1], &id->addr);
/*
* According to the spec, the message age timer cannot be
* running when we are the root bridge. So.. this was_root
* check is redundant. I'm leaving it in for now, though.
*/
spin_lock(&br->lock);
if (p->state == BR_STATE_DISABLED)
goto unlock;
was_root = br_is_root_bridge(br);
br_become_designated_port(p);
br_configuration_update(br);
br_port_state_selection(br);
if (br_is_root_bridge(br) && !was_root)
br_become_root_bridge(br);
unlock:
spin_unlock(&br->lock);
}
static void br_forward_delay_timer_expired(unsigned long arg)
{
struct net_bridge_port *p = (struct net_bridge_port *) arg;
struct net_bridge *br = p->br;
br_debug(br, "port %u(%s) forward delay timer\n",
(unsigned int) p->port_no, p->dev->name);
spin_lock(&br->lock);
if (p->state == BR_STATE_LISTENING) {
p->state = BR_STATE_LEARNING;
mod_timer(&p->forward_delay_timer,
jiffies + br->forward_delay);
} else if (p->state == BR_STATE_LEARNING) {
p->state = BR_STATE_FORWARDING;
if (br_is_designated_for_some_port(br))
br_topology_change_detection(br);
netif_carrier_on(br->dev);
}
br_log_state(p);
br_ifinfo_notify(RTM_NEWLINK, p);
spin_unlock(&br->lock);
}
static void br_tcn_timer_expired(unsigned long arg)
{
struct net_bridge *br = (struct net_bridge *) arg;
br_debug(br, "tcn timer expired\n");
spin_lock(&br->lock);
if (!br_is_root_bridge(br) && (br->dev->flags & IFF_UP)) {
br_transmit_tcn(br);
mod_timer(&br->tcn_timer,jiffies + br->bridge_hello_time);
}
spin_unlock(&br->lock);
}
static void br_topology_change_timer_expired(unsigned long arg)
{
struct net_bridge *br = (struct net_bridge *) arg;
br_debug(br, "topo change timer expired\n");
spin_lock(&br->lock);
br->topology_change_detected = 0;
br->topology_change = 0;
spin_unlock(&br->lock);
}
static void br_hold_timer_expired(unsigned long arg)
{
struct net_bridge_port *p = (struct net_bridge_port *) arg;
br_debug(p->br, "port %u(%s) hold timer expired\n",
(unsigned int) p->port_no, p->dev->name);
spin_lock(&p->br->lock);
if (p->config_pending)
br_transmit_config(p);
spin_unlock(&p->br->lock);
}
void br_stp_timer_init(struct net_bridge *br)
{
setup_timer(&br->hello_timer, br_hello_timer_expired,
(unsigned long) br);
setup_timer(&br->tcn_timer, br_tcn_timer_expired,
(unsigned long) br);
setup_timer(&br->topology_change_timer,
br_topology_change_timer_expired,
(unsigned long) br);
setup_timer(&br->gc_timer, br_fdb_cleanup, (unsigned long) br);
}
void br_stp_port_timer_init(struct net_bridge_port *p)
{
setup_timer(&p->message_age_timer, br_message_age_timer_expired,
(unsigned long) p);
setup_timer(&p->forward_delay_timer, br_forward_delay_timer_expired,
(unsigned long) p);
setup_timer(&p->hold_timer, br_hold_timer_expired,
(unsigned long) p);
}
/* Report ticks left (in USER_HZ) used for API */
unsigned long br_timer_value(const struct timer_list *timer)
{
return timer_pending(timer)
? jiffies_to_clock_t(timer->expires - jiffies) : 0;
}
| {
"content_hash": "e8573275388c446851f27678010fd8cb",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 71,
"avg_line_length": 26.45977011494253,
"alnum_prop": 0.6681146828844483,
"repo_name": "endplay/omniplay",
"id": "acc63a4d91884bedc8b87970a7dfc43754d8acb1",
"size": "4604",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "linux-lts-quantal-3.5.0/net/bridge/br_stp_timer.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "4528"
},
{
"name": "Assembly",
"bytes": "17491433"
},
{
"name": "Awk",
"bytes": "79791"
},
{
"name": "Batchfile",
"bytes": "903"
},
{
"name": "C",
"bytes": "444772157"
},
{
"name": "C++",
"bytes": "10631343"
},
{
"name": "GDB",
"bytes": "17950"
},
{
"name": "HTML",
"bytes": "47935"
},
{
"name": "Java",
"bytes": "2193"
},
{
"name": "Lex",
"bytes": "44513"
},
{
"name": "M4",
"bytes": "9029"
},
{
"name": "Makefile",
"bytes": "1758605"
},
{
"name": "Objective-C",
"bytes": "5278898"
},
{
"name": "Perl",
"bytes": "649746"
},
{
"name": "Perl 6",
"bytes": "1101"
},
{
"name": "Python",
"bytes": "585875"
},
{
"name": "RPC",
"bytes": "97869"
},
{
"name": "Roff",
"bytes": "2522798"
},
{
"name": "Scilab",
"bytes": "21433"
},
{
"name": "Shell",
"bytes": "426172"
},
{
"name": "TeX",
"bytes": "283872"
},
{
"name": "UnrealScript",
"bytes": "6143"
},
{
"name": "XS",
"bytes": "1240"
},
{
"name": "Yacc",
"bytes": "93190"
},
{
"name": "sed",
"bytes": "9202"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "ba7525031da2c04b1d99ff1c7359f2ef",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "60f0ff2e212708dd2020aee3f1c6a779481b0e0f",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Dipsacales/Dipsacaceae/Trichera/Trichera indivisa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/detail/xml_parser_error.hpp>
#include <boost/property_tree/detail/xml_parser_flags.hpp>
#include <boost/property_tree/detail/xml_parser_utils.hpp>
#include <boost/property_tree/detail/rapidxml.hpp>
#include <vector>
namespace boost { namespace property_tree { namespace xml_parser
{
template<class Ptree, class Ch>
void read_xml_node(detail::rapidxml::xml_node<Ch> *node,
Ptree &pt, int flags)
{
using namespace detail::rapidxml;
switch (node->type())
{
// Element nodes
case node_element:
{
// Create node
Ptree &pt_node = pt.push_back(std::make_pair(node->name(),
Ptree()))->second;
// Copy attributes
if (node->first_attribute())
{
Ptree &pt_attr_root = pt_node.push_back(
std::make_pair(xmlattr<Ch>(), Ptree()))->second;
for (xml_attribute<Ch> *attr = node->first_attribute();
attr; attr = attr->next_attribute())
{
Ptree &pt_attr = pt_attr_root.push_back(
std::make_pair(attr->name(), Ptree()))->second;
pt_attr.data() = attr->value();
}
}
// Copy children
for (xml_node<Ch> *child = node->first_node();
child; child = child->next_sibling())
read_xml_node(child, pt_node, flags);
}
break;
// Data nodes
case node_data:
case node_cdata:
{
if (flags & no_concat_text)
pt.push_back(std::make_pair(xmltext<Ch>(),
Ptree(node->value())));
else
pt.data() += node->value();
}
break;
// Comment nodes
case node_comment:
{
if (!(flags & no_comments))
pt.push_back(std::make_pair(xmlcomment<Ch>(),
Ptree(node->value())));
}
break;
default:
// Skip other node types
break;
}
}
template<class Ptree>
void read_xml_internal(std::basic_istream<
typename Ptree::key_type::value_type> &stream,
Ptree &pt,
int flags,
const std::string &filename)
{
typedef typename Ptree::key_type::value_type Ch;
using namespace detail::rapidxml;
// Load data into vector
stream.unsetf(std::ios::skipws);
std::vector<Ch> v(std::istreambuf_iterator<Ch>(stream.rdbuf()),
std::istreambuf_iterator<Ch>());
if (!stream.good())
BOOST_PROPERTY_TREE_THROW(
xml_parser_error("read error", filename, 0));
v.push_back(0); // zero-terminate
try {
// Parse using appropriate flags
const int f_tws = parse_normalize_whitespace
| parse_trim_whitespace;
const int f_c = parse_comment_nodes;
// Some compilers don't like the bitwise or in the template arg.
const int f_tws_c = parse_normalize_whitespace
| parse_trim_whitespace
| parse_comment_nodes;
xml_document<Ch> doc;
if (flags & no_comments) {
if (flags & trim_whitespace)
doc.BOOST_NESTED_TEMPLATE parse<f_tws>(&v.front());
else
doc.BOOST_NESTED_TEMPLATE parse<0>(&v.front());
} else {
if (flags & trim_whitespace)
doc.BOOST_NESTED_TEMPLATE parse<f_tws_c>(&v.front());
else
doc.BOOST_NESTED_TEMPLATE parse<f_c>(&v.front());
}
// Create ptree from nodes
Ptree local;
for (xml_node<Ch> *child = doc.first_node();
child; child = child->next_sibling())
read_xml_node(child, local, flags);
// Swap local and result ptrees
pt.swap(local);
} catch (parse_error &e) {
long line = static_cast<long>(
std::count(&v.front(), e.where<Ch>(), Ch('\n')) + 1);
BOOST_PROPERTY_TREE_THROW(
xml_parser_error(e.what(), filename, line));
}
}
} } }
#endif
| {
"content_hash": "3fb0999bb2f81d5fb0215d9d1caf831a",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 79,
"avg_line_length": 37.32330827067669,
"alnum_prop": 0.4425866236905721,
"repo_name": "miho/iNumerics",
"id": "d4997aecf0882220e7430445fd4a6f4e50e51bfd",
"size": "5528",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "odeint/boost/property_tree/detail/xml_parser_read_rapidxml.hpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "26194"
},
{
"name": "C++",
"bytes": "85019775"
},
{
"name": "Objective-C",
"bytes": "2668"
},
{
"name": "Perl",
"bytes": "6275"
},
{
"name": "Shell",
"bytes": "3400"
}
],
"symlink_target": ""
} |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Authentication Plugin: Email Authentication
*
* @author Martin Dougiamas
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package auth_email
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/authlib.php');
/**
* Email authentication plugin.
*/
class auth_plugin_email extends auth_plugin_base {
/**
* Constructor.
*/
public function __construct() {
$this->authtype = 'email';
$this->config = get_config('auth_email');
}
/**
* Old syntax of class constructor. Deprecated in PHP7.
*
* @deprecated since Moodle 3.1
*/
public function auth_plugin_email() {
debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
self::__construct();
}
/**
* Returns true if the username and password work and false if they are
* wrong or don't exist.
*
* @param string $username The username
* @param string $password The password
* @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
global $CFG, $DB;
if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
return validate_internal_user_password($user, $password);
}
return false;
}
/**
* Updates the user's password.
*
* called when the user password is updated.
*
* @param object $user User table object (with system magic quotes)
* @param string $newpassword Plaintext password (with system magic quotes)
* @return boolean result
*
*/
function user_update_password($user, $newpassword) {
$user = get_complete_user_data('id', $user->id);
// This will also update the stored hash to the latest algorithm
// if the existing hash is using an out-of-date algorithm (or the
// legacy md5 algorithm).
return update_internal_user_password($user, $newpassword);
}
function can_signup() {
return true;
}
/**
* Sign up a new user ready for confirmation.
* Password is passed in plaintext.
*
* @param object $user new user object
* @param boolean $notify print notice with link and terminate
*/
function user_signup($user, $notify=true) {
// Standard signup, without custom confirmatinurl.
return $this->user_signup_with_confirmation($user, $notify);
}
/**
* Sign up a new user ready for confirmation.
*
* Password is passed in plaintext.
* A custom confirmationurl could be used.
*
* @param object $user new user object
* @param boolean $notify print notice with link and terminate
* @param string $confirmationurl user confirmation URL
* @return boolean true if everything well ok and $notify is set to true
* @throws moodle_exception
* @since Moodle 3.2
*/
public function user_signup_with_confirmation($user, $notify=true, $confirmationurl = null) {
global $CFG, $DB;
require_once($CFG->dirroot.'/user/profile/lib.php');
require_once($CFG->dirroot.'/user/lib.php');
$plainpassword = $user->password;
$user->password = hash_internal_user_password($user->password);
if (empty($user->calendartype)) {
$user->calendartype = $CFG->calendartype;
}
$user->id = user_create_user($user, false, false);
user_add_password_history($user->id, $plainpassword);
// Save any custom profile field information.
profile_save_data($user);
// Trigger event.
\core\event\user_created::create_from_userid($user->id)->trigger();
if (! send_confirmation_email($user, $confirmationurl)) {
print_error('auth_emailnoemail', 'auth_email');
}
if ($notify) {
global $CFG, $PAGE, $OUTPUT;
$emailconfirm = get_string('emailconfirm');
$PAGE->navbar->add($emailconfirm);
$PAGE->set_title($emailconfirm);
$PAGE->set_heading($PAGE->course->fullname);
echo $OUTPUT->header();
notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php");
} else {
return true;
}
}
/**
* Returns true if plugin allows confirming of new users.
*
* @return bool
*/
function can_confirm() {
return true;
}
/**
* Confirm the new user as registered.
*
* @param string $username
* @param string $confirmsecret
*/
function user_confirm($username, $confirmsecret) {
global $DB;
$user = get_complete_user_data('username', $username);
if (!empty($user)) {
if ($user->auth != $this->authtype) {
return AUTH_CONFIRM_ERROR;
} else if ($user->secret == $confirmsecret && $user->confirmed) {
return AUTH_CONFIRM_ALREADY;
} else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in
$DB->set_field("user", "confirmed", 1, array("id"=>$user->id));
return AUTH_CONFIRM_OK;
}
} else {
return AUTH_CONFIRM_ERROR;
}
}
function prevent_local_passwords() {
return false;
}
/**
* Returns true if this authentication plugin is 'internal'.
*
* @return bool
*/
function is_internal() {
return true;
}
/**
* Returns true if this authentication plugin can change the user's
* password.
*
* @return bool
*/
function can_change_password() {
return true;
}
/**
* Returns the URL for changing the user's pw, or empty if the default can
* be used.
*
* @return moodle_url
*/
function change_password_url() {
return null; // use default internal method
}
/**
* Returns true if plugin allows resetting of internal password.
*
* @return bool
*/
function can_reset_password() {
return true;
}
/**
* Returns true if plugin can be manually set.
*
* @return bool
*/
function can_be_manually_set() {
return true;
}
/**
* Returns whether or not the captcha element is enabled.
* @return bool
*/
function is_captcha_enabled() {
return get_config("auth_{$this->authtype}", 'recaptcha');
}
}
| {
"content_hash": "87b137a883528c5fb1d1f75239a87ee1",
"timestamp": "",
"source": "github",
"line_count": 249,
"max_line_length": 115,
"avg_line_length": 29.17269076305221,
"alnum_prop": 0.5931993392070485,
"repo_name": "dilawar/moodle",
"id": "f1cbc111361f0ded7ec93ad4be8500f0be19c677",
"size": "7264",
"binary": false,
"copies": "32",
"ref": "refs/heads/master",
"path": "auth/email/auth.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "11995"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ImageViewer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[]? args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));
}
}
} | {
"content_hash": "c7a54291f0c014343f6c893dfa780625",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 65,
"avg_line_length": 24.90909090909091,
"alnum_prop": 0.5948905109489051,
"repo_name": "i-e-b/ImageTools",
"id": "04f42d21330d5f7122568903d0db6beeb4058cd7",
"size": "550",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ImageViewer/Program.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "925136"
}
],
"symlink_target": ""
} |
using FluentAssertions;
using MvcBootstrapTable.Builders;
using MvcBootstrapTable.Config;
using Xunit;
namespace Test.Builders
{
public class UpdateBuilderTest
{
private readonly UpdateBuilder _builder;
private readonly UpdateConfig _config;
public UpdateBuilderTest()
{
_config = new UpdateConfig();
_builder = new UpdateBuilder(_config);
}
[Fact]
public void Url()
{
UpdateBuilder builder = _builder.Url("Url");
_config.Url.Should().Be("Url");
builder.Should().BeSameAs(_builder);
}
[Fact]
public void Start()
{
UpdateBuilder builder = _builder.Start("jsFunc");
_config.Start.Should().Be("jsFunc");
builder.Should().BeSameAs(_builder);
}
[Fact]
public void Success()
{
UpdateBuilder builder = _builder.Success("jsFunc");
_config.Success.Should().Be("jsFunc");
builder.Should().BeSameAs(_builder);
}
[Fact]
public void Error()
{
UpdateBuilder builder = _builder.Error("jsFunc");
_config.Error.Should().Be("jsFunc");
builder.Should().BeSameAs(_builder);
}
[Fact]
public void Complete()
{
UpdateBuilder builder = _builder.Complete("jsFunc");
_config.Complete.Should().Be("jsFunc");
builder.Should().BeSameAs(_builder);
}
[Fact]
public void QueryParameter()
{
UpdateBuilder builder = _builder.QueryParameter("Name", "Value");
_config.CustomQueryPars.Should().ContainKey("Name");
_config.CustomQueryPars["Name"].Should().Be("Value");
builder.Should().BeSameAs(_builder);
}
[Fact]
public void BusyIndicatorId()
{
UpdateBuilder builder = _builder.BusyIndicatorId("Id");
_config.BusyIndicatorId.Should().Be("Id");
builder.Should().BeSameAs(_builder);
}
}
}
| {
"content_hash": "7d6ee37a69149db780aec95d5fe78cb3",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 77,
"avg_line_length": 25.686746987951807,
"alnum_prop": 0.5389305816135085,
"repo_name": "Robelind/MvcBootstrapTable",
"id": "1534a04f64edae86e48c36c0ae61b1737ee8e32c",
"size": "2134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Test/Builders/UpdateBuilderTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "155024"
}
],
"symlink_target": ""
} |
import { SymbolGroup } from '../../entities/symbol-group';
import { BaseApiService } from './base-api.service';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { EnvironmentProvider } from '../../../environments/environment.provider';
/**
* The resource that handles http requests to the API to do CRUD operations on symbol groups.
*/
@Injectable()
export class SymbolGroupApiService extends BaseApiService {
constructor(private http: HttpClient, private env: EnvironmentProvider) {
super();
}
/**
* Fetches all symbol groups from the server.
*
* @param projectId The id of the project whose projects should be fetched.
*/
getAll(projectId: number): Observable<SymbolGroup[]> {
return this.http.get(`${this.env.apiUrl}/projects/${projectId}/groups`, this.defaultHttpOptions)
.pipe(
map((body: any) => body.map(g => new SymbolGroup(g)))
);
}
/**
* Creates a new symbol group.
*
* @param projectId The id of the project of the symbol group.
* @param group The object of the symbol group that should be created.
*/
create(projectId: number, group: SymbolGroup): Observable<SymbolGroup> {
return this.http.post(`${this.env.apiUrl}/projects/${projectId}/groups`, group, this.defaultHttpOptions)
.pipe(
map(body => new SymbolGroup(body))
);
}
/**
* Updates an existing symbol group.
*
* @param group The symbol group that should be updated.
*/
update(group: SymbolGroup): Observable<SymbolGroup> {
return this.http.put(`${this.env.apiUrl}/projects/${group.project}/groups/${group.id}`, group, this.defaultHttpOptions)
.pipe(
map(body => new SymbolGroup(body))
);
}
/**
* Moves an existing symbol group.
*
* @param group The symbol group to move with the new parent.
*/
move(group: SymbolGroup): Observable<any> {
return this.http.put(`${this.env.apiUrl}/projects/${group.project}/groups/${group.id}/move`, group, this.defaultHttpOptions)
.pipe(
map(body => new SymbolGroup(body))
);
}
/**
* Deletes a symbol group.
*
* @param group The symbol group that should be deleted.
*/
remove(group: SymbolGroup): Observable<any> {
return this.http.delete(`${this.env.apiUrl}/projects/${group.project}/groups/${group.id}`, this.defaultHttpOptions);
}
}
| {
"content_hash": "61cfe6b82714c1c4a4ac41e5f5866b03",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 128,
"avg_line_length": 31.743589743589745,
"alnum_prop": 0.6639741518578353,
"repo_name": "LearnLib/alex",
"id": "41a01dd60a0f6135004ed5e24a5bae852e65e43e",
"size": "3077",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "frontend/src/app/services/api/symbol-group-api.service.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1948"
},
{
"name": "Dockerfile",
"bytes": "2317"
},
{
"name": "HTML",
"bytes": "318400"
},
{
"name": "Java",
"bytes": "2197732"
},
{
"name": "JavaScript",
"bytes": "8787"
},
{
"name": "SCSS",
"bytes": "19255"
},
{
"name": "TypeScript",
"bytes": "887775"
}
],
"symlink_target": ""
} |
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2014 HackPascal <hackpascal@gmail.com>
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
$Id$
]]--
local data = {}
local ds = require "luci.dispatcher"
local ps = luci.util.execi("/bin/busybox top -bn1 | grep '/usr/sbin/pppd'")
for line in ps do
local pid, ppid, speed, gateway, vip, cip = line:match(
"^ *(%d+) +(%d+) +.+options%.pptpd +(%d+) +(%S.-%S)%:(%S.-%S) +.+ +(.+)"
)
local idx = tonumber(pid)
if idx then
data["%02i.%s" % { idx, "online" }] = {
['PID'] = pid,
['PPID'] = ppid,
['SPEED'] = speed,
['GATEWAY'] = gateway,
['VIP'] = vip,
['CIP'] = cip,
['BLACKLIST'] = 0
}
end
end
-- local ps = luci.util.execi("sed -n '/## pptpd-blacklist-/p' /etc/firewall.user")
local ps = luci.util.execi("sed = /etc/firewall.user | sed 'N;s/\\n/:/'")
for line in ps do
local idx, ip = line:match(
"^ *(%d+)%:.+%#%# pptpd%-blacklist%-(.+)"
)
local idx = tonumber(idx)
if idx then
data["%02i.%s" % { idx, "blacklist" }] = {
['PID'] = "-1",
['PPID'] = "-1",
['SPEED'] = "-1",
['GATEWAY'] = "-",
['VIP'] = "-",
['CIP'] = ip,
['BLACKLIST'] = 1
}
end
end
f = SimpleForm("processes")
f.reset = false
f.submit = false
t = f:section(Table, data, translate("Online Users"))
t:option(DummyValue, "GATEWAY", translate("Server IP"))
t:option(DummyValue, "VIP", translate("Client IP"))
t:option(DummyValue, "CIP", translate("IP address"))
blacklist = t:option(Button, "_blacklist", translate("Blacklist"))
function blacklist.render(self, section, scope)
if self.map:get(section, "BLACKLIST")==0 then
self.title = translate("Add to Blacklist")
self.inputstyle = "remove"
else
self.title = translate("Remove from Blacklist")
self.inputstyle = "apply"
end
Button.render(self, section, scope)
end
function blacklist.write(self, section)
local CIP = self.map:get(section, "CIP")
if self.map:get(section, "BLACKLIST")==0 then
luci.util.execi("echo 'iptables -A input_rule -s %s -p tcp --dport 1723 -j DROP ## pptpd-blacklist-%s' >> /etc/firewall.user" % { CIP, CIP })
luci.util.execi("iptables -A input_rule -s %s -p tcp --dport 1723 -j DROP" % { CIP })
null, self.tag_error[section] = luci.sys.process.signal(self.map:get(section, "PID"), 9)
else
luci.util.execi("sed -i -e '/## pptpd-blacklist-%s/d' /etc/firewall.user" % { CIP })
luci.util.execi("iptables -D input_rule -s %s -p tcp --dport 1723 -j DROP" % { CIP })
end
luci.http.redirect(ds.build_url("admin/services/pptpd/online"))
end
kill = t:option(Button, "_kill", translate("Forced offline"))
kill.inputstyle = "reset"
function kill.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(self.map:get(section, "PID"), 9)
luci.http.redirect(ds.build_url("admin/services/pptpd/online"))
end
return f
| {
"content_hash": "fe39862dcdc9ccafd9c10223913591fa",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 143,
"avg_line_length": 30.484848484848484,
"alnum_prop": 0.6401590457256461,
"repo_name": "mumuqz/luci",
"id": "ec9b506e13670b5e0f905b7a582cc90105d95283",
"size": "3023",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "applications/luci-app-pptpd/luasrc/model/cbi/pptpd/online.lua",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "44"
},
{
"name": "Awk",
"bytes": "526"
},
{
"name": "C",
"bytes": "1161097"
},
{
"name": "C#",
"bytes": "42820"
},
{
"name": "C++",
"bytes": "29700"
},
{
"name": "CSS",
"bytes": "73264"
},
{
"name": "HTML",
"bytes": "664617"
},
{
"name": "Java",
"bytes": "49574"
},
{
"name": "JavaScript",
"bytes": "64583"
},
{
"name": "Lex",
"bytes": "7173"
},
{
"name": "Lua",
"bytes": "1589998"
},
{
"name": "Makefile",
"bytes": "115338"
},
{
"name": "Perl",
"bytes": "47647"
},
{
"name": "Shell",
"bytes": "159046"
},
{
"name": "Visual Basic",
"bytes": "33030"
},
{
"name": "Yacc",
"bytes": "14699"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.15"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>0.9.9 API documenation: GLM_GTX_log_base</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logo-mini.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">0.9.9 API documenation
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.15 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">GLM_GTX_log_base<div class="ingroups"><a class="el" href="a00716.html">Experimental extensions</a></div></div> </div>
</div><!--header-->
<div class="contents">
<p>Include <<a class="el" href="a00521.html" title="GLM_GTX_log_base">glm/gtx/log_base.hpp</a>> to use the features of this extension.
<a href="#details">More...</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:ga60a7b0a401da660869946b2b77c710c9"><td class="memTemplParams" colspan="2">template<typename genType > </td></tr>
<tr class="memitem:ga60a7b0a401da660869946b2b77c710c9"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00761.html#ga60a7b0a401da660869946b2b77c710c9">log</a> (genType const &x, genType const &base)</td></tr>
<tr class="memdesc:ga60a7b0a401da660869946b2b77c710c9"><td class="mdescLeft"> </td><td class="mdescRight">Logarithm for any base. <a href="a00761.html#ga60a7b0a401da660869946b2b77c710c9">More...</a><br /></td></tr>
<tr class="separator:ga60a7b0a401da660869946b2b77c710c9"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga04ef803a24f3d4f8c67dbccb33b0fce0"><td class="memTemplParams" colspan="2">template<length_t L, typename T , qualifier Q> </td></tr>
<tr class="memitem:ga04ef803a24f3d4f8c67dbccb33b0fce0"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vec< L, T, Q > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00761.html#ga04ef803a24f3d4f8c67dbccb33b0fce0">sign</a> (vec< L, T, Q > const &x, vec< L, T, Q > const &base)</td></tr>
<tr class="memdesc:ga04ef803a24f3d4f8c67dbccb33b0fce0"><td class="mdescLeft"> </td><td class="mdescRight">Logarithm for any base. <a href="a00761.html#ga04ef803a24f3d4f8c67dbccb33b0fce0">More...</a><br /></td></tr>
<tr class="separator:ga04ef803a24f3d4f8c67dbccb33b0fce0"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<p>Include <<a class="el" href="a00521.html" title="GLM_GTX_log_base">glm/gtx/log_base.hpp</a>> to use the features of this extension. </p>
<p>Logarithm for any base. base can be a vector or a scalar. </p>
<h2 class="groupheader">Function Documentation</h2>
<a id="ga60a7b0a401da660869946b2b77c710c9"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ga60a7b0a401da660869946b2b77c710c9">◆ </a></span>log()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL genType glm::log </td>
<td>(</td>
<td class="paramtype">genType const & </td>
<td class="paramname"><em>x</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">genType const & </td>
<td class="paramname"><em>base</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Logarithm for any base. </p>
<p>From GLM_GTX_log_base. </p>
</div>
</div>
<a id="ga04ef803a24f3d4f8c67dbccb33b0fce0"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ga04ef803a24f3d4f8c67dbccb33b0fce0">◆ </a></span>sign()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vec<L, T, Q> glm::sign </td>
<td>(</td>
<td class="paramtype">vec< L, T, Q > const & </td>
<td class="paramname"><em>x</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">vec< L, T, Q > const & </td>
<td class="paramname"><em>base</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Logarithm for any base. </p>
<p>From GLM_GTX_log_base. </p>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.15
</small></address>
</body>
</html>
| {
"content_hash": "9fe4d1b7c1b9ac45e2452ca6d0cde3d7",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 362,
"avg_line_length": 45.28125,
"alnum_prop": 0.6535541752933057,
"repo_name": "kumakoko/KumaGL",
"id": "62ced6651da7b96debf30af6551057056fd5830b",
"size": "7245",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "third_lib/glm/0.9.9.5/share/man/html/a00761.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "763"
},
{
"name": "Batchfile",
"bytes": "1610"
},
{
"name": "C",
"bytes": "10066221"
},
{
"name": "C++",
"bytes": "122279207"
},
{
"name": "CMake",
"bytes": "32438"
},
{
"name": "CSS",
"bytes": "97842"
},
{
"name": "GLSL",
"bytes": "288465"
},
{
"name": "HTML",
"bytes": "28003047"
},
{
"name": "JavaScript",
"bytes": "512828"
},
{
"name": "M4",
"bytes": "10000"
},
{
"name": "Makefile",
"bytes": "12990"
},
{
"name": "Objective-C",
"bytes": "100340"
},
{
"name": "Objective-C++",
"bytes": "2520"
},
{
"name": "Perl",
"bytes": "6275"
},
{
"name": "Roff",
"bytes": "332021"
},
{
"name": "Ruby",
"bytes": "9186"
},
{
"name": "Shell",
"bytes": "37826"
}
],
"symlink_target": ""
} |
import json
import os
import sys, logging
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
with open(sys.argv[1]) as fhd:
lines = fhd.readlines()
while lines:
line = lines.pop(0)
if "Plugin Components:" in line.strip():
logging.debug("Found start: %s", line)
break
plugins = {}
while lines:
line = lines.pop(0)
#logging.debug(line)
if not line.strip():
break
plugins[line.strip()] = json.loads(lines.pop(0).strip()[len('"componentClasses":'):-1])
#logging.info("%s", plugins)
for fname in os.listdir(sys.argv[2]):
fname = os.path.join(sys.argv[2], fname)
logging.info(fname)
with open(fname) as fhd:
fpls = json.loads(fhd.read())
for plugin in fpls:
if plugin['id'] not in plugins or not plugin['markerClass']:
logging.warning("Missing: %s", plugin['id'])
continue
if not 'componentClasses' in plugin:
plugin['componentClasses'] = []
if set(plugin['componentClasses']) != set(plugins[plugin['id']]):
diff = json.dumps(list(set(plugins[plugin['id']]) - set(plugin['componentClasses'])))
logging.debug("Diff %s %s: %s", plugin['id'], diff, json.dumps(plugins[plugin['id']]))
| {
"content_hash": "f43f1ba57d7b5e2da3b33850f2a250ad",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 102,
"avg_line_length": 31.40909090909091,
"alnum_prop": 0.5506512301013025,
"repo_name": "undera/jmeter-plugins-manager",
"id": "dfcfad2f73602ba9e048285ce7d2edc6747740f6",
"size": "1382",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/resources/check-descriptors.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "151"
},
{
"name": "Java",
"bytes": "260324"
},
{
"name": "Python",
"bytes": "1382"
},
{
"name": "Shell",
"bytes": "295"
}
],
"symlink_target": ""
} |
function [output] = F_beamforming_gainTDOA(input_layer, curr_layer)
input = input_layer.a;
[D,T,N] = size(input);
gain = curr_layer.W; % W is a 2*nCh x nBin matrix. The first half store the real parts, the second half store the imaginary parts
TDOA = curr_layer.b;
[nCh,nBin] = size(gain);
freqBin = curr_layer.freqBin;
weight = F_tdoa2weight(TDOA(2:end), freqBin);
if isfield(curr_layer, 'useGain') && curr_layer.useGain==1
weight = bsxfun(@times, weight, gain');
end
input2 = reshape(input, nBin, nCh, T, N);
output = bsxfun(@times, input2, conj(weight));
output = squeeze(sum(output,2));
end
| {
"content_hash": "f4aa2173244947f411eedbfa409016ca",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 131,
"avg_line_length": 29.19047619047619,
"alnum_prop": 0.6867862969004894,
"repo_name": "singaxiong/SignalGraph",
"id": "3371b3640e61a30a9d6c35c727c95f5da7e1106f",
"size": "613",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "graph/obsolute/F_beamforming_gainTDOA.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "11212"
},
{
"name": "C++",
"bytes": "309"
},
{
"name": "M",
"bytes": "8974"
},
{
"name": "Mathematica",
"bytes": "2719"
},
{
"name": "Matlab",
"bytes": "2469239"
}
],
"symlink_target": ""
} |
package com.facebook.buck.android.toolchain.ndk.impl;
import com.facebook.buck.android.AndroidBuckConfig;
import com.facebook.buck.android.toolchain.ndk.AndroidNdk;
import com.facebook.buck.android.toolchain.ndk.AndroidNdkConstants;
import com.facebook.buck.android.toolchain.ndk.NdkCompilerType;
import com.facebook.buck.android.toolchain.ndk.NdkCxxPlatform;
import com.facebook.buck.android.toolchain.ndk.NdkCxxPlatformCompiler;
import com.facebook.buck.android.toolchain.ndk.NdkCxxPlatformTargetConfiguration;
import com.facebook.buck.android.toolchain.ndk.NdkCxxRuntime;
import com.facebook.buck.android.toolchain.ndk.NdkTargetArchAbi;
import com.facebook.buck.android.toolchain.ndk.TargetCpuType;
import com.facebook.buck.cxx.toolchain.ArchiverProvider;
import com.facebook.buck.cxx.toolchain.CompilerProvider;
import com.facebook.buck.cxx.toolchain.CxxBuckConfig;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.CxxToolProvider;
import com.facebook.buck.cxx.toolchain.ElfSharedLibraryInterfaceParams;
import com.facebook.buck.cxx.toolchain.GnuArchiver;
import com.facebook.buck.cxx.toolchain.HeaderVerification;
import com.facebook.buck.cxx.toolchain.MungingDebugPathSanitizer;
import com.facebook.buck.cxx.toolchain.PosixNmSymbolNameTool;
import com.facebook.buck.cxx.toolchain.PrefixMapDebugPathSanitizer;
import com.facebook.buck.cxx.toolchain.PreprocessorProvider;
import com.facebook.buck.cxx.toolchain.SharedLibraryInterfaceParams;
import com.facebook.buck.cxx.toolchain.linker.DefaultLinkerProvider;
import com.facebook.buck.cxx.toolchain.linker.GnuLinker;
import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.cxx.toolchain.linker.LinkerProvider;
import com.facebook.buck.io.ExecutableFinder;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.InternalFlavor;
import com.facebook.buck.rules.ConstantToolProvider;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.rules.ToolProvider;
import com.facebook.buck.rules.VersionedTool;
import com.facebook.buck.toolchain.ToolchainProvider;
import com.facebook.buck.util.environment.Platform;
import com.facebook.infer.annotation.Assertions;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
public class NdkCxxPlatforms {
private static final Logger LOG = Logger.get(NdkCxxPlatforms.class);
/**
* Magic string we substitute into debug paths in place of the build-host name, erasing the
* difference between say, building on Darwin and building on Linux.
*/
public static final String BUILD_HOST_SUBST = "@BUILD_HOST@";
public static final NdkCompilerType DEFAULT_COMPILER_TYPE = NdkCompilerType.GCC;
public static final String DEFAULT_TARGET_APP_PLATFORM = "android-16";
public static final ImmutableSet<String> DEFAULT_CPU_ABIS =
ImmutableSet.of("arm", "armv7", "x86");
public static final NdkCxxRuntime DEFAULT_CXX_RUNTIME = NdkCxxRuntime.GNUSTL;
private static final ImmutableMap<Platform, Host> BUILD_PLATFORMS =
ImmutableMap.of(
Platform.LINUX, Host.LINUX_X86_64,
Platform.MACOS, Host.DARWIN_X86_64,
Platform.WINDOWS, Host.WINDOWS_X86_64);
// TODO(cjhopman): Does the preprocessor need the -std= flags? Right now we don't send them.
/** Defaults for c and c++ flags */
public static final ImmutableList<String> DEFAULT_COMMON_CFLAGS =
ImmutableList.of(
// Default to the C11 standard.
"-std=gnu11");
public static final ImmutableList<String> DEFAULT_COMMON_CXXFLAGS =
ImmutableList.of(
// Default to the C++11 standard.
"-std=gnu++11", "-fno-exceptions", "-fno-rtti");
public static final ImmutableList<String> DEFAULT_COMMON_CPPFLAGS =
ImmutableList.of(
// Disable searching for headers provided by the system. This limits headers to just
// those provided by the NDK and any library dependencies.
"-nostdinc",
// Default macro definitions applied to all builds.
"-DNDEBUG",
"-DANDROID");
public static final ImmutableList<String> DEFAULT_COMMON_CXXPPFLAGS = DEFAULT_COMMON_CPPFLAGS;
/** Flags used when compiling either C or C++ sources. */
public static final ImmutableList<String> DEFAULT_COMMON_COMPILER_FLAGS =
ImmutableList.of(
// Default compiler flags provided by the NDK build makefiles.
"-ffunction-sections", "-funwind-tables", "-fomit-frame-pointer", "-fno-strict-aliasing");
/** Default linker flags added by the NDK. */
public static final ImmutableList<String> DEFAULT_COMMON_LDFLAGS =
ImmutableList.of(
// Add a deterministic build ID to Android builds.
// We use it to find symbols from arbitrary binaries.
"-Wl,--build-id",
// Enforce the NX (no execute) security feature
"-Wl,-z,noexecstack",
// Strip unused code
"-Wl,--gc-sections",
// Refuse to produce dynamic objects with undefined symbols
"-Wl,-z,defs",
// Forbid dangerous copy "relocations"
"-Wl,-z,nocopyreloc",
// We always pass the runtime library on the command line, so setting this flag
// means the resulting link will only use it if it was actually needed it.
"-Wl,--as-needed");
// Utility class, do not instantiate.
private NdkCxxPlatforms() {}
static int getNdkMajorVersion(String ndkVersion) {
return ndkVersion.startsWith("r9")
? 9
: ndkVersion.startsWith("r10")
? 10
: ndkVersion.startsWith("11.")
? 11
: ndkVersion.startsWith("12.")
? 12
: ndkVersion.startsWith("13.")
? 13
: ndkVersion.startsWith("14.")
? 14
: ndkVersion.startsWith("15.")
? 15
: ndkVersion.startsWith("16.") ? 16 : -1;
}
public static String getDefaultGccVersionForNdk(String ndkVersion) {
return getNdkMajorVersion(ndkVersion) < 11 ? "4.8" : "4.9";
}
public static String getDefaultClangVersionForNdk(String ndkVersion) {
int ndkMajorVersion = getNdkMajorVersion(ndkVersion);
if (ndkMajorVersion < 11) {
return "3.5";
} else if (ndkMajorVersion >= 15) {
return "5.0";
}
return "3.8";
}
public static boolean isSupportedConfiguration(Path ndkRoot, NdkCxxRuntime cxxRuntime) {
// TODO(12846101): With ndk r12, Android has started to use libc++abi. Buck
// needs to figure out how to support that.
String ndkVersion = readVersion(ndkRoot);
return !(cxxRuntime == NdkCxxRuntime.LIBCXX && getNdkMajorVersion(ndkVersion) >= 12);
}
public static ImmutableMap<TargetCpuType, NdkCxxPlatform> getPlatforms(
CxxBuckConfig config,
AndroidBuckConfig androidConfig,
ProjectFilesystem filesystem,
Platform platform,
ToolchainProvider toolchainProvider,
String ndkVersion) {
AndroidNdk androidNdk = toolchainProvider.getByName(AndroidNdk.DEFAULT_NAME, AndroidNdk.class);
Path ndkRoot = androidNdk.getNdkRootPath();
NdkCompilerType compilerType =
androidConfig.getNdkCompiler().orElse(NdkCxxPlatforms.DEFAULT_COMPILER_TYPE);
String gccVersion =
androidConfig
.getNdkGccVersion()
.orElse(NdkCxxPlatforms.getDefaultGccVersionForNdk(ndkVersion));
String clangVersion =
androidConfig
.getNdkClangVersion()
.orElse(NdkCxxPlatforms.getDefaultClangVersionForNdk(ndkVersion));
String compilerVersion = compilerType == NdkCompilerType.GCC ? gccVersion : clangVersion;
NdkCxxPlatformCompiler compiler =
NdkCxxPlatformCompiler.builder()
.setType(compilerType)
.setVersion(compilerVersion)
.setGccVersion(gccVersion)
.build();
return getPlatforms(
config,
androidConfig,
filesystem,
ndkRoot,
compiler,
androidConfig.getNdkCxxRuntime().orElse(NdkCxxPlatforms.DEFAULT_CXX_RUNTIME),
androidConfig.getNdkAppPlatform().orElse(NdkCxxPlatforms.DEFAULT_TARGET_APP_PLATFORM),
androidConfig.getNdkCpuAbis().orElse(NdkCxxPlatforms.DEFAULT_CPU_ABIS),
platform);
}
@VisibleForTesting
public static ImmutableMap<TargetCpuType, NdkCxxPlatform> getPlatforms(
CxxBuckConfig config,
AndroidBuckConfig androidConfig,
ProjectFilesystem filesystem,
Path ndkRoot,
NdkCxxPlatformCompiler compiler,
NdkCxxRuntime cxxRuntime,
String androidPlatform,
Set<String> cpuAbis,
Platform platform) {
return getPlatforms(
config,
androidConfig,
filesystem,
ndkRoot,
compiler,
cxxRuntime,
androidPlatform,
cpuAbis,
platform,
new ExecutableFinder(),
/* strictToolchainPaths */ true);
}
/** @return the map holding the available {@link NdkCxxPlatform}s. */
public static ImmutableMap<TargetCpuType, NdkCxxPlatform> getPlatforms(
CxxBuckConfig config,
AndroidBuckConfig androidConfig,
ProjectFilesystem filesystem,
Path ndkRoot,
NdkCxxPlatformCompiler compiler,
NdkCxxRuntime cxxRuntime,
String androidPlatform,
Set<String> cpuAbis,
Platform platform,
ExecutableFinder executableFinder,
boolean strictToolchainPaths) {
ImmutableMap.Builder<TargetCpuType, NdkCxxPlatform> ndkCxxPlatformBuilder =
ImmutableMap.builder();
// ARM Platform
if (cpuAbis.contains("arm")) {
NdkCxxPlatformTargetConfiguration targetConfiguration =
getTargetConfiguration(TargetCpuType.ARM, compiler, androidPlatform);
NdkCxxPlatform armeabi =
build(
config,
androidConfig,
filesystem,
InternalFlavor.of("android-arm"),
platform,
ndkRoot,
targetConfiguration,
cxxRuntime,
executableFinder,
strictToolchainPaths);
ndkCxxPlatformBuilder.put(TargetCpuType.ARM, armeabi);
}
// ARMv7 Platform
if (cpuAbis.contains("armv7")) {
NdkCxxPlatformTargetConfiguration targetConfiguration =
getTargetConfiguration(TargetCpuType.ARMV7, compiler, androidPlatform);
NdkCxxPlatform armeabiv7 =
build(
config,
androidConfig,
filesystem,
InternalFlavor.of("android-armv7"),
platform,
ndkRoot,
targetConfiguration,
cxxRuntime,
executableFinder,
strictToolchainPaths);
ndkCxxPlatformBuilder.put(TargetCpuType.ARMV7, armeabiv7);
}
// ARM64 Platform
if (cpuAbis.contains("arm64")) {
NdkCxxPlatformTargetConfiguration targetConfiguration =
getTargetConfiguration(TargetCpuType.ARM64, compiler, androidPlatform);
NdkCxxPlatform arm64 =
build(
config,
androidConfig,
filesystem,
InternalFlavor.of("android-arm64"),
platform,
ndkRoot,
targetConfiguration,
cxxRuntime,
executableFinder,
strictToolchainPaths);
ndkCxxPlatformBuilder.put(TargetCpuType.ARM64, arm64);
}
// x86 Platform
if (cpuAbis.contains("x86")) {
NdkCxxPlatformTargetConfiguration targetConfiguration =
getTargetConfiguration(TargetCpuType.X86, compiler, androidPlatform);
NdkCxxPlatform x86 =
build(
config,
androidConfig,
filesystem,
InternalFlavor.of("android-x86"),
platform,
ndkRoot,
targetConfiguration,
cxxRuntime,
executableFinder,
strictToolchainPaths);
ndkCxxPlatformBuilder.put(TargetCpuType.X86, x86);
}
// x86_64 Platform
if (cpuAbis.contains("x86_64")) {
NdkCxxPlatformTargetConfiguration targetConfiguration =
getTargetConfiguration(TargetCpuType.X86_64, compiler, androidPlatform);
// CHECKSTYLE.OFF: LocalVariableName
NdkCxxPlatform x86_64 =
// CHECKSTYLE.ON
build(
config,
androidConfig,
filesystem,
InternalFlavor.of("android-x86_64"),
platform,
ndkRoot,
targetConfiguration,
cxxRuntime,
executableFinder,
strictToolchainPaths);
ndkCxxPlatformBuilder.put(TargetCpuType.X86_64, x86_64);
}
return ndkCxxPlatformBuilder.build();
}
@VisibleForTesting
static NdkCxxPlatformTargetConfiguration getTargetConfiguration(
TargetCpuType targetCpuType, NdkCxxPlatformCompiler compiler, String androidPlatform) {
if (targetCpuType == TargetCpuType.MIPS) {
throw new AssertionError();
}
return NdkCxxPlatformTargetConfiguration.builder()
.setTargetCpuType(targetCpuType)
.setTargetAppPlatform(androidPlatform)
.setCompiler(compiler)
.build();
}
@VisibleForTesting
static NdkCxxPlatform build(
CxxBuckConfig config,
AndroidBuckConfig androidConfig,
ProjectFilesystem filesystem,
Flavor flavor,
Platform platform,
Path ndkRoot,
NdkCxxPlatformTargetConfiguration targetConfiguration,
NdkCxxRuntime cxxRuntime,
ExecutableFinder executableFinder,
boolean strictToolchainPaths) {
// Create a version string to use when generating rule keys via the NDK tools we'll generate
// below. This will be used in lieu of hashing the contents of the tools, so that builds from
// different host platforms (which produce identical output) will share the cache with one
// another.
NdkCompilerType compilerType = targetConfiguration.getCompiler().getType();
String version =
Joiner.on('-')
.join(
ImmutableList.of(
readVersion(ndkRoot),
targetConfiguration.getToolchain(),
targetConfiguration.getTargetAppPlatform(),
compilerType,
targetConfiguration.getCompiler().getVersion(),
targetConfiguration.getCompiler().getGccVersion(),
cxxRuntime));
Host host = Preconditions.checkNotNull(BUILD_PLATFORMS.get(platform));
NdkCxxToolchainPaths toolchainPaths =
new NdkCxxToolchainPaths(
filesystem,
ndkRoot,
targetConfiguration,
host.toString(),
cxxRuntime,
strictToolchainPaths);
// Sanitized paths will have magic placeholders for parts of the paths that
// are machine/host-specific. See comments on ANDROID_NDK_ROOT and
// BUILD_HOST_SUBST above.
NdkCxxToolchainPaths sanitizedPaths = toolchainPaths.getSanitizedPaths();
// Build up the map of paths that must be sanitized.
ImmutableBiMap.Builder<Path, String> sanitizePathsBuilder = ImmutableBiMap.builder();
sanitizePathsBuilder.put(
toolchainPaths.getNdkToolRoot(), sanitizedPaths.getNdkToolRoot().toString());
if (compilerType != NdkCompilerType.GCC) {
sanitizePathsBuilder.put(
toolchainPaths.getNdkGccToolRoot(), sanitizedPaths.getNdkGccToolRoot().toString());
}
sanitizePathsBuilder.put(ndkRoot, AndroidNdkConstants.ANDROID_NDK_ROOT);
CxxToolProvider.Type type =
compilerType == NdkCompilerType.CLANG
? CxxToolProvider.Type.CLANG
: CxxToolProvider.Type.GCC;
ToolProvider ccTool =
new ConstantToolProvider(
getCTool(toolchainPaths, compilerType.cc, version, executableFinder));
ToolProvider cxxTool =
new ConstantToolProvider(
getCTool(toolchainPaths, compilerType.cxx, version, executableFinder));
CompilerProvider cc = new CompilerProvider(ccTool, type);
PreprocessorProvider cpp = new PreprocessorProvider(ccTool, type);
CompilerProvider cxx = new CompilerProvider(cxxTool, type);
PreprocessorProvider cxxpp = new PreprocessorProvider(cxxTool, type);
CxxPlatform.Builder cxxPlatformBuilder = CxxPlatform.builder();
ImmutableBiMap<Path, String> sanitizePaths = sanitizePathsBuilder.build();
PrefixMapDebugPathSanitizer compilerDebugPathSanitizer =
new PrefixMapDebugPathSanitizer(".", sanitizePaths);
MungingDebugPathSanitizer assemblerDebugPathSanitizer =
new MungingDebugPathSanitizer(
config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizePaths);
cxxPlatformBuilder
.setFlavor(flavor)
.setAs(cc)
.addAllAsflags(getAsflags(targetConfiguration, toolchainPaths))
.setAspp(cpp)
.setCc(cc)
.addAllCflags(getCCompilationFlags(targetConfiguration, toolchainPaths, androidConfig))
.setCpp(cpp)
.addAllCppflags(getCPreprocessorFlags(targetConfiguration, toolchainPaths, androidConfig))
.setCxx(cxx)
.addAllCxxflags(getCxxCompilationFlags(targetConfiguration, toolchainPaths, androidConfig))
.setCxxpp(cxxpp)
.addAllCxxppflags(
getCxxPreprocessorFlags(targetConfiguration, toolchainPaths, androidConfig))
.setLd(
new DefaultLinkerProvider(
LinkerProvider.Type.GNU,
new ConstantToolProvider(
getCcLinkTool(
targetConfiguration,
toolchainPaths,
compilerType.cxx,
version,
cxxRuntime,
executableFinder))))
.addAllLdflags(getLdFlags(targetConfiguration, androidConfig))
.setStrip(getGccTool(toolchainPaths, "strip", version, executableFinder))
.setSymbolNameTool(
new PosixNmSymbolNameTool(getGccTool(toolchainPaths, "nm", version, executableFinder)))
.setAr(
ArchiverProvider.from(
new GnuArchiver(getGccTool(toolchainPaths, "ar", version, executableFinder))))
.setRanlib(
new ConstantToolProvider(
getGccTool(toolchainPaths, "ranlib", version, executableFinder)))
// NDK builds are cross compiled, so the header is the same regardless of the host platform.
.setCompilerDebugPathSanitizer(compilerDebugPathSanitizer)
.setAssemblerDebugPathSanitizer(assemblerDebugPathSanitizer)
.setSharedLibraryExtension("so")
.setSharedLibraryVersionedExtensionFormat("so.%s")
.setStaticLibraryExtension("a")
.setObjectFileExtension("o")
.setSharedLibraryInterfaceParams(
config.getSharedLibraryInterfaces() != SharedLibraryInterfaceParams.Type.DISABLED
? Optional.of(
ElfSharedLibraryInterfaceParams.of(
new ConstantToolProvider(
getGccTool(toolchainPaths, "objcopy", version, executableFinder)),
ImmutableList.of(),
config.getSharedLibraryInterfaces()
== SharedLibraryInterfaceParams.Type.DEFINED_ONLY))
: Optional.empty())
.setPublicHeadersSymlinksEnabled(config.getPublicHeadersSymlinksEnabled())
.setPrivateHeadersSymlinksEnabled(config.getPrivateHeadersSymlinksEnabled());
// Add the NDK root path to the white-list so that headers from the NDK won't trigger the
// verification warnings. Ideally, long-term, we'd model NDK libs/headers via automatically
// generated nodes/descriptions so that they wouldn't need to special case it here.
HeaderVerification headerVerification = config.getHeaderVerificationOrIgnore();
try {
headerVerification =
headerVerification.withPlatformWhitelist(
ImmutableList.of(
"^"
+ Pattern.quote(ndkRoot.toRealPath().toString() + File.separatorChar)
+ ".*"));
} catch (IOException e) {
LOG.warn(e, "NDK path could not be resolved: %s", ndkRoot);
}
cxxPlatformBuilder.setHeaderVerification(headerVerification);
LOG.debug("NDK root: %s", ndkRoot.toString());
LOG.debug(
"Headers verification platform whitelist: %s", headerVerification.getPlatformWhitelist());
if (cxxRuntime != NdkCxxRuntime.SYSTEM) {
cxxPlatformBuilder.putRuntimeLdflags(
Linker.LinkableDepType.SHARED, "-l" + cxxRuntime.sharedName);
cxxPlatformBuilder.putRuntimeLdflags(
Linker.LinkableDepType.STATIC, "-l" + cxxRuntime.staticName);
String ndkVersion = readVersion(ndkRoot);
if (getNdkMajorVersion(ndkVersion) >= 12 && cxxRuntime == NdkCxxRuntime.LIBCXX) {
cxxPlatformBuilder.putRuntimeLdflags(Linker.LinkableDepType.STATIC, "-lc++abi");
if (targetConfiguration.getTargetArchAbi() == NdkTargetArchAbi.ARMEABI) {
cxxPlatformBuilder.putRuntimeLdflags(Linker.LinkableDepType.STATIC, "-latomic");
}
}
}
CxxPlatform cxxPlatform = cxxPlatformBuilder.build();
NdkCxxPlatform.Builder builder = NdkCxxPlatform.builder();
builder
.setCxxPlatform(cxxPlatform)
.setCxxRuntime(cxxRuntime)
.setObjdump(getGccTool(toolchainPaths, "objdump", version, executableFinder));
if (cxxRuntime != NdkCxxRuntime.SYSTEM) {
builder.setCxxSharedRuntimePath(
toolchainPaths.getCxxRuntimeLibsDirectory().resolve(cxxRuntime.getSoname()));
}
return builder.build();
}
/**
* It returns the version of the Android NDK located at the {@code ndkRoot} or throws the
* exception.
*
* @param ndkRoot the path where Android NDK is located.
* @return the version of the Android NDK located in {@code ndkRoot}.
*/
private static String readVersion(Path ndkRoot) {
return AndroidNdkResolver.findNdkVersionFromDirectory(ndkRoot).get();
}
private static Path getToolPath(
NdkCxxToolchainPaths toolchainPaths, String tool, ExecutableFinder executableFinder) {
Path expected = toolchainPaths.getToolPath(tool);
Optional<Path> path = executableFinder.getOptionalExecutable(expected, ImmutableMap.of());
Preconditions.checkState(path.isPresent(), expected.toString());
return path.get();
}
private static Path getGccToolPath(
NdkCxxToolchainPaths toolchainPaths, String tool, ExecutableFinder executableFinder) {
Path expected = toolchainPaths.getGccToolchainBinPath().resolve(tool);
Optional<Path> path = executableFinder.getOptionalExecutable(expected, ImmutableMap.of());
Preconditions.checkState(path.isPresent(), expected.toString());
return path.get();
}
private static Tool getGccTool(
NdkCxxToolchainPaths toolchainPaths,
String tool,
String version,
ExecutableFinder executableFinder) {
return VersionedTool.of(getGccToolPath(toolchainPaths, tool, executableFinder), tool, version);
}
private static Tool getCTool(
NdkCxxToolchainPaths toolchainPaths,
String tool,
String version,
ExecutableFinder executableFinder) {
return VersionedTool.of(getToolPath(toolchainPaths, tool, executableFinder), tool, version);
}
private static ImmutableList<String> getCxxRuntimeIncludeFlags(
NdkCxxPlatformTargetConfiguration targetConfiguration, NdkCxxToolchainPaths toolchainPaths) {
ImmutableList.Builder<String> flags = ImmutableList.builder();
switch (toolchainPaths.getCxxRuntime()) {
case GNUSTL:
flags.add(
"-isystem", toolchainPaths.getCxxRuntimeDirectory().resolve("include").toString());
flags.add(
"-isystem",
toolchainPaths
.getCxxRuntimeDirectory()
.resolve("libs")
.resolve(targetConfiguration.getTargetArchAbi().toString())
.resolve("include")
.toString());
break;
case LIBCXX:
String ndkVersion = readVersion(toolchainPaths.getNdkRoot());
// NDK r12b has a different include path for the LLVM headers
if (getNdkMajorVersion(ndkVersion) <= 12) {
flags.add(
"-isystem",
toolchainPaths
.getCxxRuntimeDirectory()
.resolve("libcxx")
.resolve("include")
.toString());
flags.add(
"-isystem",
toolchainPaths
.getCxxRuntimeDirectory()
.getParent()
.resolve("llvm-libc++abi")
.resolve("libcxxabi")
.resolve("include")
.toString());
} else {
flags.add(
"-isystem", toolchainPaths.getCxxRuntimeDirectory().resolve("include").toString());
flags.add(
"-isystem",
toolchainPaths
.getCxxRuntimeDirectory()
.getParent()
.resolve("llvm-libc++abi")
.resolve("include")
.toString());
}
flags.add(
"-isystem",
toolchainPaths
.getNdkRoot()
.resolve("sources")
.resolve("android")
.resolve("support")
.resolve("include")
.toString());
break;
// $CASES-OMITTED$
default:
flags.add(
"-isystem", toolchainPaths.getCxxRuntimeDirectory().resolve("include").toString());
}
return flags.build();
}
private static Linker getCcLinkTool(
NdkCxxPlatformTargetConfiguration targetConfiguration,
NdkCxxToolchainPaths toolchainPaths,
String tool,
String version,
NdkCxxRuntime cxxRuntime,
ExecutableFinder executableFinder) {
ImmutableList.Builder<String> flags = ImmutableList.builder();
// Clang still needs to find GCC tools.
if (targetConfiguration.getCompiler().getType() == NdkCompilerType.CLANG) {
flags.add("-gcc-toolchain", toolchainPaths.getNdkGccToolRoot().toString());
}
// Set the sysroot to the platform-specific path.
flags.add("--sysroot=" + toolchainPaths.getSysroot());
// TODO(#7264008): This was added for windows support but it's not clear why it's needed.
if (targetConfiguration.getCompiler().getType() == NdkCompilerType.GCC) {
flags.add("-B" + toolchainPaths.getLibexecGccToolPath(), "-B" + toolchainPaths.getLibPath());
}
// Add the path to the C/C++ runtime libraries, if necessary.
if (cxxRuntime != NdkCxxRuntime.SYSTEM) {
flags.add("-L" + toolchainPaths.getCxxRuntimeLibsDirectory());
}
return new GnuLinker(
VersionedTool.builder()
.setPath(getToolPath(toolchainPaths, tool, executableFinder))
.setName(tool)
.setVersion(version)
.setExtraArgs(flags.build())
.build());
}
private static ImmutableList<String> getLdFlags(
NdkCxxPlatformTargetConfiguration targetConfiguration, AndroidBuckConfig config) {
return ImmutableList.<String>builder()
.addAll(targetConfiguration.getLinkerFlags(targetConfiguration.getCompiler().getType()))
.addAll(DEFAULT_COMMON_LDFLAGS)
.addAll(config.getExtraNdkLdFlags())
.build();
}
/** Flags to be used when either preprocessing or compiling C or C++ sources. */
private static ImmutableList<String> getCommonFlags(
NdkCxxPlatformTargetConfiguration targetConfiguration, NdkCxxToolchainPaths toolchainPaths) {
ImmutableList.Builder<String> flags = ImmutableList.builder();
// Clang still needs to find the GCC tools.
if (targetConfiguration.getCompiler().getType() == NdkCompilerType.CLANG) {
flags.add("-gcc-toolchain", toolchainPaths.getNdkGccToolRoot().toString());
}
// TODO(#7264008): This was added for windows support but it's not clear why it's needed.
if (targetConfiguration.getCompiler().getType() == NdkCompilerType.GCC) {
flags.add(
"-B" + toolchainPaths.getLibexecGccToolPath(),
"-B" + toolchainPaths.getToolchainBinPath());
}
// Enable default warnings and turn them into errors.
flags.add("-Wall", "-Werror");
// NOTE: We pass all compiler flags to the preprocessor to make sure any necessary internal
// macros get defined and we also pass the include paths to the to the compiler since we're
// not whether we're doing combined preprocessing/compiling or not.
if (targetConfiguration.getCompiler().getType() == NdkCompilerType.CLANG) {
flags.add("-Wno-unused-command-line-argument");
}
// NDK builds enable stack protector and debug symbols by default.
flags.add("-fstack-protector", "-g3");
return flags.build();
}
private static ImmutableList<String> getCommonIncludes(NdkCxxToolchainPaths toolchainPaths) {
return ImmutableList.of(
"-isystem",
toolchainPaths.getNdkToolRoot().resolve("include").toString(),
"-isystem",
toolchainPaths.getLibPath().resolve("include").toString(),
"-isystem",
toolchainPaths.getSysroot().resolve("usr").resolve("include").toString(),
"-isystem",
toolchainPaths.getSysroot().resolve("usr").resolve("include").resolve("linux").toString());
}
private static ImmutableList<String> getAsflags(
NdkCxxPlatformTargetConfiguration targetConfiguration, NdkCxxToolchainPaths toolchainPaths) {
return ImmutableList.<String>builder()
.addAll(getCommonFlags(targetConfiguration, toolchainPaths))
// Default assembler flags added by the NDK to enforce the NX (no execute) security feature.
.add("-Xassembler", "--noexecstack")
.addAll(targetConfiguration.getAssemblerFlags(targetConfiguration.getCompiler().getType()))
.build();
}
// TODO(cjhopman): The way that c/cpp/cxx/cxxpp flags work is rather unintuitive. The
// documentation states that cflags/cxxflags are added to both preprocess and compile,
// cppflags/cxxppflags are added only to the preprocessor flags. At runtime, we typically do
// preprocess+compile, and in that case we're going to add both the preprocess and the compile
// flags to the command line. Still, BUCK expects that a CxxPlatform can do all of
// preprocess/compile/preprocess+compile. Many of the flags are duplicated across both preprocess
// and compile to support that (and then typically our users have to deal with ridiculously long
// command lines because we only ever do preprocess+compile).
private static ImmutableList<String> getCPreprocessorFlags(
NdkCxxPlatformTargetConfiguration targetConfiguration,
NdkCxxToolchainPaths toolchainPaths,
AndroidBuckConfig config) {
return ImmutableList.<String>builder()
.addAll(getCommonIncludes(toolchainPaths))
.addAll(DEFAULT_COMMON_CPPFLAGS)
.addAll(getCommonFlags(targetConfiguration, toolchainPaths))
.addAll(DEFAULT_COMMON_CFLAGS)
.addAll(targetConfiguration.getCompilerFlags(targetConfiguration.getCompiler().getType()))
.addAll(config.getExtraNdkCFlags())
.build();
}
private static ImmutableList<String> getCxxPreprocessorFlags(
NdkCxxPlatformTargetConfiguration targetConfiguration,
NdkCxxToolchainPaths toolchainPaths,
AndroidBuckConfig config) {
ImmutableList.Builder<String> flags = ImmutableList.builder();
flags.addAll(getCxxRuntimeIncludeFlags(targetConfiguration, toolchainPaths));
flags.addAll(getCommonIncludes(toolchainPaths));
flags.addAll(DEFAULT_COMMON_CXXPPFLAGS);
flags.addAll(getCommonFlags(targetConfiguration, toolchainPaths));
flags.addAll(DEFAULT_COMMON_CXXFLAGS);
if (targetConfiguration.getCompiler().getType() == NdkCompilerType.GCC) {
flags.add("-Wno-literal-suffix");
}
flags.addAll(targetConfiguration.getCompilerFlags(targetConfiguration.getCompiler().getType()));
flags.addAll(config.getExtraNdkCxxFlags());
return flags.build();
}
private static ImmutableList<String> getCCompilationFlags(
NdkCxxPlatformTargetConfiguration targetConfiguration,
NdkCxxToolchainPaths toolchainPaths,
AndroidBuckConfig config) {
return ImmutableList.<String>builder()
.addAll(targetConfiguration.getCompilerFlags(targetConfiguration.getCompiler().getType()))
.addAll(DEFAULT_COMMON_CFLAGS)
.addAll(getCommonFlags(targetConfiguration, toolchainPaths))
.addAll(DEFAULT_COMMON_COMPILER_FLAGS)
.addAll(config.getExtraNdkCFlags())
.build();
}
private static ImmutableList<String> getCxxCompilationFlags(
NdkCxxPlatformTargetConfiguration targetConfiguration,
NdkCxxToolchainPaths toolchainPaths,
AndroidBuckConfig config) {
return ImmutableList.<String>builder()
.addAll(targetConfiguration.getCompilerFlags(targetConfiguration.getCompiler().getType()))
.addAll(DEFAULT_COMMON_CXXFLAGS)
.addAll(getCommonFlags(targetConfiguration, toolchainPaths))
.addAll(DEFAULT_COMMON_COMPILER_FLAGS)
.addAll(config.getExtraNdkCxxFlags())
.build();
}
/** The OS and Architecture that we're building on. */
public enum Host {
DARWIN_X86_64("darwin-x86_64"),
LINUX_X86_64("linux-x86_64"),
WINDOWS_X86_64("windows-x86_64"),
;
private final String value;
Host(String value) {
this.value = Preconditions.checkNotNull(value);
}
@Override
public String toString() {
return value;
}
}
/** The toolchains name for the platform being targeted. */
public enum ToolchainTarget {
I686_LINUX_ANDROID("i686-linux-android"),
X86_64_LINUX_ANDROID("x86_64-linux-android"),
ARM_LINUX_ANDROIDEABI("arm-linux-androideabi"),
AARCH64_LINUX_ANDROID("aarch64-linux-android"),
;
private final String value;
ToolchainTarget(String value) {
this.value = Preconditions.checkNotNull(value);
}
@Override
public String toString() {
return value;
}
}
static class NdkCxxToolchainPaths {
private Path ndkRoot;
private String ndkVersion;
private NdkCxxPlatformTargetConfiguration targetConfiguration;
private String hostName;
private NdkCxxRuntime cxxRuntime;
private Map<String, Path> cachedPaths;
private boolean strict;
private int ndkMajorVersion;
private ProjectFilesystem filesystem;
NdkCxxToolchainPaths(
ProjectFilesystem filesystem,
Path ndkRoot,
NdkCxxPlatformTargetConfiguration targetConfiguration,
String hostName,
NdkCxxRuntime cxxRuntime,
boolean strict) {
this(
filesystem,
ndkRoot,
readVersion(ndkRoot),
targetConfiguration,
hostName,
cxxRuntime,
strict);
}
private NdkCxxToolchainPaths(
ProjectFilesystem filesystem,
Path ndkRoot,
String ndkVersion,
NdkCxxPlatformTargetConfiguration targetConfiguration,
String hostName,
NdkCxxRuntime cxxRuntime,
boolean strict) {
this.filesystem = filesystem;
this.cachedPaths = new HashMap<>();
this.strict = strict;
this.targetConfiguration = targetConfiguration;
this.hostName = hostName;
this.cxxRuntime = cxxRuntime;
this.ndkRoot = ndkRoot;
this.ndkVersion = ndkVersion;
this.ndkMajorVersion = getNdkMajorVersion(ndkVersion);
Assertions.assertCondition(ndkMajorVersion > 0, "Unknown ndk version: " + ndkVersion);
}
NdkCxxToolchainPaths getSanitizedPaths() {
return new NdkCxxToolchainPaths(
filesystem,
Paths.get(AndroidNdkConstants.ANDROID_NDK_ROOT),
ndkVersion,
targetConfiguration,
BUILD_HOST_SUBST,
cxxRuntime,
false);
}
Path processPathPattern(Path root, String pattern) {
String key = root + "/" + pattern;
Path result = cachedPaths.get(key);
if (result == null) {
String[] segments = pattern.split("/");
result = root;
for (String s : segments) {
if (s.contains("{")) {
s = s.replace("{toolchain}", targetConfiguration.getToolchain().toString());
s =
s.replace(
"{toolchain_target}", targetConfiguration.getToolchainTarget().toString());
s = s.replace("{compiler_version}", targetConfiguration.getCompiler().getVersion());
s = s.replace("{compiler_type}", targetConfiguration.getCompiler().getType().name);
s =
s.replace(
"{gcc_compiler_version}", targetConfiguration.getCompiler().getGccVersion());
s = s.replace("{hostname}", hostName);
s = s.replace("{target_platform}", targetConfiguration.getTargetAppPlatform());
s = s.replace("{target_arch}", targetConfiguration.getTargetArch().toString());
s = s.replace("{target_arch_abi}", targetConfiguration.getTargetArchAbi().toString());
}
result = result.resolve(s);
}
if (strict) {
Assertions.assertCondition(result.toFile().exists(), result + " doesn't exist.");
}
cachedPaths.put(key, result);
}
return result;
}
private boolean isGcc() {
return targetConfiguration.getCompiler().getType() == NdkCompilerType.GCC;
}
Path processPathPattern(String s) {
return processPathPattern(ndkRoot, s);
}
Path getNdkToolRoot() {
if (isGcc()) {
return processPathPattern("toolchains/{toolchain}-{compiler_version}/prebuilt/{hostname}");
} else {
if (ndkMajorVersion < 11) {
return processPathPattern("toolchains/llvm-{compiler_version}/prebuilt/{hostname}");
} else {
return processPathPattern("toolchains/llvm/prebuilt/{hostname}");
}
}
}
/**
* @return the path to use as the system root, targeted to the given target platform and
* architecture.
*/
Path getSysroot() {
return processPathPattern("platforms/{target_platform}/arch-{target_arch}");
}
Path getLibexecGccToolPath() {
Assertions.assertCondition(isGcc());
if (ndkMajorVersion < 12) {
return processPathPattern(
getNdkToolRoot(), "libexec/gcc/{toolchain_target}/{compiler_version}");
} else {
return processPathPattern(
getNdkToolRoot(), "libexec/gcc/{toolchain_target}/{compiler_version}.x");
}
}
Path getLibPath() {
String pattern;
if (isGcc()) {
if (ndkMajorVersion < 12) {
pattern = "lib/{compiler_type}/{toolchain_target}/{compiler_version}";
} else {
pattern = "lib/{compiler_type}/{toolchain_target}/{compiler_version}.x";
}
} else {
if (ndkMajorVersion < 11) {
pattern = "lib/{compiler_type}/{compiler_version}";
} else {
pattern = "lib64/{compiler_type}/{compiler_version}";
}
}
return processPathPattern(getNdkToolRoot(), pattern);
}
Path getNdkGccToolRoot() {
return processPathPattern(
"toolchains/{toolchain}-{gcc_compiler_version}/prebuilt/{hostname}");
}
Path getToolchainBinPath() {
if (isGcc()) {
return processPathPattern(getNdkToolRoot(), "{toolchain_target}/bin");
} else {
return processPathPattern(getNdkToolRoot(), "bin");
}
}
private Path getGccToolchainBinPath() {
return processPathPattern(getNdkGccToolRoot(), "{toolchain_target}/bin");
}
private Path getCxxRuntimeDirectory() {
if (cxxRuntime == NdkCxxRuntime.GNUSTL) {
return processPathPattern("sources/cxx-stl/" + cxxRuntime.name + "/{gcc_compiler_version}");
} else {
return processPathPattern("sources/cxx-stl/" + cxxRuntime.name);
}
}
private Path getCxxRuntimeLibsDirectory() {
return processPathPattern(getCxxRuntimeDirectory(), "libs/{target_arch_abi}");
}
Path getToolPath(String tool) {
if (isGcc()) {
return processPathPattern(getNdkToolRoot(), "bin/{toolchain_target}-" + tool);
} else {
return processPathPattern(getNdkToolRoot(), "bin/" + tool);
}
}
public Path getNdkRoot() {
return ndkRoot;
}
public NdkCxxRuntime getCxxRuntime() {
return cxxRuntime;
}
}
}
| {
"content_hash": "71f247e7e15716c0ec0846b06deb2c9b",
"timestamp": "",
"source": "github",
"line_count": 1055,
"max_line_length": 100,
"avg_line_length": 39.28625592417062,
"alnum_prop": 0.6673824402248655,
"repo_name": "clonetwin26/buck",
"id": "d2e26eb689d4fd411bfab93897788915b0959842",
"size": "42052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/facebook/buck/android/toolchain/ndk/impl/NdkCxxPlatforms.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "793"
},
{
"name": "Batchfile",
"bytes": "2215"
},
{
"name": "C",
"bytes": "263152"
},
{
"name": "C#",
"bytes": "237"
},
{
"name": "C++",
"bytes": "14997"
},
{
"name": "CSS",
"bytes": "54894"
},
{
"name": "D",
"bytes": "1017"
},
{
"name": "Go",
"bytes": "4646"
},
{
"name": "Groovy",
"bytes": "3362"
},
{
"name": "HTML",
"bytes": "7248"
},
{
"name": "Haskell",
"bytes": "971"
},
{
"name": "IDL",
"bytes": "385"
},
{
"name": "Java",
"bytes": "25118787"
},
{
"name": "JavaScript",
"bytes": "933531"
},
{
"name": "Kotlin",
"bytes": "19145"
},
{
"name": "Lex",
"bytes": "2867"
},
{
"name": "Makefile",
"bytes": "1816"
},
{
"name": "Matlab",
"bytes": "47"
},
{
"name": "OCaml",
"bytes": "4935"
},
{
"name": "Objective-C",
"bytes": "160741"
},
{
"name": "Objective-C++",
"bytes": "34"
},
{
"name": "PowerShell",
"bytes": "244"
},
{
"name": "Prolog",
"bytes": "858"
},
{
"name": "Python",
"bytes": "1848054"
},
{
"name": "Roff",
"bytes": "1207"
},
{
"name": "Rust",
"bytes": "5199"
},
{
"name": "Scala",
"bytes": "5046"
},
{
"name": "Shell",
"bytes": "57970"
},
{
"name": "Smalltalk",
"bytes": "3794"
},
{
"name": "Swift",
"bytes": "10663"
},
{
"name": "Thrift",
"bytes": "42010"
},
{
"name": "Yacc",
"bytes": "323"
}
],
"symlink_target": ""
} |
import Prelude hiding (catch); no = catch | {
"content_hash": "44c4d206b494692bd606481759ccd6e5",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 41,
"avg_line_length": 41,
"alnum_prop": 0.7560975609756098,
"repo_name": "mpickering/hlint-refactor",
"id": "c3c551b722bcbf19cf04ec80078641cc628c68ed",
"size": "41",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "tests/examples/Default62.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Haskell",
"bytes": "55954"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
//$route['default_controller'] = 'under-contruction';
$route['default_controller'] = 'deal';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
// front
// $route['/'] = 'Home';
// hosting
$route['sign-up'] = 'sign-up/index';
$route['sign-up/(:any)'] = 'sign-up/$1';
// hosting
$route['hosting'] = 'hosting/index';
$route['hosting/(:any)'] = 'hosting/$1';
// deal
$route['deal'] = 'deal/index';
$route['deal/(:any)'] = 'deal/$1';
// contact-us
$route['contact-us'] = 'contact-us/index';
$route['contact-us/(:any)'] = 'contact-us/$1';
// support
$route['support'] = 'support/index';
$route['support/(:any)'] = 'support/$1';
// submission - all forms submission goes here
$route['submission'] = 'submission/index';
$route['submission/(:any)'] = 'submission/$1'; | {
"content_hash": "36a4b38215b5fa1db80131cb1aa28592",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 75,
"avg_line_length": 31.843373493975903,
"alnum_prop": 0.6193719258418464,
"repo_name": "chilieu/cbsh",
"id": "664b548abf0e9d69b3760f48ae9657e1b8cbadee",
"size": "2643",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/config/routes.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1154"
},
{
"name": "CSS",
"bytes": "1253201"
},
{
"name": "HTML",
"bytes": "10906572"
},
{
"name": "JavaScript",
"bytes": "544020"
},
{
"name": "PHP",
"bytes": "1817934"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>B13</logradouro><bairro>Santa Maria</bairro><cidade>Aracaju</cidade><uf>SE</uf><cep>49044298</cep></feed>
| {
"content_hash": "03b67ca860729aa68a29f96656d09463",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 139,
"avg_line_length": 98,
"alnum_prop": 0.7142857142857143,
"repo_name": "chesarex/webservice-cep",
"id": "05070552acdb74c81f45360de80b3f07c369a27b",
"size": "196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/ceps/49/044/298/cep.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import {
GraphQLInputObjectType,
GraphQLObjectType,
GraphQLNonNull,
GraphQLList,
GraphQLString,
GraphQLInt,
GraphQLID
} from 'graphql';
import { RelationInput, EdgeInput, MetaInput } from './subdocuments';
export default new GraphQLInputObjectType({
name: 'ConstellationInput',
fields: {
_id: {
type: GraphQLID,
},
meta: {
type: MetaInput,
},
editors: {
type: new GraphQLList(GraphQLID),
},
avatar: {
type: GraphQLString,
},
trees: {
type: new GraphQLList(RelationInput),
},
trustedBy: {
type: new GraphQLList(RelationInput),
},
theme: {
type: RelationInput,
},
nodes: {
type: new GraphQLList(GraphQLID),
},
edges: {
type: new GraphQLList(EdgeInput),
},
trustRequired: {
type: GraphQLInt,
},
},
});
| {
"content_hash": "756ee0cea5c09af53610e659e38df7a6",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 69,
"avg_line_length": 18.319148936170212,
"alnum_prop": 0.5923344947735192,
"repo_name": "GetGee/G",
"id": "9c5c1849fcfd64bc043413e6a0a098ca50d2845a",
"size": "861",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/server/graphql/types/constellation-input.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "161393"
},
{
"name": "HTML",
"bytes": "16783"
},
{
"name": "JavaScript",
"bytes": "5103037"
}
],
"symlink_target": ""
} |
{% extends 'layout.html' %}
{% block title %}Login{% endblock %}
{% block body %}
<h1>You have successfully signed up.</h1>
<p>
An email has been sent to the account you signed up with.
Once you verify your email from the link provided in that
email you will be able to login.
</p>
{% endblock %}
| {
"content_hash": "e717ffbc92e8a483d2d369529278b0fc",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 65,
"avg_line_length": 33.3,
"alnum_prop": 0.6216216216216216,
"repo_name": "BaySchoolCS2/ProjectRepo",
"id": "43226bd8d72c2b073f720b0cee9fc34b99dd14ae",
"size": "333",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "application/templates/signupLanding.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8436"
},
{
"name": "HTML",
"bytes": "31748"
},
{
"name": "JavaScript",
"bytes": "1293"
},
{
"name": "Python",
"bytes": "36093"
},
{
"name": "Shell",
"bytes": "595"
}
],
"symlink_target": ""
} |
var _ = require('underscore');
var keystone = require('keystone');
var browserify = require('browserify-middleware');
var babelify = require('babelify');
var middleware = require('./middleware');
var importRoutes = keystone.importer(__dirname);
var clientConfig = require('../client/config');
// Common Middleware
keystone.pre('routes', middleware.initErrorHandlers);
keystone.pre('routes', middleware.initLocals);
keystone.pre('routes', middleware.loadSponsors);
keystone.pre('render', middleware.flashMessages);
// Handle 404 errors
keystone.set('404', function(req, res, next) {
res.notfound();
});
// Handle other errors
keystone.set('500', function(err, req, res, next) {
var title, message;
if (err instanceof Error) {
message = err.message;
err = err.stack;
}
res.err(err, title, message);
});
// Load Routes
var routes = {
api: importRoutes('./api'),
views: importRoutes('./views'),
auth: importRoutes('./auth')
};
// Bind Routes
exports = module.exports = function(app) {
// Browserification
app.get('/js/packages.js', browserify(clientConfig.packages, {
cache: true,
precompile: true
}));
app.use('/js', browserify('./client/scripts', {
external: clientConfig.packages,
transform: ['babelify']
}));
// Allow cross-domain requests (development only)
if (process.env.NODE_ENV != 'production') {
console.log('------------------------------------------------');
console.log('Notice: Enabling CORS for development.');
console.log('------------------------------------------------');
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
}
// Website
app.get('/', routes.views.index);
app.get('/meetups', routes.views.meetups);
app.get('/meetups/:meetup', routes.views.meetup);
app.get('/members', routes.views.members);
app.get('/members/mentors', routes.views.mentors);
app.get('/member/:member', routes.views.member);
app.get('/organisations', routes.views.organisations);
app.get('/links', routes.views.links);
app.get('/links/:tag?', routes.views.links);
app.all('/links/link/:link', routes.views.link);
app.get('/blog/:category?', routes.views.blog);
app.all('/blog/post/:post', routes.views.post);
app.get('/skills/:tag?', routes.views.skills);
app.all('/skills/:skill', routes.views.skill);
app.get('/about', routes.views.about);
app.get('/mentoring', routes.views.mentoring);
//app.get('/profile', routes.views.profile);
app.get('/profiles', routes.views.profiles);
app.get('/profiles/:tag?', routes.views.profiles);
app.all('/profiles/profile/:profile', routes.views.profile);
app.get('/showbag', routes.views.showbag);
// Session
app.all('/join', routes.views.session.join);
app.all('/signin', routes.views.session.signin);
app.get('/signout', routes.views.session.signout);
app.all('/forgot-password', routes.views.session['forgot-password']);
app.all('/reset-password/:key', routes.views.session['reset-password']);
// Authentication
app.all('/auth/confirm', routes.auth.confirm);
app.all('/auth/app', routes.auth.app);
app.all('/auth/:service', routes.auth.service);
// User
app.all('/me*', middleware.requireUser);
app.all('/me', routes.views.me);
app.all('/me/create/post', routes.views.createPost);
app.all('/me/create/link', routes.views.createLink);
app.all('/me/create/skill', routes.views.createSkill);
//app.all('/me/create/profile', routes.views.createProfile);
// Tools
app.all('/notification-center', routes.views.tools['notification-center']);
// Maintenace
app.all('/maintenance', routes.views.maintenance);
// API
//app.all('/api*', keystone.initAPI);
app.all('/api*', keystone.middleware.api);
app.all('/api/me/meetup', routes.api.me.meetup);
app.all('/api/stats', routes.api.stats);
app.all('/api/meetup/:id', routes.api.meetup);
// API - App
app.all('/api/app/status', routes.api.app.status);
app.all('/api/app/rsvp', routes.api.app.rsvp);
app.all('/api/app/signin-email', routes.api.app['signin-email']);
app.all('/api/app/signup-email', routes.api.app['signup-email']);
app.all('/api/app/signin-service', routes.api.app['signin-service']);
app.all('/api/app/signin-service-check', routes.api.app['signin-service-check']);
app.all('/api/app/signin-recover', routes.api.app['signin-recover']);
}
| {
"content_hash": "7ed8437c0b34c5fd56b5a2b78e34f830",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 82,
"avg_line_length": 33.80916030534351,
"alnum_prop": 0.6730638970422217,
"repo_name": "s-vp/site",
"id": "3e3e1acf567ab61f7318508cc120d4e47b89f71c",
"size": "4429",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "routes/index.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "270922"
},
{
"name": "HTML",
"bytes": "102462"
},
{
"name": "JavaScript",
"bytes": "222146"
}
],
"symlink_target": ""
} |
package com.inman.model.response;
public enum ResponseType {
ADD,CHANGE,DELETE,QUERY
}
| {
"content_hash": "655af3b0b683cfe797bd6c56a05c415b",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 33,
"avg_line_length": 18.4,
"alnum_prop": 0.7608695652173914,
"repo_name": "PirateBag/Inman",
"id": "064262b510c0f3a0dd916f213bdf8459a2c99439",
"size": "92",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/inman/model/response/ResponseType.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "891"
},
{
"name": "Java",
"bytes": "49594"
},
{
"name": "Shell",
"bytes": "358"
}
],
"symlink_target": ""
} |
package com.hazelcast.internal.util.collection;
import com.hazelcast.internal.util.QuickMath;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.IntFunction;
import static com.hazelcast.internal.util.Preconditions.checkNotNull;
import static com.hazelcast.internal.util.collection.Hashing.intHash;
/**
* {@link java.util.Map} implementation specialized for int keys using open addressing and
* linear probing for cache-efficient access.
* <p>
* <strong>NOTE: This map doesn't support {@code null} keys and values.</strong>
*
* @param <V> values stored in the {@link java.util.Map}
*/
public class Int2ObjectHashMap<V> implements Map<Integer, V> {
/** The default load factor for constructors not explicitly supplying it. */
public static final double DEFAULT_LOAD_FACTOR = 0.6;
/** The default initial capacity for constructors not explicitly supplying it. */
public static final int DEFAULT_INITIAL_CAPACITY = 8;
private final double loadFactor;
private int resizeThreshold;
private int capacity;
private int mask;
private int size;
private int[] keys;
private Object[] values;
// cached to avoid allocation
private final ValueCollection valueCollection = new ValueCollection();
private final KeySet keySet = new KeySet();
private final EntrySet entrySet = new EntrySet();
public Int2ObjectHashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public Int2ObjectHashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Construct a new map allowing a configuration for initial capacity and load factor.
*
* @param initialCapacity for the backing array
* @param loadFactor limit for resizing on puts
*/
public Int2ObjectHashMap(final int initialCapacity, final double loadFactor) {
this.loadFactor = loadFactor;
capacity = QuickMath.nextPowerOfTwo(initialCapacity);
mask = capacity - 1;
resizeThreshold = (int) (capacity * loadFactor);
keys = new int[capacity];
values = new Object[capacity];
}
/**
* Get the load factor beyond which the map will increase size.
*
* @return load factor for when the map should increase size.
*/
public double loadFactor() {
return loadFactor;
}
/**
* Get the total capacity for the map to which the load factor with be a fraction of.
*
* @return the total capacity for the map.
*/
public int capacity() {
return capacity;
}
/**
* Get the actual threshold which when reached the map resize.
* This is a function of the current capacity and load factor.
*
* @return the threshold when the map will resize.
*/
public int resizeThreshold() {
return resizeThreshold;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return 0 == size;
}
@Override
public boolean containsKey(final Object key) {
checkNotNull(key, "Null keys are not permitted");
return containsKey(((Integer) key).intValue());
}
/**
* Overloaded version of {@link Map#containsKey(Object)} that takes a primitive int key.
*
* @param key for indexing the {@link Map}
* @return true if the key is found otherwise false.
*/
public boolean containsKey(final int key) {
int index = intHash(key, mask);
while (null != values[index]) {
if (key == keys[index]) {
return true;
}
index = ++index & mask;
}
return false;
}
@Override
public boolean containsValue(final Object value) {
checkNotNull(value, "Null values are not permitted");
for (final Object v : values) {
if (null != v && value.equals(v)) {
return true;
}
}
return false;
}
@Override
public V get(final Object key) {
return get(((Integer) key).intValue());
}
/**
* Overloaded version of {@link Map#get(Object)} that takes a primitive int key.
*
* @param key for indexing the {@link Map}
* @return the value if found otherwise null
*/
@SuppressWarnings("unchecked")
public V get(final int key) {
int index = intHash(key, mask);
Object value;
while (null != (value = values[index])) {
if (key == keys[index]) {
return (V) value;
}
index = ++index & mask;
}
return null;
}
/**
* Get a value for a given key, or if it does ot exist then default the value via a {@link IntFunction}
* and put it in the map.
*
* @param key to search on.
* @param mappingFunction to provide a value if the get returns null.
* @return the value if found otherwise the default.
*/
public V computeIfAbsent(final int key, final IntFunction<? extends V> mappingFunction) {
checkNotNull(mappingFunction, "mappingFunction cannot be null");
V value = get(key);
if (value == null) {
value = mappingFunction.apply(key);
if (value != null) {
put(key, value);
}
}
return value;
}
@Override
public V put(final Integer key, final V value) {
return put(key.intValue(), value);
}
/**
* Overloaded version of {@link Map#put(Object, Object)} that takes a primitive int key.
*
* @param key for indexing the {@link Map}
* @param value to be inserted in the {@link Map}
* @return the previous value if found otherwise null
*/
@SuppressWarnings("unchecked")
public V put(final int key, final V value) {
checkNotNull(value, "Value cannot be null");
V oldValue = null;
int index = intHash(key, mask);
while (null != values[index]) {
if (key == keys[index]) {
oldValue = (V) values[index];
break;
}
index = ++index & mask;
}
if (null == oldValue) {
++size;
keys[index] = key;
}
values[index] = value;
if (size > resizeThreshold) {
increaseCapacity();
}
return oldValue;
}
@Override
public V remove(final Object key) {
return remove(((Integer) key).intValue());
}
/**
* Overloaded version of {@link Map#remove(Object)} that takes a primitive int key.
*
* @param key for indexing the {@link Map}
* @return the value if found otherwise null
*/
@SuppressWarnings("unchecked")
public V remove(final int key) {
int index = intHash(key, mask);
Object value;
while (null != (value = values[index])) {
if (key == keys[index]) {
values[index] = null;
--size;
compactChain(index);
return (V) value;
}
index = ++index & mask;
}
return null;
}
@Override
public void clear() {
size = 0;
Arrays.fill(values, null);
}
/**
* Compact the {@link Map} backing arrays by rehashing with a capacity just larger than current size
* and giving consideration to the load factor.
*/
public void compact() {
final int idealCapacity = (int) Math.round(size() * (1.0d / loadFactor));
rehash(QuickMath.nextPowerOfTwo(idealCapacity));
}
@Override
public void putAll(final Map<? extends Integer, ? extends V> map) {
for (final Entry<? extends Integer, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public KeySet keySet() {
return keySet;
}
@Override
public Collection<V> values() {
return valueCollection;
}
/**
* {@inheritDoc}
* This set's iterator also implements <code>Map.Entry</code>
* so the <code>next()</code> method can just return the iterator
* instance itself with no heap allocation. This characteristic
* makes the set unusable wherever the returned entries are
* retained (such as <code>coll.addAll(entrySet)</code>.
*/
@Override
public Set<Entry<Integer, V>> entrySet() {
return entrySet;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append('{');
for (final Entry<Integer, V> entry : entrySet()) {
sb.append(entry.getKey().intValue());
sb.append('=');
sb.append(entry.getValue());
sb.append(", ");
}
if (sb.length() > 1) {
sb.setLength(sb.length() - 2);
}
sb.append('}');
return sb.toString();
}
private void increaseCapacity() {
final int newCapacity = capacity << 1;
if (newCapacity < 0) {
throw new IllegalStateException("Max capacity reached at size=" + size);
}
rehash(newCapacity);
}
private void rehash(final int newCapacity) {
if (1 != Integer.bitCount(newCapacity)) {
throw new IllegalStateException("New capacity must be a power of two");
}
capacity = newCapacity;
mask = newCapacity - 1;
resizeThreshold = (int) (newCapacity * loadFactor);
final int[] tempKeys = new int[capacity];
final Object[] tempValues = new Object[capacity];
for (int i = 0, size = values.length; i < size; i++) {
final Object value = values[i];
if (null != value) {
final int key = keys[i];
int newHash = intHash(key, mask);
while (null != tempValues[newHash]) {
newHash = ++newHash & mask;
}
tempKeys[newHash] = key;
tempValues[newHash] = value;
}
}
keys = tempKeys;
values = tempValues;
}
private void compactChain(int deleteIndex) {
int index = deleteIndex;
while (true) {
index = ++index & mask;
if (null == values[index]) {
return;
}
final int hash = intHash(keys[index], mask);
if ((index < hash && (hash <= deleteIndex || deleteIndex <= index))
|| (hash <= deleteIndex && deleteIndex <= index)) {
keys[deleteIndex] = keys[index];
values[deleteIndex] = values[index];
values[index] = null;
deleteIndex = index;
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Internal Sets and Collections
///////////////////////////////////////////////////////////////////////////////////////////////
/** Adds non-boxing methods to the standard Set interface. */
public class KeySet extends AbstractSet<Integer> {
@Override
public int size() {
return Int2ObjectHashMap.this.size();
}
@Override
public boolean isEmpty() {
return Int2ObjectHashMap.this.isEmpty();
}
@Override
public boolean contains(final Object o) {
return Int2ObjectHashMap.this.containsKey(o);
}
/** Non-boxing variant of contains(). */
public boolean contains(final int key) {
return Int2ObjectHashMap.this.containsKey(key);
}
@Override
public KeyIterator iterator() {
return new KeyIterator();
}
@Override
public boolean remove(final Object o) {
return null != Int2ObjectHashMap.this.remove(o);
}
/** Non-boxing variant of remove(). */
public boolean remove(final int key) {
return null != Int2ObjectHashMap.this.remove(key);
}
@Override
public void clear() {
Int2ObjectHashMap.this.clear();
}
}
private class ValueCollection extends AbstractCollection<V> {
@Override
public int size() {
return Int2ObjectHashMap.this.size();
}
@Override
public boolean isEmpty() {
return Int2ObjectHashMap.this.isEmpty();
}
@Override
public boolean contains(final Object o) {
return Int2ObjectHashMap.this.containsValue(o);
}
@Override
public ValueIterator<V> iterator() {
return new ValueIterator<V>();
}
@Override
public void clear() {
Int2ObjectHashMap.this.clear();
}
}
private class EntrySet extends AbstractSet<Entry<Integer, V>> {
@Override
public int size() {
return Int2ObjectHashMap.this.size();
}
@Override
public boolean isEmpty() {
return Int2ObjectHashMap.this.isEmpty();
}
@Override
public Iterator<Entry<Integer, V>> iterator() {
return new EntryIterator();
}
@Override
public void clear() {
Int2ObjectHashMap.this.clear();
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Iterators
///////////////////////////////////////////////////////////////////////////////////////////////
private abstract class AbstractIterator<T> implements Iterator<T> {
protected final int[] keys = Int2ObjectHashMap.this.keys;
protected final Object[] values = Int2ObjectHashMap.this.values;
private int posCounter;
private int stopCounter;
private boolean isPositionValid;
protected AbstractIterator() {
int i = capacity;
if (null != values[capacity - 1]) {
i = 0;
for (int size = capacity; i < size; i++) {
if (null == values[i]) {
break;
}
}
}
stopCounter = i;
posCounter = i + capacity;
}
protected int getPosition() {
return posCounter & mask;
}
@Override
public boolean hasNext() {
for (int i = posCounter - 1; i >= stopCounter; i--) {
final int index = i & mask;
if (null != values[index]) {
return true;
}
}
return false;
}
protected void findNext() {
isPositionValid = false;
for (int i = posCounter - 1; i >= stopCounter; i--) {
final int index = i & mask;
if (null != values[index]) {
posCounter = i;
isPositionValid = true;
return;
}
}
throw new NoSuchElementException();
}
@Override
public abstract T next();
@Override
public void remove() {
if (isPositionValid) {
final int position = getPosition();
values[position] = null;
--size;
compactChain(position);
isPositionValid = false;
} else {
throw new IllegalStateException();
}
}
}
private class ValueIterator<T> extends AbstractIterator<T> {
@Override
@SuppressWarnings("unchecked")
public T next() {
findNext();
return (T) values[getPosition()];
}
}
/** Adds an unboxed next() method to the standard Iterator interface. */
public class KeyIterator extends AbstractIterator<Integer> {
@Override
public Integer next() {
return nextInt();
}
/** Non-boxing variant of next(). */
public int nextInt() {
findNext();
return keys[getPosition()];
}
}
@SuppressWarnings("unchecked")
@SuppressFBWarnings(value = "PZ_DONT_REUSE_ENTRY_OBJECTS_IN_ITERATORS",
justification = "deliberate, documented choice")
private class EntryIterator extends AbstractIterator<Entry<Integer, V>> implements Entry<Integer, V> {
@Override
public Entry<Integer, V> next() {
findNext();
return this;
}
@Override
public Integer getKey() {
return keys[getPosition()];
}
@Override
public V getValue() {
return (V) values[getPosition()];
}
@Override
public V setValue(final V value) {
checkNotNull(value);
final int pos = getPosition();
final Object oldValue = values[pos];
values[pos] = value;
return (V) oldValue;
}
}
}
| {
"content_hash": "d11b6493b87023f0c3ae395e0c46b455",
"timestamp": "",
"source": "github",
"line_count": 589,
"max_line_length": 107,
"avg_line_length": 29.500848896434636,
"alnum_prop": 0.5412638121546961,
"repo_name": "emre-aydin/hazelcast",
"id": "bd2fb9469a33f100afc63116c00d4bf7b40f0c97",
"size": "18063",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "hazelcast/src/main/java/com/hazelcast/internal/util/collection/Int2ObjectHashMap.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1261"
},
{
"name": "C",
"bytes": "353"
},
{
"name": "Java",
"bytes": "39634758"
},
{
"name": "Shell",
"bytes": "29479"
}
],
"symlink_target": ""
} |
package liquibase.database.core;
import static java.util.Arrays.asList;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import liquibase.CatalogAndSchema;
import liquibase.database.Database;
import liquibase.database.DatabaseConnection;
import liquibase.exception.DatabaseException;
import liquibase.executor.Executor;
import liquibase.executor.ExecutorService;
import liquibase.statement.SqlStatement;
public class SybaseDatabaseTest {
@Test
public void testIsSybaseProductName() {
SybaseDatabase database = new SybaseDatabase();
assertTrue("Sybase SQL Server is a valid product name", database.isSybaseProductName("Sybase SQL Server"));
assertTrue("sql server is a valid product name", database.isSybaseProductName("sql server"));
assertTrue("ASE is a valid product name", database.isSybaseProductName("ASE"));
assertTrue("Adaptive Server Enterprise is a valid product name", database.isSybaseProductName("Adaptive Server Enterprise"));
}
/**
* Configure the {@code Executor} associated with the provided {@code Database}
* to return the specified rows.
* @param database the database for which to configure an {@code Executor}
* @param viewInfoRows the rows to be returned by the {@code Executor}
*/
private void configureExecutor(Database database, String... viewInfoRows) {
Executor executor = createNiceMock(Executor.class);
try {
@SuppressWarnings("unchecked")
Class<String> stringClassMatcher = (Class<String>)anyObject();
expect(executor.queryForList((SqlStatement)anyObject(), stringClassMatcher)).andReturn(asList(viewInfoRows));
} catch (DatabaseException e) {
throw new RuntimeException(e);
}
replay(executor);
ExecutorService.getInstance().setExecutor(database, executor);
}
@Test
public void testGetViewDefinitionWhenNoRows() throws Exception {
SybaseDatabase database = new SybaseDatabase();
configureExecutor(database);
assertEquals("", database.getViewDefinition(new CatalogAndSchema(null, "dbo"), "view_name"));
}
@Test
public void testGetViewDefinitionWhenSingleRow() throws Exception {
SybaseDatabase database = new SybaseDatabase();
configureExecutor(database, "foo");
assertEquals("foo", database.getViewDefinition(new CatalogAndSchema(null, "dbo"), "view_name"));
}
@Test
public void testGetViewDefinitionWhenMultipleRows() throws Exception {
SybaseDatabase database = new SybaseDatabase();
configureExecutor(database, "foo", " bar", " bat");
assertEquals("foo bar bat", database.getViewDefinition(new CatalogAndSchema(null, "dbo"), "view_name"));
}
@Test
public void testGetDatabaseMajorVersionWhenImplemented() throws Exception {
DatabaseConnection connection = createNiceMock(DatabaseConnection.class);
expect(connection.getDatabaseMajorVersion()).andReturn(15);
replay(connection);
SybaseDatabase database = new SybaseDatabase();
database.setConnection(connection);
assertEquals(15, database.getDatabaseMajorVersion());
}
@Test
public void testGetDatabaseMinorVersionWhenImplemented() throws Exception {
DatabaseConnection connection = createNiceMock(DatabaseConnection.class);
expect(connection.getDatabaseMinorVersion()).andReturn(5);
replay(connection);
SybaseDatabase database = new SybaseDatabase();
database.setConnection(connection);
assertEquals(5, database.getDatabaseMinorVersion());
}
@Test
public void testGetDatabaseMajorVersionWhenNotImplemented() throws Exception {
DatabaseConnection connection = createNiceMock(DatabaseConnection.class);
expect(connection.getDatabaseMajorVersion()).andThrow(new UnsupportedOperationException());
replay(connection);
SybaseDatabase database = new SybaseDatabase();
database.setConnection(connection);
assertEquals(-1, database.getDatabaseMajorVersion());
}
@Test
public void testGetDatabaseMinorVersionWhenNotImplemented() throws Exception {
DatabaseConnection connection = createNiceMock(DatabaseConnection.class);
expect(connection.getDatabaseMinorVersion()).andThrow(new UnsupportedOperationException());
replay(connection);
SybaseDatabase database = new SybaseDatabase();
database.setConnection(connection);
assertEquals(-1, database.getDatabaseMinorVersion());
}
}
| {
"content_hash": "915d90463a25671f9773f59c36570454",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 127,
"avg_line_length": 36.49593495934959,
"alnum_prop": 0.784361773223435,
"repo_name": "AlisonSouza/liquibase",
"id": "9e2533cec39584993216c1133fbedab62b3ee9d3",
"size": "4489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "liquibase-core/src/test/java/liquibase/database/core/SybaseDatabaseTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "621"
},
{
"name": "CSS",
"bytes": "1202"
},
{
"name": "Groff",
"bytes": "2297"
},
{
"name": "HTML",
"bytes": "2223"
},
{
"name": "Inno Setup",
"bytes": "2522"
},
{
"name": "Java",
"bytes": "3330311"
},
{
"name": "PLSQL",
"bytes": "5380"
},
{
"name": "PLpgSQL",
"bytes": "502"
},
{
"name": "Puppet",
"bytes": "4616"
},
{
"name": "Ruby",
"bytes": "4959"
},
{
"name": "SQLPL",
"bytes": "1791"
},
{
"name": "Shell",
"bytes": "3976"
}
],
"symlink_target": ""
} |
package org.drools.eclipse.flow.ruleflow.view.property.constraint;
import java.util.List;
import java.util.Map;
import org.drools.eclipse.editors.DRLSourceViewerConfig;
import org.drools.eclipse.editors.scanners.DRLPartionScanner;
import org.drools.eclipse.flow.common.view.property.EditBeanDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.rules.FastPartitioner;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.jbpm.workflow.core.WorkflowProcess;
import org.jbpm.workflow.core.node.MilestoneNode;
/**
* Dialog for editing constraints.
*/
public class MilestoneConstraintDialog extends EditBeanDialog<String> {
private WorkflowProcess process;
private TabFolder tabFolder;
private SourceViewer constraintViewer;
private ConstraintCompletionProcessor completionProcessor;
public MilestoneConstraintDialog(Shell parentShell, WorkflowProcess process, MilestoneNode milestone) {
super(parentShell, "Constraint editor");
this.process = process;
setValue(milestone.getConstraint());
}
protected String updateValue(String value) {
if (tabFolder.getSelectionIndex() == 0) {
return getConstraintText();
}
return null;
}
protected Point getInitialSize() {
return new Point(600, 450);
}
private Control createTextualEditor(Composite parent) {
constraintViewer = new SourceViewer(parent, null, SWT.BORDER);
constraintViewer.configure(new DRLSourceViewerConfig(null) {
public IReconciler getReconciler(ISourceViewer sourceViewer) {
return null;
}
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
ContentAssistant assistant = new ContentAssistant();
completionProcessor = new ConstraintCompletionProcessor(process);
assistant.setContentAssistProcessor(
completionProcessor, IDocument.DEFAULT_CONTENT_TYPE);
assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY);
return assistant;
}
});
String value = (String) getValue();
if (value == null) {
value = "";
}
IDocument document = new Document(value);
constraintViewer.setDocument(document);
IDocumentPartitioner partitioner =
new FastPartitioner(
new DRLPartionScanner(),
DRLPartionScanner.LEGAL_CONTENT_TYPES);
partitioner.connect(document);
document.setDocumentPartitioner(partitioner);
constraintViewer.getControl().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.character == ' ' && e.stateMask == SWT.CTRL) {
constraintViewer.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
}
}
public void keyReleased(KeyEvent e) {
}
});
return constraintViewer.getControl();
}
private String getConstraintText() {
return constraintViewer.getDocument().get();
}
public Control createDialogArea(Composite parent) {
GridLayout layout = new GridLayout();
parent.setLayout(layout);
layout.numColumns = 2;
Composite top = new Composite(parent, SWT.NONE);
GridData gd = new GridData();
gd.horizontalSpan = 2;
gd.grabExcessHorizontalSpace = true;
top.setLayoutData(gd);
layout = new GridLayout();
layout.numColumns = 3;
top.setLayout(layout);
Button importButton = new Button(top, SWT.PUSH);
importButton.setText("Imports ...");
importButton.setFont(JFaceResources.getDialogFont());
importButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
importButtonPressed();
}
});
gd = new GridData();
importButton.setLayoutData(gd);
Button globalButton = new Button(top, SWT.PUSH);
globalButton.setText("Globals ...");
globalButton.setFont(JFaceResources.getDialogFont());
globalButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
globalButtonPressed();
}
});
gd = new GridData();
globalButton.setLayoutData(gd);
tabFolder = new TabFolder(parent, SWT.NONE);
gd = new GridData();
gd.horizontalSpan = 3;
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.verticalAlignment = GridData.FILL;
gd.horizontalAlignment = GridData.FILL;
tabFolder.setLayoutData(gd);
TabItem textEditorTab = new TabItem(tabFolder, SWT.NONE);
textEditorTab.setText("Textual Editor");
textEditorTab.setControl(createTextualEditor(tabFolder));
return tabFolder;
}
private void importButtonPressed() {
final Runnable r = new Runnable() {
public void run() {
RuleFlowImportsDialog dialog =
new RuleFlowImportsDialog(getShell(), process);
dialog.create();
int code = dialog.open();
if (code != CANCEL) {
List<String> imports = dialog.getImports();
process.setImports(imports);
List<String> functionImports = dialog.getFunctionImports();
process.setFunctionImports(functionImports);
completionProcessor.reset();
}
}
};
r.run();
}
private void globalButtonPressed() {
final Runnable r = new Runnable() {
public void run() {
RuleFlowGlobalsDialog dialog =
new RuleFlowGlobalsDialog(getShell(), process);
dialog.create();
int code = dialog.open();
if (code != CANCEL) {
Map<String, String> globals = dialog.getGlobals();
process.setGlobals(globals);
completionProcessor.reset();
}
}
};
r.run();
}
}
| {
"content_hash": "1d05c7ef00b3e69c336eeee1eaa68b65",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 107,
"avg_line_length": 37.255102040816325,
"alnum_prop": 0.6454396055875102,
"repo_name": "psiroky/droolsjbpm-tools",
"id": "7b2796f0613b694581c2cd0fe46bfb4ebaed868b",
"size": "7895",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "drools-eclipse/org.drools.eclipse/src/main/java/org/drools/eclipse/flow/ruleflow/view/property/constraint/MilestoneConstraintDialog.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Shared
{
internal interface IDocumentSupportsFeatureService : IWorkspaceService
{
bool SupportsCodeFixes(Document document);
bool SupportsRefactorings(Document document);
bool SupportsRename(Document document);
bool SupportsNavigationToAnyPosition(Document document);
}
[ExportWorkspaceService(typeof(IDocumentSupportsFeatureService), ServiceLayer.Default), Shared]
internal class DefaultDocumentSupportsFeatureService : IDocumentSupportsFeatureService
{
[ImportingConstructor]
public DefaultDocumentSupportsFeatureService()
{
}
public bool SupportsCodeFixes(Document document)
=> true;
public bool SupportsNavigationToAnyPosition(Document document)
=> true;
public bool SupportsRefactorings(Document document)
=> true;
public bool SupportsRename(Document document)
=> true;
}
}
| {
"content_hash": "74fe8ef29fbc638b9d0789e7f787ac6a",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 161,
"avg_line_length": 33,
"alnum_prop": 0.7192982456140351,
"repo_name": "nguerrera/roslyn",
"id": "0423494f6cd7a188f450b5b5ce2f02986fdebd62",
"size": "1256",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Features/Core/Portable/Shared/IDocumentSupportsFeatureService.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "8757"
},
{
"name": "C#",
"bytes": "122747926"
},
{
"name": "C++",
"bytes": "5392"
},
{
"name": "CMake",
"bytes": "9153"
},
{
"name": "Dockerfile",
"bytes": "2102"
},
{
"name": "F#",
"bytes": "508"
},
{
"name": "PowerShell",
"bytes": "217803"
},
{
"name": "Rich Text Format",
"bytes": "14887"
},
{
"name": "Shell",
"bytes": "83770"
},
{
"name": "Smalltalk",
"bytes": "622"
},
{
"name": "Visual Basic",
"bytes": "70046841"
}
],
"symlink_target": ""
} |
:block(Popup)
{
position: absolute;
}
| {
"content_hash": "630183449d12a329e7de325bcd8c6a91",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 23,
"avg_line_length": 10.5,
"alnum_prop": 0.6190476190476191,
"repo_name": "dfilatov/vidom-ui",
"id": "bfede151e95a298dcfb02f09a321f347df7d745f",
"size": "42",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/Popup/Popup.post.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "44459"
},
{
"name": "HTML",
"bytes": "1424"
},
{
"name": "JavaScript",
"bytes": "178763"
}
],
"symlink_target": ""
} |
/* PP - Post Processing for THREE.js
* @author rdad / http://www.whiteflashwhitehit.com
* @link three.js https://github.com/mrdoob/three.js
*/
/*
* @todo : affectation d'un nom perso pour les shaders (permet d'utiliser plusieur fois le même shader)
**/
var PP = PP || {
enabled: true,
list: {},
renderer: null,
context3D: {},
context2D: {},
contextFinal: {},
config: {
camera: { z:100},
rtTexture: { minFilter: THREE.LinearFilter,
magFilter: THREE.NearestFilter,
format: THREE.RGBFormat,
stencilBuffer: false
},
dimension: { width: window.innerWidth,
height: window.innerHeight
},
resolution: 1.0
},
rendered: null,
mouse: { enabled:false,
x:0,
y:0
},
TEXTURE: 0,
SHADER: 1,
e: null,
init: function( parameters ){
parameters = parameters || {};
this.config.camera.z = ( parameters.camera_z !== undefined ) ? parameters.camera_z : this.config.camera.z;
this.config.dimension = ( parameters.dimension !== undefined ) ? parameters.dimension : this.config.dimension;
this.config.resolution = ( parameters.resolution !== undefined ) ? parameters.resolution : this.config.resolution;
this.gui.enabled = ( parameters.guiEnabled !== undefined ) ? parameters.guiEnabled : false;
// --- résolution
this.config.dimension.width *= this.config.resolution;
this.config.dimension.height *= this.config.resolution;
// --- 2D context & Final
this.context2D = new PP.Context();
this.contextFinal = new PP.Context({quadReverse: true});
// --- 3D context
this.renderer = ( parameters.renderer !== undefined ) ? parameters.renderer : null;
this.context3D.scene = ( parameters.scene !== undefined ) ? parameters.scene : null;
this.context3D.camera = ( parameters.camera !== undefined ) ? parameters.camera : null;
if(parameters.clearColor !== undefined) this.renderer.setClearColorHex( parameters.clearColor, 0.0 );
// --- Gui
if(this.gui.enabled && DAT.GUI != undefined)
{
this.gui.handler = new DAT.GUI();
this.gui.handler.close();
}
// --- ready ?
if(this.renderer === null || this.context3D.scene === null || this.context3D.camera === null)
{
this.error('PP not initialized correctly: Three infos not set', true);
return this;
}
return this;
},
setScene: function(scene, camera){
this.context3D.scene = scene;
this.context3D.camera = camera;
},
addTexture:function(name, parameters){
if(this.enabled === false) return this;
var texture = new PP.Texture(name, parameters);
if(this.debug) this.debug.addSprite(texture);
this.list[name] = texture;
this.error('Texture "'+name+'" successfully added');
return this;
},
addShader: function(name, parameters){
if(this.enabled === false) return this;
var shader = new PP.Shader(name, parameters);
if(this.guiControl) this.gui.addControl(shader);
if(this.debug) this.debug.addSprite(shader);
this.list[shader.name] = shader;
this.error('Shader "'+name+'" successfully added');
return this;
},
loadShader: function( name, uniforms, parameters ){
if(this.enabled === false) return this;
if(typeof this.lib === 'undefined' || typeof this.lib.shader.shaders[name] === 'undefined')
{
this.error(["Shader '", name, "' doesn't exist in PP.lib"].join(''), true);
return;
}
var shader = this.lib.shader.get( name, uniforms, parameters );
if(PP.gui.enabled) PP.gui.addControl(shader);
if(PP.debug) PP.debug.addSprite(shader);
this.list[shader.name] = shader;
this.error('Shader "'+name+'" successfully loaded');
return this;
},
get: function( name )
{
if(this.enabled === false) return;
if(this.list[name])
{
return this.list[name];
}else{
this.error([name," doesn't exist."].join(''), true);
}
},
start: function(){
//this.renderer.clear();
this.rendered = null;
},
// ---------------------------------- Render -------------------------------
renderScene: function() {
this.rendered = '_scene';
return this;
},
renderTexture: function(name){
if(this.enabled === false) return this;
this.rendered = name;
return this;
},
renderShader: function(name) {
if(this.enabled === false) return this;
this.rendered = name;
this.e = this.list[name];
if(typeof this.e === 'undefined')
{
this.error(["Shader '", name, "' can't be found: no render"].join(''), true);
return this;
}
this.e = this.list[name];
this.context2D.quad.materials = [ this.e.material ];
if(this.e.update) this.e.update(this.e);
this.renderer.render( this.context2D.scene,
this.context2D.camera,
this.e.textureOut,
true);
return this;
},
toTexture:function( name ) {
if(this.enabled === false) return;
if(this.rendered === '_scene')
{
this.renderer.render( this.context3D.scene,
this.context3D.camera,
this.list[name].textureOut,
true);
}else{
if(name == this.rendered) return;
var e = this.list[name],
s = PP.list[this.rendered];
if(e.type == PP.SHADER && typeof e.material.uniforms.textureIn != 'undefined'){
e.material.uniforms.textureIn.texture = s.textureOut;
}
}
},
toScene: function(){
if(this.enabled === false) return;
if(this.debug){
this.debug.update();
}
this.contextFinal.quad.materials[0].map = this.list[this.rendered].textureOut;
this.renderer.render( this.contextFinal.scene, this.contextFinal.camera );
},
error:function(message, stopProcess)
{
if(this.debug){
this.debug.toConsole(message);
}
if(typeof stopProcess != undefined && stopProcess == true){
this.enabled = false;
PP.debug.showConsole();
}
},
getLastRenderedShaderName: function()
{
return this.rendered;
}
};
| {
"content_hash": "87d3b0daeeb1fc924810083799a503d6",
"timestamp": "",
"source": "github",
"line_count": 261,
"max_line_length": 138,
"avg_line_length": 29.796934865900383,
"alnum_prop": 0.4756332776134756,
"repo_name": "rdad/PP.js",
"id": "8dc5e5a4ab1b52ccaa4206f98e08055e75a4150e",
"size": "7779",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/PP.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "182545"
}
],
"symlink_target": ""
} |
use vut::project::Vut;
use crate::error::*;
use crate::ui::StderrUiHandler;
pub fn generate() -> Result<(), CliError> {
let mut ui = StderrUiHandler::new();
let vut = Vut::from_current_dir(&mut ui)?;
eprint!("Generating output... ");
vut.generate_output(&mut ui)?;
eprintln!("Done.");
Ok(())
}
| {
"content_hash": "f47f17575774abc4d0fafd81ee164e11",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 46,
"avg_line_length": 18.055555555555557,
"alnum_prop": 0.5938461538461538,
"repo_name": "forbjok/vut",
"id": "181594722b5ecaceedc6619a0f33aca14f26777b",
"size": "325",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cli/src/command/generate.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PowerShell",
"bytes": "3166"
},
{
"name": "Rust",
"bytes": "82443"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/mendeley_red"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bg_hexpattern" />
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/space_between_logo_and_buttons"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="@drawable/logo_mendeley" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/button_margin"
android:layout_marginRight="@dimen/button_margin" >
<Button
android:id="@+id/signinButton"
android:layout_width="@dimen/phone_button_width"
android:layout_height="@dimen/button_height"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="@drawable/button_signin"
android:text="@string/signin_button_text"
android:textColor="@color/mendeley_red"
android:textSize="@dimen/signin_button_text" />
<Button
android:id="@+id/signupButton"
android:layout_width="@dimen/phone_button_width"
android:layout_height="@dimen/button_height"
android:layout_alignParentLeft="true"
android:layout_below="@+id/signinButton"
android:layout_marginTop="@dimen/button_margin"
android:background="@drawable/button_signup"
android:text="@string/signup_button_text"
android:textColor="@color/create_account_botton_text"
android:textSize="@dimen/signin_button_text" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout> | {
"content_hash": "a5518c7331698484de9d313634fbf0a4",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 79,
"avg_line_length": 39.955882352941174,
"alnum_prop": 0.6194331983805668,
"repo_name": "thirdiron/mendeley-android-sdk",
"id": "85b4828c1511f4db133807c7e8baf195b0b5c9aa",
"size": "2717",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/src/main/res/layout/splash_layout.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "533814"
}
],
"symlink_target": ""
} |
using namespace lldb;
using namespace lldb_private;
NativeRegisterContext::NativeRegisterContext(NativeThreadProtocol &thread)
: m_thread(thread) {}
// Destructor
NativeRegisterContext::~NativeRegisterContext() {}
// FIXME revisit invalidation, process stop ids, etc. Right now we don't
// support caching in NativeRegisterContext. We can do this later by utilizing
// NativeProcessProtocol::GetStopID () and adding a stop id to
// NativeRegisterContext.
// void
// NativeRegisterContext::InvalidateIfNeeded (bool force) {
// ProcessSP process_sp (m_thread.GetProcess());
// bool invalidate = force;
// uint32_t process_stop_id = UINT32_MAX;
// if (process_sp)
// process_stop_id = process_sp->GetStopID();
// else
// invalidate = true;
// if (!invalidate)
// invalidate = process_stop_id != GetStopID();
// if (invalidate)
// {
// InvalidateAllRegisters ();
// SetStopID (process_stop_id);
// }
// }
const RegisterInfo *
NativeRegisterContext::GetRegisterInfoByName(llvm::StringRef reg_name,
uint32_t start_idx) {
if (reg_name.empty())
return nullptr;
const uint32_t num_registers = GetRegisterCount();
for (uint32_t reg = start_idx; reg < num_registers; ++reg) {
const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg);
if (reg_name.equals_lower(reg_info->name) ||
reg_name.equals_lower(reg_info->alt_name))
return reg_info;
}
return nullptr;
}
const RegisterInfo *NativeRegisterContext::GetRegisterInfo(uint32_t kind,
uint32_t num) {
const uint32_t reg_num = ConvertRegisterKindToRegisterNumber(kind, num);
if (reg_num == LLDB_INVALID_REGNUM)
return nullptr;
return GetRegisterInfoAtIndex(reg_num);
}
const char *NativeRegisterContext::GetRegisterName(uint32_t reg) {
const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg);
if (reg_info)
return reg_info->name;
return nullptr;
}
const char *NativeRegisterContext::GetRegisterSetNameForRegisterAtIndex(
uint32_t reg_index) const {
const RegisterInfo *const reg_info = GetRegisterInfoAtIndex(reg_index);
if (!reg_info)
return nullptr;
for (uint32_t set_index = 0; set_index < GetRegisterSetCount(); ++set_index) {
const RegisterSet *const reg_set = GetRegisterSet(set_index);
if (!reg_set)
continue;
for (uint32_t reg_num_index = 0; reg_num_index < reg_set->num_registers;
++reg_num_index) {
const uint32_t reg_num = reg_set->registers[reg_num_index];
// FIXME double check we're checking the right register kind here.
if (reg_info->kinds[RegisterKind::eRegisterKindLLDB] == reg_num) {
// The given register is a member of this register set. Return the
// register set name.
return reg_set->name;
}
}
}
// Didn't find it.
return nullptr;
}
lldb::addr_t NativeRegisterContext::GetPC(lldb::addr_t fail_value) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
LLDB_REGNUM_GENERIC_PC);
LLDB_LOGF(log,
"NativeRegisterContext::%s using reg index %" PRIu32
" (default %" PRIu64 ")",
__FUNCTION__, reg, fail_value);
const uint64_t retval = ReadRegisterAsUnsigned(reg, fail_value);
LLDB_LOGF(log, "NativeRegisterContext::%s " PRIu32 " retval %" PRIu64,
__FUNCTION__, retval);
return retval;
}
lldb::addr_t
NativeRegisterContext::GetPCfromBreakpointLocation(lldb::addr_t fail_value) {
return GetPC(fail_value);
}
Status NativeRegisterContext::SetPC(lldb::addr_t pc) {
uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
LLDB_REGNUM_GENERIC_PC);
return WriteRegisterFromUnsigned(reg, pc);
}
lldb::addr_t NativeRegisterContext::GetSP(lldb::addr_t fail_value) {
uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
LLDB_REGNUM_GENERIC_SP);
return ReadRegisterAsUnsigned(reg, fail_value);
}
Status NativeRegisterContext::SetSP(lldb::addr_t sp) {
uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
LLDB_REGNUM_GENERIC_SP);
return WriteRegisterFromUnsigned(reg, sp);
}
lldb::addr_t NativeRegisterContext::GetFP(lldb::addr_t fail_value) {
uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
LLDB_REGNUM_GENERIC_FP);
return ReadRegisterAsUnsigned(reg, fail_value);
}
Status NativeRegisterContext::SetFP(lldb::addr_t fp) {
uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
LLDB_REGNUM_GENERIC_FP);
return WriteRegisterFromUnsigned(reg, fp);
}
lldb::addr_t NativeRegisterContext::GetReturnAddress(lldb::addr_t fail_value) {
uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
LLDB_REGNUM_GENERIC_RA);
return ReadRegisterAsUnsigned(reg, fail_value);
}
lldb::addr_t NativeRegisterContext::GetFlags(lldb::addr_t fail_value) {
uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
LLDB_REGNUM_GENERIC_FLAGS);
return ReadRegisterAsUnsigned(reg, fail_value);
}
lldb::addr_t
NativeRegisterContext::ReadRegisterAsUnsigned(uint32_t reg,
lldb::addr_t fail_value) {
if (reg != LLDB_INVALID_REGNUM)
return ReadRegisterAsUnsigned(GetRegisterInfoAtIndex(reg), fail_value);
return fail_value;
}
uint64_t
NativeRegisterContext::ReadRegisterAsUnsigned(const RegisterInfo *reg_info,
lldb::addr_t fail_value) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
if (reg_info) {
RegisterValue value;
Status error = ReadRegister(reg_info, value);
if (error.Success()) {
LLDB_LOGF(log,
"NativeRegisterContext::%s ReadRegister() succeeded, value "
"%" PRIu64,
__FUNCTION__, value.GetAsUInt64());
return value.GetAsUInt64();
} else {
LLDB_LOGF(log,
"NativeRegisterContext::%s ReadRegister() failed, error %s",
__FUNCTION__, error.AsCString());
}
} else {
LLDB_LOGF(log, "NativeRegisterContext::%s ReadRegister() null reg_info",
__FUNCTION__);
}
return fail_value;
}
Status NativeRegisterContext::WriteRegisterFromUnsigned(uint32_t reg,
uint64_t uval) {
if (reg == LLDB_INVALID_REGNUM)
return Status("NativeRegisterContext::%s (): reg is invalid", __FUNCTION__);
return WriteRegisterFromUnsigned(GetRegisterInfoAtIndex(reg), uval);
}
Status
NativeRegisterContext::WriteRegisterFromUnsigned(const RegisterInfo *reg_info,
uint64_t uval) {
assert(reg_info);
if (!reg_info)
return Status("reg_info is nullptr");
RegisterValue value;
if (!value.SetUInt(uval, reg_info->byte_size))
return Status("RegisterValue::SetUInt () failed");
return WriteRegister(reg_info, value);
}
lldb::tid_t NativeRegisterContext::GetThreadID() const {
return m_thread.GetID();
}
uint32_t NativeRegisterContext::NumSupportedHardwareBreakpoints() { return 0; }
uint32_t NativeRegisterContext::SetHardwareBreakpoint(lldb::addr_t addr,
size_t size) {
return LLDB_INVALID_INDEX32;
}
Status NativeRegisterContext::ClearAllHardwareBreakpoints() {
return Status("not implemented");
}
bool NativeRegisterContext::ClearHardwareBreakpoint(uint32_t hw_idx) {
return false;
}
Status NativeRegisterContext::GetHardwareBreakHitIndex(uint32_t &bp_index,
lldb::addr_t trap_addr) {
bp_index = LLDB_INVALID_INDEX32;
return Status("not implemented");
}
uint32_t NativeRegisterContext::NumSupportedHardwareWatchpoints() { return 0; }
uint32_t NativeRegisterContext::SetHardwareWatchpoint(lldb::addr_t addr,
size_t size,
uint32_t watch_flags) {
return LLDB_INVALID_INDEX32;
}
bool NativeRegisterContext::ClearHardwareWatchpoint(uint32_t hw_index) {
return false;
}
Status NativeRegisterContext::ClearAllHardwareWatchpoints() {
return Status("not implemented");
}
Status NativeRegisterContext::IsWatchpointHit(uint32_t wp_index, bool &is_hit) {
is_hit = false;
return Status("not implemented");
}
Status NativeRegisterContext::GetWatchpointHitIndex(uint32_t &wp_index,
lldb::addr_t trap_addr) {
wp_index = LLDB_INVALID_INDEX32;
return Status("not implemented");
}
Status NativeRegisterContext::IsWatchpointVacant(uint32_t wp_index,
bool &is_vacant) {
is_vacant = false;
return Status("not implemented");
}
lldb::addr_t NativeRegisterContext::GetWatchpointAddress(uint32_t wp_index) {
return LLDB_INVALID_ADDRESS;
}
lldb::addr_t NativeRegisterContext::GetWatchpointHitAddress(uint32_t wp_index) {
return LLDB_INVALID_ADDRESS;
}
bool NativeRegisterContext::HardwareSingleStep(bool enable) { return false; }
Status NativeRegisterContext::ReadRegisterValueFromMemory(
const RegisterInfo *reg_info, lldb::addr_t src_addr, size_t src_len,
RegisterValue ®_value) {
Status error;
if (reg_info == nullptr) {
error.SetErrorString("invalid register info argument.");
return error;
}
// Moving from addr into a register
//
// Case 1: src_len == dst_len
//
// |AABBCCDD| Address contents
// |AABBCCDD| Register contents
//
// Case 2: src_len > dst_len
//
// Status! (The register should always be big enough to hold the data)
//
// Case 3: src_len < dst_len
//
// |AABB| Address contents
// |AABB0000| Register contents [on little-endian hardware]
// |0000AABB| Register contents [on big-endian hardware]
if (src_len > RegisterValue::kMaxRegisterByteSize) {
error.SetErrorString("register too small to receive memory data");
return error;
}
const size_t dst_len = reg_info->byte_size;
if (src_len > dst_len) {
error.SetErrorStringWithFormat(
"%" PRIu64 " bytes is too big to store in register %s (%" PRIu64
" bytes)",
static_cast<uint64_t>(src_len), reg_info->name,
static_cast<uint64_t>(dst_len));
return error;
}
NativeProcessProtocol &process = m_thread.GetProcess();
uint8_t src[RegisterValue::kMaxRegisterByteSize];
// Read the memory
size_t bytes_read;
error = process.ReadMemory(src_addr, src, src_len, bytes_read);
if (error.Fail())
return error;
// Make sure the memory read succeeded...
if (bytes_read != src_len) {
// This might happen if we read _some_ bytes but not all
error.SetErrorStringWithFormat("read %" PRIu64 " of %" PRIu64 " bytes",
static_cast<uint64_t>(bytes_read),
static_cast<uint64_t>(src_len));
return error;
}
// We now have a memory buffer that contains the part or all of the register
// value. Set the register value using this memory data.
// TODO: we might need to add a parameter to this function in case the byte
// order of the memory data doesn't match the process. For now we are
// assuming they are the same.
reg_value.SetFromMemoryData(reg_info, src, src_len, process.GetByteOrder(),
error);
return error;
}
Status NativeRegisterContext::WriteRegisterValueToMemory(
const RegisterInfo *reg_info, lldb::addr_t dst_addr, size_t dst_len,
const RegisterValue ®_value) {
uint8_t dst[RegisterValue::kMaxRegisterByteSize];
Status error;
NativeProcessProtocol &process = m_thread.GetProcess();
// TODO: we might need to add a parameter to this function in case the byte
// order of the memory data doesn't match the process. For now we are
// assuming they are the same.
const size_t bytes_copied = reg_value.GetAsMemoryData(
reg_info, dst, dst_len, process.GetByteOrder(), error);
if (error.Success()) {
if (bytes_copied == 0) {
error.SetErrorString("byte copy failed.");
} else {
size_t bytes_written;
error = process.WriteMemory(dst_addr, dst, bytes_copied, bytes_written);
if (error.Fail())
return error;
if (bytes_written != bytes_copied) {
// This might happen if we read _some_ bytes but not all
error.SetErrorStringWithFormat("only wrote %" PRIu64 " of %" PRIu64
" bytes",
static_cast<uint64_t>(bytes_written),
static_cast<uint64_t>(bytes_copied));
}
}
}
return error;
}
uint32_t
NativeRegisterContext::ConvertRegisterKindToRegisterNumber(uint32_t kind,
uint32_t num) const {
const uint32_t num_regs = GetRegisterCount();
assert(kind < kNumRegisterKinds);
for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) {
const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg_idx);
if (reg_info->kinds[kind] == num)
return reg_idx;
}
return LLDB_INVALID_REGNUM;
}
| {
"content_hash": "34ad928ab3fe2a918c308f7ea205cb5d",
"timestamp": "",
"source": "github",
"line_count": 405,
"max_line_length": 80,
"avg_line_length": 33.901234567901234,
"alnum_prop": 0.6396941005098324,
"repo_name": "llvm-mirror/lldb",
"id": "fe40073eb59de3e67d906c8c2272440d9d919306",
"size": "14354",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "source/Host/common/NativeRegisterContext.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "131618"
},
{
"name": "C",
"bytes": "195293"
},
{
"name": "C++",
"bytes": "23346708"
},
{
"name": "CMake",
"bytes": "167302"
},
{
"name": "DTrace",
"bytes": "334"
},
{
"name": "LLVM",
"bytes": "6106"
},
{
"name": "Makefile",
"bytes": "50396"
},
{
"name": "Objective-C",
"bytes": "106956"
},
{
"name": "Objective-C++",
"bytes": "24806"
},
{
"name": "Perl",
"bytes": "72175"
},
{
"name": "Python",
"bytes": "3669886"
},
{
"name": "Shell",
"bytes": "6573"
},
{
"name": "Vim script",
"bytes": "8434"
}
],
"symlink_target": ""
} |
package scriptella;
import scriptella.execution.EtlExecutor;
import scriptella.execution.EtlExecutorException;
import scriptella.util.RepeatingInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* TODO: Add documentation
*
* @author Fyodor Kupolov
* @version 1.0
*/
public class SQLSupportPerfTest extends DBTestCase {
private static final byte SQL[] = "update ${'test'} set id=?{property};rollback;".getBytes();
private static final byte SQL2[] = "update test set id=?{property};".getBytes();
private static final byte SQL3[] = "update test set id=12345;".getBytes();
/**
* History:
* 04.11.2006 - Duron 1.7Mhz - 1400 ms
* 11.09.2006 - Duron 1.7Mhz - 1578 ms
*/
public void test() throws EtlExecutorException {
getConnection("sqlsupport");
AbstractTestCase.testURLHandler = new TestURLHandler() {
public InputStream getInputStream(final URL u) {
return new RepeatingInputStream(SQL, 50000);
}
public OutputStream getOutputStream(final URL u) {
throw new UnsupportedOperationException();
}
public int getContentLength(final URL u) {
return 50000 * SQL.length;
}
};
EtlExecutor se = newEtlExecutor();
se.execute();
}
/**
* History:
* 04.11.2006 - Duron 1.7Mhz - 2300 ms
* 11.09.2006 - Duron 1.7Mhz - 2578 ms
*
* @throws EtlExecutorException
* @throws SQLException
* @throws IOException
*/
public void testCompare() throws EtlExecutorException, SQLException, IOException {
final int n = 20000;
Connection con = getConnection("sqlsupport");
AbstractTestCase.testURLHandler = new TestURLHandler() {
public InputStream getInputStream(final URL u) {
return new RepeatingInputStream(SQL2, n);
}
public OutputStream getOutputStream(final URL u) {
throw new UnsupportedOperationException();
}
public int getContentLength(final URL u) {
return n * SQL.length;
}
};
EtlExecutor se = newEtlExecutor();
long ti = System.currentTimeMillis();
se.execute();
ti = System.currentTimeMillis() - ti;
System.out.println("ti = " + ti);
//Now let's test direct HSQL connection
RepeatingInputStream ris = new RepeatingInputStream("update test set id=?\n".getBytes(), n);
BufferedReader br = new BufferedReader(new InputStreamReader(ris));
ti = System.currentTimeMillis();
for (String s; (s = br.readLine()) != null;) {
PreparedStatement ps = con.prepareStatement(s);
ps.setObject(1, 1);
ps.execute();
ps.close();
}
con.commit();
ti = System.currentTimeMillis() - ti;
System.out.println("ti hsql = " + ti);
}
/**
* History:
* 19.01.2007 - Duron 1.7Mhz - 330 ms
*
* @throws EtlExecutorException
* @throws SQLException
* @throws IOException
*/
public void testBulkUpdates() throws EtlExecutorException {
//50000 identical statements
getConnection("sqlsupport");
AbstractTestCase.testURLHandler = new TestURLHandler() {
public InputStream getInputStream(final URL u) {
return new RepeatingInputStream(SQL3, 50000);
}
public OutputStream getOutputStream(final URL u) {
throw new UnsupportedOperationException();
}
public int getContentLength(final URL u) {
return 50000 * SQL3.length;
}
};
EtlExecutor se = newEtlExecutor();
se.execute();
}
public static void main(final String args[]) throws EtlExecutorException {
SQLSupportPerfTest t = new SQLSupportPerfTest();
t.test();
}
}
| {
"content_hash": "e894d8712356ca779281cdbda8878cae",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 100,
"avg_line_length": 31.107142857142858,
"alnum_prop": 0.5880597014925373,
"repo_name": "scriptella/scriptella-etl",
"id": "bda053eabc642ba99f5930be35ef30b9f65307d9",
"size": "4986",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/scriptella/SQLSupportPerfTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1794"
},
{
"name": "HTML",
"bytes": "90799"
},
{
"name": "Java",
"bytes": "1289261"
},
{
"name": "Shell",
"bytes": "1508"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "e5da2ad756955daefc03dc522a60c601",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "f0a35e96666d5de901c4288d56c59df6c3fba622",
"size": "174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Silene/Lychnis cuneifolia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Verifying a signature with additional restrictions.</title>
<meta name="GENERATOR" content="Modular DocBook HTML Stylesheet Version 1.79">
<link rel="HOME" title="XML Security Library Reference Manual" href="index.html">
<link rel="UP" title="Examples." href="xmlsec-examples.html">
<link rel="PREVIOUS" title="Verifying a signature with X509 certificates." href="xmlsec-verify-with-x509.html">
<link rel="NEXT" title="Encrypting data with a template file." href="xmlsec-encrypt-template-file.html">
<meta name="GENERATOR" content="GTK-Doc V1.11 (SGML mode)">
<style type="text/css">.synopsis, .classsynopsis {
background: #eeeeee;
border: solid 1px #aaaaaa;
padding: 0.5em;
}
.programlisting {
background: #eeeeff;
border: solid 1px #aaaaff;
padding: 0.5em;
}
.variablelist {
padding: 4px;
margin-left: 3em;
}
.navigation {
background: #ffeeee;
border: solid 1px #ffaaaa;
margin-top: 0.5em;
margin-bottom: 0.5em;
}
.navigation a {
color: #770000;
}
.navigation a:visited {
color: #550000;
}
.navigation .title {
font-size: 200%;
}</style>
</head>
<body><table witdh="100%" valign="top"><tr valign="top">
<td valign="top" align="left" width="210">
<img src="../images/logo.gif" alt="XML Security Library" border="0"><p></p>
<ul>
<li><a href="../index.html">Home</a></li>
<li><a href="../download.html">Download</a></li>
<li><a href="../news.html">News</a></li>
<li><a href="../documentation.html">Documentation</a></li>
<ul>
<li><a href="../faq.html">FAQ</a></li>
<li><a href="../api/xmlsec-notes.html">Tutorial</a></li>
<li><a href="../api/xmlsec-reference.html">API reference</a></li>
<li><a href="../api/xmlsec-examples.html">Examples</a></li>
</ul>
<li><a href="../xmldsig.html">XML Digital Signature</a></li>
<ul><li><a href="http://www.aleksey.com/xmlsec/xmldsig-verifier.html">Online Verifier</a></li></ul>
<li><a href="../xmlenc.html">XML Encryption</a></li>
<li><a href="../c14n.html">XML Canonicalization</a></li>
<li><a href="../bugs.html">Reporting Bugs</a></li>
<li><a href="http://www.aleksey.com/pipermail/xmlsec">Mailing list</a></li>
<li><a href="../related.html">Related</a></li>
<li><a href="../authors.html">Authors</a></li>
</ul>
<table width="100%">
<tr>
<td width="15"></td>
<td><a href="http://xmlsoft.org/"><img src="../images/libxml2-logo.png" alt="LibXML2" border="0"></a></td>
</tr>
<tr>
<td width="15"></td>
<td><a href="http://xmlsoft.org/XSLT"><img src="../images/libxslt-logo.png" alt="LibXSLT" border="0"></a></td>
</tr>
<tr>
<td width="15"></td>
<td><a href="http://www.openssl.org/"><img src="../images/openssl-logo.png" alt="OpenSSL" border="0"></a></td>
</tr>
<!--Links - start--><!--Links - end-->
</table>
</td>
<td valign="top"><table width="100%" valign="top"><tr><td valign="top" align="left" id="xmlsecContent">
<table width="100%" class="navigation" summary="Navigation header" cellpadding="2" cellspacing="2"><tr valign="middle">
<td><a accesskey="p" href="xmlsec-verify-with-x509.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td>
<td><a accesskey="u" href="xmlsec-examples.html"><img src="up.png" width="24" height="24" border="0" alt="Up"></a></td>
<td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td>
<th width="100%" align="center">XML Security Library Reference Manual</th>
<td><a accesskey="n" href="xmlsec-encrypt-template-file.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td>
</tr></table>
<br clear="all"><div class="SECT1">
<h1 class="SECT1"><a name="XMLSEC-VERIFY-WITH-RESTRICTIONS">Verifying a signature with additional restrictions.</a></h1>
<br clear="all"><div class="SECT2">
<h2 class="SECT2"><a name="XMLSEC-EXAMPLE-VERIFY4">verify4.c</a></h2>
<p></p>
<div class="INFORMALEXAMPLE">
<p></p>
<a name="AEN722"></a><pre class="PROGRAMLISTING">
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#ifndef XMLSEC_NO_XSLT
#include <libxslt/xslt.h>
#include <libxslt/security.h>
#endif /* XMLSEC_NO_XSLT */
#include <xmlsec/xmlsec.h>
#include <xmlsec/xmltree.h>
#include <xmlsec/xmldsig.h>
#include <xmlsec/crypto.h>
xmlSecKeysMngrPtr load_trusted_certs(char** files, int files_size);
int verify_file(xmlSecKeysMngrPtr mngr, const char* xml_file);
int
main(int argc, char **argv) {
#ifndef XMLSEC_NO_XSLT
xsltSecurityPrefsPtr xsltSecPrefs = NULL;
#endif /* XMLSEC_NO_XSLT */
xmlSecKeysMngrPtr mngr;
assert(argv);
if(argc < 3) {
fprintf(stderr, "Error: wrong number of arguments.\n");
fprintf(stderr, "Usage: %s <xml-file> <cert-file1> [<cert-file2> [...]]\n", argv[0]);
return(1);
}
/* Init libxml and libxslt libraries */
xmlInitParser();
LIBXML_TEST_VERSION
xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
xmlSubstituteEntitiesDefault(1);
#ifndef XMLSEC_NO_XSLT
xmlIndentTreeOutput = 1;
#endif /* XMLSEC_NO_XSLT */
/* Init libxslt */
#ifndef XMLSEC_NO_XSLT
/* disable everything */
xsltSecPrefs = xsltNewSecurityPrefs();
xsltSetSecurityPrefs(xsltSecPrefs, XSLT_SECPREF_READ_FILE, xsltSecurityForbid);
xsltSetSecurityPrefs(xsltSecPrefs, XSLT_SECPREF_WRITE_FILE, xsltSecurityForbid);
xsltSetSecurityPrefs(xsltSecPrefs, XSLT_SECPREF_CREATE_DIRECTORY, xsltSecurityForbid);
xsltSetSecurityPrefs(xsltSecPrefs, XSLT_SECPREF_READ_NETWORK, xsltSecurityForbid);
xsltSetSecurityPrefs(xsltSecPrefs, XSLT_SECPREF_WRITE_NETWORK, xsltSecurityForbid);
xsltSetDefaultSecurityPrefs(xsltSecPrefs);
#endif /* XMLSEC_NO_XSLT */
/* Init xmlsec library */
if(xmlSecInit() < 0) {
fprintf(stderr, "Error: xmlsec initialization failed.\n");
return(-1);
}
/* Check loaded library version */
if(xmlSecCheckVersion() != 1) {
fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
return(-1);
}
/* Load default crypto engine if we are supporting dynamic
* loading for xmlsec-crypto libraries. Use the crypto library
* name ("openssl", "nss", etc.) to load corresponding
* xmlsec-crypto library.
*/
#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
fprintf(stderr, "Error: unable to load default xmlsec-crypto library. Make sure\n"
"that you have it installed and check shared libraries path\n"
"(LD_LIBRARY_PATH) envornment variable.\n");
return(-1);
}
#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
/* Init crypto library */
if(xmlSecCryptoAppInit(NULL) < 0) {
fprintf(stderr, "Error: crypto initialization failed.\n");
return(-1);
}
/* Init xmlsec-crypto library */
if(xmlSecCryptoInit() < 0) {
fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
return(-1);
}
/* create keys manager and load trusted certificates */
mngr = load_trusted_certs(&(argv[2]), argc - 2);
if(mngr == NULL) {
return(-1);
}
/* verify file */
if(verify_file(mngr, argv[1]) < 0) {
xmlSecKeysMngrDestroy(mngr);
return(-1);
}
/* destroy keys manager */
xmlSecKeysMngrDestroy(mngr);
/* Shutdown xmlsec-crypto library */
xmlSecCryptoShutdown();
/* Shutdown crypto library */
xmlSecCryptoAppShutdown();
/* Shutdown xmlsec library */
xmlSecShutdown();
/* Shutdown libxslt/libxml */
#ifndef XMLSEC_NO_XSLT
xsltFreeSecurityPrefs(xsltSecPrefs);
xsltCleanupGlobals();
#endif /* XMLSEC_NO_XSLT */
xmlCleanupParser();
return(0);
}
/**
* load_trusted_certs:
* @files: the list of filenames.
* @files_size: the number of filenames in #files.
*
* Creates simple keys manager and load trusted certificates from PEM #files.
* The caller is responsible for destroing returned keys manager using
* @xmlSecKeysMngrDestroy.
*
* Returns the pointer to newly created keys manager or NULL if an error
* occurs.
*/
xmlSecKeysMngrPtr
load_trusted_certs(char** files, int files_size) {
xmlSecKeysMngrPtr mngr;
int i;
assert(files);
assert(files_size > 0);
/* create and initialize keys manager, we use a simple list based
* keys manager, implement your own xmlSecKeysStore klass if you need
* something more sophisticated
*/
mngr = xmlSecKeysMngrCreate();
if(mngr == NULL) {
fprintf(stderr, "Error: failed to create keys manager.\n");
return(NULL);
}
if(xmlSecCryptoAppDefaultKeysMngrInit(mngr) < 0) {
fprintf(stderr, "Error: failed to initialize keys manager.\n");
xmlSecKeysMngrDestroy(mngr);
return(NULL);
}
for(i = 0; i < files_size; ++i) {
assert(files[i]);
/* load trusted cert */
if(xmlSecCryptoAppKeysMngrCertLoad(mngr, files[i], xmlSecKeyDataFormatPem, xmlSecKeyDataTypeTrusted) < 0) {
fprintf(stderr,"Error: failed to load pem certificate from \"%s\"\n", files[i]);
xmlSecKeysMngrDestroy(mngr);
return(NULL);
}
}
return(mngr);
}
/**
* verify_file:
* @mngr: the pointer to keys manager.
* @xml_file: the signed XML file name.
*
* Verifies XML signature in #xml_file.
*
* Returns 0 on success or a negative value if an error occurs.
*/
int
verify_file(xmlSecKeysMngrPtr mngr, const char* xml_file) {
xmlDocPtr doc = NULL;
xmlNodePtr node = NULL;
xmlSecDSigCtxPtr dsigCtx = NULL;
int res = -1;
assert(mngr);
assert(xml_file);
/* load file */
doc = xmlParseFile(xml_file);
if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){
fprintf(stderr, "Error: unable to parse file \"%s\"\n", xml_file);
goto done;
}
/* find start node */
node = xmlSecFindNode(xmlDocGetRootElement(doc), xmlSecNodeSignature, xmlSecDSigNs);
if(node == NULL) {
fprintf(stderr, "Error: start node not found in \"%s\"\n", xml_file);
goto done;
}
/* create signature context */
dsigCtx = xmlSecDSigCtxCreate(mngr);
if(dsigCtx == NULL) {
fprintf(stderr,"Error: failed to create signature context\n");
goto done;
}
/* limit the Reference URI attributes to empty or NULL */
dsigCtx->enabledReferenceUris = xmlSecTransformUriTypeEmpty;
/* limit allowed transforms for signature and reference processing */
if((xmlSecDSigCtxEnableSignatureTransform(dsigCtx, xmlSecTransformInclC14NId) < 0) ||
(xmlSecDSigCtxEnableSignatureTransform(dsigCtx, xmlSecTransformExclC14NId) < 0) ||
(xmlSecDSigCtxEnableSignatureTransform(dsigCtx, xmlSecTransformSha1Id) < 0) ||
(xmlSecDSigCtxEnableSignatureTransform(dsigCtx, xmlSecTransformRsaSha1Id) < 0)) {
fprintf(stderr,"Error: failed to limit allowed signature transforms\n");
goto done;
}
if((xmlSecDSigCtxEnableReferenceTransform(dsigCtx, xmlSecTransformInclC14NId) < 0) ||
(xmlSecDSigCtxEnableReferenceTransform(dsigCtx, xmlSecTransformExclC14NId) < 0) ||
(xmlSecDSigCtxEnableReferenceTransform(dsigCtx, xmlSecTransformSha1Id) < 0) ||
(xmlSecDSigCtxEnableReferenceTransform(dsigCtx, xmlSecTransformEnvelopedId) < 0)) {
fprintf(stderr,"Error: failed to limit allowed reference transforms\n");
goto done;
}
/* in addition, limit possible key data to valid X509 certificates only */
if(xmlSecPtrListAdd(&(dsigCtx->keyInfoReadCtx.enabledKeyData), BAD_CAST xmlSecKeyDataX509Id) < 0) {
fprintf(stderr,"Error: failed to limit allowed key data\n");
goto done;
}
/* Verify signature */
if(xmlSecDSigCtxVerify(dsigCtx, node) < 0) {
fprintf(stderr,"Error: signature verify\n");
goto done;
}
/* check that we have only one Reference */
if((dsigCtx->status == xmlSecDSigStatusSucceeded) &&
(xmlSecPtrListGetSize(&(dsigCtx->signedInfoReferences)) != 1)) {
fprintf(stderr,"Error: only one reference is allowed\n");
goto done;
}
/* print verification result to stdout */
if(dsigCtx->status == xmlSecDSigStatusSucceeded) {
fprintf(stdout, "Signature is OK\n");
} else {
fprintf(stdout, "Signature is INVALID\n");
}
/* success */
res = 0;
done:
/* cleanup */
if(dsigCtx != NULL) {
xmlSecDSigCtxDestroy(dsigCtx);
}
if(doc != NULL) {
xmlFreeDoc(doc);
}
return(res);
}
</pre>
<p></p>
</div>
</div>
<br clear="all"><div class="SECT2">
<h2 class="SECT2"><a name="XMLSEC-EXAMPLE-VERIFY4-TMPL">verify4-tmpl.xml</a></h2>
<p></p>
<div class="INFORMALEXAMPLE">
<p></p>
<a name="AEN727"></a><pre class="PROGRAMLISTING"><?xml version="1.0" encoding="UTF-8"?>
<!--
XML Security Library example: A simple SAML response template (verify4 example).
Sign it using the following command (replace __ with double dashes):
../apps/xmlsec sign __privkey rsakey.pem,rsacert.pem __output verify4-res.xml verify4-tmpl.xml
-->
<Response xmlns="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" IssueInstant="2002-04-18T16:56:54Z" MajorVersion="1" MinorVersion="0" Recipient="https://shire.target.com" ResponseID="7ddc31-ed4a03d703-FB24AD27D96135B68C99FB9AACFE2FFC">
<dsig:Signature xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
<dsig:SignedInfo>
<dsig:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<dsig:Reference URI="">
<dsig:Transforms>
<dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<dsig:DigestValue/>
</dsig:Reference>
</dsig:SignedInfo>
<dsig:SignatureValue/>
<dsig:KeyInfo>
<dsig:X509Data/>
</dsig:KeyInfo>
</dsig:Signature>
<Status>
<StatusCode Value="samlp:Success"/>
</Status>
<Assertion xmlns="urn:oasis:names:tc:SAML:1.0:assertion" AssertionID="7ddc31-ed4a03d735-FB24AD27D96135B68C99FB9AACFE2FFC" IssueInstant="2002-04-18T16:56:54Z" Issuer="hs.osu.edu" MajorVersion="1" MinorVersion="0">
<Conditions NotBefore="2002-04-18T16:56:54Z" NotOnOrAfter="2002-04-18T17:01:54Z">
<AudienceRestrictionCondition>
<Audience>http://middleware.internet2.edu/shibboleth/clubs/clubshib/1.0/</Audience>
</AudienceRestrictionCondition>
</Conditions>
<AuthenticationStatement AuthenticationInstant="2002-04-18T16:56:53Z" AuthenticationMethod="urn:mace:shibboleth:authmethod">
<Subject>
<NameIdentifier Format="urn:mace:shibboleth:1.0:handle" NameQualifier="osu.edu">foo</NameIdentifier>
<SubjectConfirmation>
<ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:Bearer</ConfirmationMethod>
</SubjectConfirmation>
</Subject>
<SubjectLocality IPAddress="127.0.0.1"/>
<AuthorityBinding AuthorityKind="samlp:AttributeQuery" Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding" Location="https://aa.osu.edu/"/>
</AuthenticationStatement>
</Assertion>
</Response></pre>
<p></p>
</div>
</div>
<br clear="all"><div class="SECT2">
<h2 class="SECT2"><a name="XMLSEC-EXAMPLE-VERIFY4-RES">verify4-res.xml</a></h2>
<p></p>
<div class="INFORMALEXAMPLE">
<p></p>
<a name="AEN732"></a><pre class="PROGRAMLISTING"><?xml version="1.0" encoding="UTF-8"?>
<!--
XML Security Library example: A simple SAML response template (verify4 example).
Sign it using the following command (replace __ with double dashes):
../apps/xmlsec sign __privkey rsakey.pem,rsacert.pem __output verify4-res.xml verify4-tmpl.xml
-->
<Response xmlns="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" IssueInstant="2002-04-18T16:56:54Z" MajorVersion="1" MinorVersion="0" Recipient="https://shire.target.com" ResponseID="7ddc31-ed4a03d703-FB24AD27D96135B68C99FB9AACFE2FFC">
<dsig:Signature xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
<dsig:SignedInfo>
<dsig:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<dsig:Reference URI="">
<dsig:Transforms>
<dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<dsig:DigestValue>t1nvDq1bZXEhBIXc/DHcqIrjRyI=</dsig:DigestValue>
</dsig:Reference>
</dsig:SignedInfo>
<dsig:SignatureValue>cj28Qr33wTqwHJzpI+7Mth7HUTr9MKACSH4x/1/AO64FEGiQRoOBB8XuUHZ8tzkP
Azy8FwoZE/Jv5d/0N3ru4Q==</dsig:SignatureValue>
<dsig:KeyInfo>
<dsig:X509Data>
<dsig:X509Certificate>MIIDpzCCA1GgAwIBAgIJAK+ii7kzrdqvMA0GCSqGSIb3DQEBBQUAMIGcMQswCQYD
VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTE9MDsGA1UEChM0WE1MIFNlY3Vy
aXR5IExpYnJhcnkgKGh0dHA6Ly93d3cuYWxla3NleS5jb20veG1sc2VjKTEWMBQG
A1UEAxMNQWxla3NleSBTYW5pbjEhMB8GCSqGSIb3DQEJARYSeG1sc2VjQGFsZWtz
ZXkuY29tMCAXDTE0MDUyMzE3NTUzNFoYDzIxMTQwNDI5MTc1NTM0WjCBxzELMAkG
A1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExPTA7BgNVBAoTNFhNTCBTZWN1
cml0eSBMaWJyYXJ5IChodHRwOi8vd3d3LmFsZWtzZXkuY29tL3htbHNlYykxKTAn
BgNVBAsTIFRlc3QgVGhpcmQgTGV2ZWwgUlNBIENlcnRpZmljYXRlMRYwFAYDVQQD
Ew1BbGVrc2V5IFNhbmluMSEwHwYJKoZIhvcNAQkBFhJ4bWxzZWNAYWxla3NleS5j
b20wXDANBgkqhkiG9w0BAQEFAANLADBIAkEA09BtD3aeVt6DVDkk0dI7Vh7Ljqdn
sYmW0tbDVxxK+nume+Z9Sb4znbUKkWl+vgQATdRUEyhT2P+Gqrd0UBzYfQIDAQAB
o4IBRTCCAUEwDAYDVR0TBAUwAwEB/zAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBH
ZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFNf0xkZ3zjcEI60pVPuwDqTM
QygZMIHjBgNVHSMEgdswgdiAFP7k7FMk8JWVxxC14US1XTllWuN+oYG0pIGxMIGu
MQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTE9MDsGA1UEChM0WE1M
IFNlY3VyaXR5IExpYnJhcnkgKGh0dHA6Ly93d3cuYWxla3NleS5jb20veG1sc2Vj
KTEQMA4GA1UECxMHUm9vdCBDQTEWMBQGA1UEAxMNQWxla3NleSBTYW5pbjEhMB8G
CSqGSIb3DQEJARYSeG1sc2VjQGFsZWtzZXkuY29tggkAr6KLuTOt2q0wDQYJKoZI
hvcNAQEFBQADQQAOXBj0yICp1RmHXqnUlsppryLCW3pKBD1dkb4HWarO7RjA1yJJ
fBjXssrERn05kpBcrRfzou4r3DCgQFPhjxga</dsig:X509Certificate>
</dsig:X509Data>
</dsig:KeyInfo>
</dsig:Signature>
<Status>
<StatusCode Value="samlp:Success"/>
</Status>
<Assertion xmlns="urn:oasis:names:tc:SAML:1.0:assertion" AssertionID="7ddc31-ed4a03d735-FB24AD27D96135B68C99FB9AACFE2FFC" IssueInstant="2002-04-18T16:56:54Z" Issuer="hs.osu.edu" MajorVersion="1" MinorVersion="0">
<Conditions NotBefore="2002-04-18T16:56:54Z" NotOnOrAfter="2002-04-18T17:01:54Z">
<AudienceRestrictionCondition>
<Audience>http://middleware.internet2.edu/shibboleth/clubs/clubshib/1.0/</Audience>
</AudienceRestrictionCondition>
</Conditions>
<AuthenticationStatement AuthenticationInstant="2002-04-18T16:56:53Z" AuthenticationMethod="urn:mace:shibboleth:authmethod">
<Subject>
<NameIdentifier Format="urn:mace:shibboleth:1.0:handle" NameQualifier="osu.edu">foo</NameIdentifier>
<SubjectConfirmation>
<ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:Bearer</ConfirmationMethod>
</SubjectConfirmation>
</Subject>
<SubjectLocality IPAddress="127.0.0.1"/>
<AuthorityBinding AuthorityKind="samlp:AttributeQuery" Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding" Location="https://aa.osu.edu/"/>
</AuthenticationStatement>
</Assertion>
</Response></pre>
<p></p>
</div>
</div>
<br clear="all"><div class="SECT2">
<h2 class="SECT2"><a name="XMLSEC-EXAMPLE-VERIFY4-BAD-TMPL">verify4-bad-tmpl.xml</a></h2>
<p></p>
<div class="INFORMALEXAMPLE">
<p></p>
<a name="AEN737"></a><pre class="PROGRAMLISTING"><?xml version="1.0" encoding="UTF-8"?>
<!--
XML Security Library example: A simple bad SAML response template (verify4 example).
Sign it using the following command (replace __ with double dashes):
../apps/xmlsec sign __privkey rsakey.pem,rsacert.pem __output verify4--bad-res.xml verify4-bad-tmpl.xml
-->
<Response xmlns="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" IssueInstant="2002-04-18T16:56:54Z" MajorVersion="1" MinorVersion="0" Recipient="https://shire.target.com" ResponseID="7ddc31-ed4a03d703-FB24AD27D96135B68C99FB9AACFE2FFC">
<dsig:Signature xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
<dsig:SignedInfo>
<dsig:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<dsig:Reference URI="">
<dsig:Transforms>
<dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<dsig:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
<dsig:XPath xmlns:samlp_xpath="urn:oasis:names:tc:SAML:1.0:protocol" >
count(ancestor-or-self::samlp_xpath:Response |
here()/ancestor::samlp_xpath:Response[1]) =
count(ancestor-or-self::samlp_xpath:Response)
</dsig:XPath>
</dsig:Transform>
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<dsig:DigestValue/>
</dsig:Reference>
</dsig:SignedInfo>
<dsig:SignatureValue/>
<dsig:KeyInfo>
<dsig:X509Data/>
</dsig:KeyInfo>
</dsig:Signature>
<Status>
<StatusCode Value="samlp:Success"/>
</Status>
<Assertion xmlns="urn:oasis:names:tc:SAML:1.0:assertion" AssertionID="7ddc31-ed4a03d735-FB24AD27D96135B68C99FB9AACFE2FFC" IssueInstant="2002-04-18T16:56:54Z" Issuer="hs.osu.edu" MajorVersion="1" MinorVersion="0">
<Conditions NotBefore="2002-04-18T16:56:54Z" NotOnOrAfter="2002-04-18T17:01:54Z">
<AudienceRestrictionCondition>
<Audience>http://middleware.internet2.edu/shibboleth/clubs/clubshib/1.0/</Audience>
</AudienceRestrictionCondition>
</Conditions>
<AuthenticationStatement AuthenticationInstant="2002-04-18T16:56:53Z" AuthenticationMethod="urn:mace:shibboleth:authmethod">
<Subject>
<NameIdentifier Format="urn:mace:shibboleth:1.0:handle" NameQualifier="osu.edu">foo</NameIdentifier>
<SubjectConfirmation>
<ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:Bearer</ConfirmationMethod>
</SubjectConfirmation>
</Subject>
<SubjectLocality IPAddress="127.0.0.1"/>
<AuthorityBinding AuthorityKind="samlp:AttributeQuery" Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding" Location="https://aa.osu.edu/"/>
</AuthenticationStatement>
</Assertion>
</Response></pre>
<p></p>
</div>
</div>
<br clear="all"><div class="SECT2">
<h2 class="SECT2"><a name="XMLSEC-EXAMPLE-VERIFY4-BAD-RES">verify4-bad-res.xml</a></h2>
<p></p>
<div class="INFORMALEXAMPLE">
<p></p>
<a name="AEN742"></a><pre class="PROGRAMLISTING"><?xml version="1.0" encoding="UTF-8"?>
<!--
XML Security Library example: A simple bad SAML response (verify4 example).
This file could be verified with verify3 example (signature is valid)
but verify4 example fails because of XPath transform which is not allowed
in a simple SAML response.
This file was created from a template with the following command (replace __ with double dashes):
../apps/xmlsec sign __privkey rsakey.pem,rsacert.pem __output verify4-bad-res.xml verify4-bad-tmpl.xml
-->
<Response xmlns="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" IssueInstant="2002-04-18T16:56:54Z" MajorVersion="1" MinorVersion="0" Recipient="https://shire.target.com" ResponseID="7ddc31-ed4a03d703-FB24AD27D96135B68C99FB9AACFE2FFC">
<dsig:Signature xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
<dsig:SignedInfo>
<dsig:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<dsig:Reference URI="">
<dsig:Transforms>
<dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<dsig:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
<dsig:XPath xmlns:samlp_xpath="urn:oasis:names:tc:SAML:1.0:protocol">
count(ancestor-or-self::samlp_xpath:Response |
here()/ancestor::samlp_xpath:Response[1]) =
count(ancestor-or-self::samlp_xpath:Response)
</dsig:XPath>
</dsig:Transform>
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<dsig:DigestValue>t1nvDq1bZXEhBIXc/DHcqIrjRyI=</dsig:DigestValue>
</dsig:Reference>
</dsig:SignedInfo>
<dsig:SignatureValue>PipZFFmmYcSnSU9p5AcOmFbRYoeatERYPy4IRk+jU26xk9sAM6yfhXtbK8csl/0w
rjODj1jGcydBGP9I8kFAfHyZ+Ls+A+53oMNl+tGWfe8iICMowIU1HCxJtPrgbTKk
1gc+VnYJ3IXhoVneeQKqzilXwA5X7FW7hgIecb5KwLShYV3iO8+z8pzt3NEGKAGQ
p/lQmO3EQR4Zu0bCSOk6zXdlOhe5dPVFXJQLlE8Zz3WjGQNo0l4op0ZXKf1B+syH
blHx0tnPQDtSBzQdKohJV39UgkGnL3rd5ggBzyXemjMTX8eFxNZ7bh4UgZ+Wo74W
Zb4ompTc2ImxJfbpszWp8w==</dsig:SignatureValue>
<dsig:KeyInfo>
<dsig:X509Data>
<X509Certificate xmlns="http://www.w3.org/2000/09/xmldsig#">MIIE3zCCBEigAwIBAgIBBTANBgkqhkiG9w0BAQQFADCByzELMAkGA1UEBhMCVVMx
EzARBgNVBAgTCkNhbGlmb3JuaWExEjAQBgNVBAcTCVN1bm55dmFsZTE9MDsGA1UE
ChM0WE1MIFNlY3VyaXR5IExpYnJhcnkgKGh0dHA6Ly93d3cuYWxla3NleS5jb20v
eG1sc2VjKTEZMBcGA1UECxMQUm9vdCBDZXJ0aWZpY2F0ZTEWMBQGA1UEAxMNQWxl
a3NleSBTYW5pbjEhMB8GCSqGSIb3DQEJARYSeG1sc2VjQGFsZWtzZXkuY29tMB4X
DTAzMDMzMTA0MDIyMloXDTEzMDMyODA0MDIyMlowgb8xCzAJBgNVBAYTAlVTMRMw
EQYDVQQIEwpDYWxpZm9ybmlhMT0wOwYDVQQKEzRYTUwgU2VjdXJpdHkgTGlicmFy
eSAoaHR0cDovL3d3dy5hbGVrc2V5LmNvbS94bWxzZWMpMSEwHwYDVQQLExhFeGFt
cGxlcyBSU0EgQ2VydGlmaWNhdGUxFjAUBgNVBAMTDUFsZWtzZXkgU2FuaW4xITAf
BgkqhkiG9w0BCQEWEnhtbHNlY0BhbGVrc2V5LmNvbTCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBAJe4/rQ/gzV4FokE7CthjL/EXwCBSkXm2c3p4jyXO0Wt
quaNC3dxBwFPfPl94hmq3ZFZ9PHPPbp4RpYRnLZbRjlzVSOq954AXOXpSew7nD+E
mTqQrd9+ZIbGJnLOMQh5fhMVuOW/1lYCjWAhTCcYZPv7VXD2M70vVXDVXn6ZrqTg
qkVHE6gw1aCKncwg7OSOUclUxX8+Zi10v6N6+PPslFc5tKwAdWJhVLTQ4FKG+F53
7FBDnNK6p4xiWryy/vPMYn4jYGvHUUk3eH4lFTCr+rSuJY8i/KNIf/IKim7g/o3w
Ae3GM8xrof2mgO8GjK/2QDqOQhQgYRIf4/wFsQXVZcMCAwEAAaOCAVcwggFTMAkG
A1UdEwQCMAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRp
ZmljYXRlMB0GA1UdDgQWBBQkhCzy1FkgYosuXIaQo6owuicanDCB+AYDVR0jBIHw
MIHtgBS0ue+a5pcOaGUemM76VQ2JBttMfKGB0aSBzjCByzELMAkGA1UEBhMCVVMx
EzARBgNVBAgTCkNhbGlmb3JuaWExEjAQBgNVBAcTCVN1bm55dmFsZTE9MDsGA1UE
ChM0WE1MIFNlY3VyaXR5IExpYnJhcnkgKGh0dHA6Ly93d3cuYWxla3NleS5jb20v
eG1sc2VjKTEZMBcGA1UECxMQUm9vdCBDZXJ0aWZpY2F0ZTEWMBQGA1UEAxMNQWxl
a3NleSBTYW5pbjEhMB8GCSqGSIb3DQEJARYSeG1sc2VjQGFsZWtzZXkuY29tggEA
MA0GCSqGSIb3DQEBBAUAA4GBALU/mzIxSv8vhDuomxFcplzwdlLZbvSQrfoNkMGY
1UoS3YJrN+jZLWKSyWE3mIaPpElqXiXQGGkwD5iPQ1iJMbI7BeLvx6ZxX/f+c8Wn
ss0uc1NxfahMaBoyG15IL4+beqO182fosaKJTrJNG3mc//ANGU9OsQM9mfBEt4oL
NJ2D</X509Certificate>
</dsig:X509Data>
</dsig:KeyInfo>
</dsig:Signature>
<Status>
<StatusCode Value="samlp:Success"/>
</Status>
<Assertion xmlns="urn:oasis:names:tc:SAML:1.0:assertion" AssertionID="7ddc31-ed4a03d735-FB24AD27D96135B68C99FB9AACFE2FFC" IssueInstant="2002-04-18T16:56:54Z" Issuer="hs.osu.edu" MajorVersion="1" MinorVersion="0">
<Conditions NotBefore="2002-04-18T16:56:54Z" NotOnOrAfter="2002-04-18T17:01:54Z">
<AudienceRestrictionCondition>
<Audience>http://middleware.internet2.edu/shibboleth/clubs/clubshib/1.0/</Audience>
</AudienceRestrictionCondition>
</Conditions>
<AuthenticationStatement AuthenticationInstant="2002-04-18T16:56:53Z" AuthenticationMethod="urn:mace:shibboleth:authmethod">
<Subject>
<NameIdentifier Format="urn:mace:shibboleth:1.0:handle" NameQualifier="osu.edu">foo</NameIdentifier>
<SubjectConfirmation>
<ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:Bearer</ConfirmationMethod>
</SubjectConfirmation>
</Subject>
<SubjectLocality IPAddress="127.0.0.1"/>
<AuthorityBinding AuthorityKind="samlp:AttributeQuery" Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding" Location="https://aa.osu.edu/"/>
</AuthenticationStatement>
</Assertion>
</Response></pre>
<p></p>
</div>
</div>
</div>
<table class="navigation" width="100%" summary="Navigation footer" cellpadding="2" cellspacing="2"><tr valign="middle">
<td align="left"><a accesskey="p" href="xmlsec-verify-with-x509.html"><b><<< Verifying a signature with X509 certificates.</b></a></td>
<td align="right"><a accesskey="n" href="xmlsec-encrypt-template-file.html"><b>Encrypting data with a template file. >>></b></a></td>
</tr></table>
</td></tr></table></td>
</tr></table></body>
</html>
| {
"content_hash": "ddaa5d71de8ce2b9e1e516bbab565fe5",
"timestamp": "",
"source": "github",
"line_count": 680,
"max_line_length": 283,
"avg_line_length": 44.83529411764706,
"alnum_prop": 0.7065074783521386,
"repo_name": "SoteriousIdaofevil/xmlstar",
"id": "86116c825994a9a47399dd2b18877a325a9a4d35",
"size": "31580",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "share/doc/xmlsec1/api/xmlsec-verify-with-restrictions.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "141281"
},
{
"name": "Awk",
"bytes": "3158"
},
{
"name": "Batchfile",
"bytes": "105895"
},
{
"name": "C",
"bytes": "60224544"
},
{
"name": "C#",
"bytes": "55626"
},
{
"name": "C++",
"bytes": "1629857"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "36522"
},
{
"name": "CSS",
"bytes": "19082"
},
{
"name": "Clean",
"bytes": "27204"
},
{
"name": "DIGITAL Command Language",
"bytes": "70628"
},
{
"name": "HTML",
"bytes": "46310322"
},
{
"name": "JavaScript",
"bytes": "143520"
},
{
"name": "M4",
"bytes": "1378720"
},
{
"name": "Makefile",
"bytes": "3795634"
},
{
"name": "Max",
"bytes": "1184"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "Objective-C",
"bytes": "36179"
},
{
"name": "PHP",
"bytes": "81852"
},
{
"name": "Pascal",
"bytes": "70297"
},
{
"name": "Perl",
"bytes": "289466"
},
{
"name": "Python",
"bytes": "4550602"
},
{
"name": "Roff",
"bytes": "19596601"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "7077595"
},
{
"name": "XSLT",
"bytes": "2271778"
},
{
"name": "Yacc",
"bytes": "7516"
}
],
"symlink_target": ""
} |
<?php
namespace backend\service;
use backend\models\User;
class UserService
{
public static function show()
{
return User::find()->asArray()->all();
}
/**
* 按id查询用户
*/
public static function selId($id)
{
return User::findOne($id);
}
/**
* 更新到数据库
*/
public static function editUser($id,$user)
{
$model = User::findOne($id);
if(!$model){
return false;
}
$model->setAttributes($user);
return $model->save();
}
/**
* 删除用户
*/
public static function delUser($id)
{
return User::findOne($id)->delete();
}
} | {
"content_hash": "5be9e4fd9ecb62cd5370ff2b64f22516",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 46,
"avg_line_length": 16.725,
"alnum_prop": 0.4992526158445441,
"repo_name": "nihao5/huanglong",
"id": "500ea6a8a5bc96f845028532be25824432964760",
"size": "699",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/service/UserService.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "15351"
},
{
"name": "JavaScript",
"bytes": "76895"
},
{
"name": "PHP",
"bytes": "1034099"
}
],
"symlink_target": ""
} |
// Copyright 2022 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.
package org.chromium.weblayer_private;
import org.chromium.components.digital_asset_links.VerificationResultStore;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* WebLayerVerificationResultStore stores relationships in a local variable.
*/
public class WebLayerVerificationResultStore extends VerificationResultStore {
private static final WebLayerVerificationResultStore sInstance =
new WebLayerVerificationResultStore();
private Set<String> mVerifiedOrigins = Collections.synchronizedSet(new HashSet<>());
private WebLayerVerificationResultStore() {}
public static WebLayerVerificationResultStore getInstance() {
return sInstance;
}
@Override
protected Set<String> getRelationships() {
return mVerifiedOrigins;
}
@Override
protected void setRelationships(Set<String> relationships) {
mVerifiedOrigins = relationships;
}
} | {
"content_hash": "46e47fdd30129aa81c85eccb074d4466",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 88,
"avg_line_length": 30.135135135135137,
"alnum_prop": 0.757847533632287,
"repo_name": "chromium/chromium",
"id": "fc799333001460cb91cdb8f6fba39f2f10d5e017",
"size": "1115",
"binary": false,
"copies": "5",
"ref": "refs/heads/main",
"path": "weblayer/browser/java/org/chromium/weblayer_private/WebLayerVerificationResultStore.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/* #### Generated By: http://www.cufonfonts.com #### */
@font-face {
font-family: 'Avenir LT Std 95 Black';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 95 Black'), url('AvenirLTStd-Black.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 45 Book';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 45 Book'), url('AvenirLTStd-Book.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 85 Heavy';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 85 Heavy'), url('AvenirLTStd-Heavy.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 35 Light';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 35 Light'), url('AvenirLTStd-Light.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 65 Medium';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 65 Medium'), url('AvenirLTStd-Medium.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 55 Roman';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 55 Roman'), url('AvenirLTStd-Roman.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 95 Black Oblique';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 95 Black Oblique'), url('AvenirLTStd-BlackOblique.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 45 Book Oblique';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 45 Book Oblique'), url('AvenirLTStd-BookOblique.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 85 Heavy Oblique';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 85 Heavy Oblique'), url('AvenirLTStd-HeavyOblique.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 35 Light Oblique';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 35 Light Oblique'), url('AvenirLTStd-LightOblique.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 65 Medium Oblique';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 65 Medium Oblique'), url('AvenirLTStd-MediumOblique.woff') format('woff');
}
@font-face {
font-family: 'Avenir LT Std 55 Oblique';
font-style: normal;
font-weight: normal;
src: local('Avenir LT Std 55 Oblique'), url('AvenirLTStd-Oblique.woff') format('woff');
}
body{
font-family:'Avenir LT Std 55 Roman';
font-weight:normal;
}
h1{
font-family:'Avenir LT Std 95 Black';
font-weight:normal;
}
h2,h3{
font-family:'Avenir LT Std 65 Medium';
font-weight:normal;
}
p,h5,h4{
font-family:'Avenir LT Std 45 Book';
font-weight:normal;
}
strong {
font-family:'Avenir LT Std 95 Black';
font-weight:normal;
}
| {
"content_hash": "e16ea4eef04416cd75043f6ee761e03d",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 100,
"avg_line_length": 22.371900826446282,
"alnum_prop": 0.7000369412633912,
"repo_name": "sbeltran10/proyecto-final-web",
"id": "bea8002d1b5af0ff053fcace331ea82d72e2c06b",
"size": "2707",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "imports/assets/css/font-style.css",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "113"
},
{
"name": "CSS",
"bytes": "124736"
},
{
"name": "HTML",
"bytes": "4433"
},
{
"name": "JavaScript",
"bytes": "280758"
}
],
"symlink_target": ""
} |
package io.codearte.jFairyOnline.services;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
import io.codearte.jFairyOnline.config.JFOProperties;
import io.codearte.jFairyOnline.services.fairy.FairyProvider;
import io.codearte.jFairyOnline.services.validation.CountProvider;
import io.codearte.jfairy.Fairy;
import io.codearte.jfairy.producer.text.TextProducer;
import org.springframework.stereotype.Service;
import static java.lang.String.join;
import static java.lang.System.lineSeparator;
import static java.util.Collections.nCopies;
/**
* @author Olga Maciaszek-Sharma
* @since 8/26/17
*/
@Service
public class TextService {
private static final String LOREM_IPSUM = "loremIpsum";
private static final String TEXT = "text";
private static final String WORD = "word";
private static final String LATIN_WORD = "latinWord";
private static final String LATIN_SENTENCE = "latinSentence";
private static final String SENTENCE = "sentence";
private static final String PARAGRAPH = "paragraph";
private static final String RANDOM = "random";
private final JFOProperties jfoProperties;
private final FairyProvider fairyProvider;
private final CountProvider countProvider;
private final Map<String, BiFunction<String, Integer, String>> methodMap = new HashMap<>();
public TextService(JFOProperties jfoProperties, FairyProvider fairyProvider, CountProvider countProvider) {
this.jfoProperties = jfoProperties;
this.fairyProvider = fairyProvider;
this.countProvider = countProvider;
initialiseMethodMap();
}
public String getForType(String languageTag, int count, String textType) {
return methodMap.get(textType).apply(languageTag, count);
}
public String loremIpsum() {
return textProducer().loremIpsum();
}
public String loremIpsum(String languageTag, int count) {
int validCount = countProvider.validForText(count);
return join(lineSeparator(), nCopies(validCount, loremIpsum()));
}
public String text(String languageTag, int count) {
int validCount = countProvider.validForText(count);
return join(lineSeparator(), nCopies(validCount, text(languageTag)));
}
public String text(String languageTag) {
return textProducer(languageTag).text();
}
public String word(String languageTag, int count) {
int validCount = countProvider.validForText(count);
return textProducer(languageTag).word(validCount);
}
public String latinWord(int count) {
int validCount = countProvider.validForText(count);
return textProducer().latinWord(validCount);
}
private String latinWord(String languageTag, int count) {
return latinWord(count);
}
public String latinSentence(int wordCount) {
int validWordCount = countProvider.validForText(wordCount);
return textProducer().latinSentence(validWordCount);
}
private String latinSentence(String languageTag, int wordCount) {
return latinSentence(wordCount);
}
public String sentence(String languageTag, int wordCount) {
int validWordCount = countProvider.validForText(wordCount);
return textProducer(languageTag).sentence(validWordCount);
}
public String paragraph(String languageTag, int sentenceCount) {
int validSentenceCount = countProvider.validForText(sentenceCount);
return textProducer(languageTag).paragraph(validSentenceCount);
}
public String randomString(int charsCount) {
int validCharsCount = countProvider.validForRandomString(charsCount);
return textProducer().randomString(validCharsCount);
}
private String randomString(String languageTag, int charsCount) {
return randomString(charsCount);
}
private void initialiseMethodMap() {
methodMap.put(LOREM_IPSUM, this::loremIpsum);
methodMap.put(TEXT, this::text);
methodMap.put(WORD, this::word);
methodMap.put(LATIN_WORD, this::latinWord);
methodMap.put(LATIN_SENTENCE, this::latinSentence);
methodMap.put(SENTENCE, this::sentence);
methodMap.put(PARAGRAPH, this::paragraph);
methodMap.put(RANDOM, this::randomString);
}
private TextProducer textProducer(String languageTag) {
Fairy fairy = fairyProvider.getFairy(languageTag);
return fairy.textProducer();
}
private TextProducer textProducer() {
Fairy fairy = fairyProvider.getFairy(jfoProperties.getDefaultLanguageTag());
return fairy.textProducer();
}
}
| {
"content_hash": "a7b50c30cded491cc53334afc5fc2ee5",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 108,
"avg_line_length": 32.9,
"alnum_prop": 0.7825578676642506,
"repo_name": "Codearte/jfairy-online",
"id": "77d6f6e8fb87a41f95e706ad1b76a4ce152e357c",
"size": "4277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/codearte/jFairyOnline/services/TextService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/**
* MLLib tree loss module
* @module eclairjs/mllib/tree/loss
*/
module.exports = function(kernelP) {
return {
Loss: require('./Loss.js')(kernelP)
};
}; | {
"content_hash": "023d9ab538d88f0a7cd4265487d309ab",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 39,
"avg_line_length": 15.181818181818182,
"alnum_prop": 0.6227544910179641,
"repo_name": "EclairJS/eclairjs-node",
"id": "2131240edc967393cae039129c56d171b6718b5a",
"size": "760",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/mllib/tree/loss/module.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "1602633"
}
],
"symlink_target": ""
} |
#ifndef JMEM_ALLOCATOR_INTERNAL_H
#define JMEM_ALLOCATOR_INTERNAL_H
#ifndef JMEM_ALLOCATOR_INTERNAL
# error "The header is for internal routines of memory allocator component. Please, don't use the routines directly."
#endif /* !JMEM_ALLOCATOR_INTERNAL */
/** \addtogroup mem Memory allocation
* @{
*/
/**
* @{
* Valgrind-related options and headers
*/
#if JERRY_VALGRIND
# include "memcheck.h"
# define JMEM_VALGRIND_NOACCESS_SPACE(p, s) VALGRIND_MAKE_MEM_NOACCESS((p), (s))
# define JMEM_VALGRIND_UNDEFINED_SPACE(p, s) VALGRIND_MAKE_MEM_UNDEFINED((p), (s))
# define JMEM_VALGRIND_DEFINED_SPACE(p, s) VALGRIND_MAKE_MEM_DEFINED((p), (s))
# define JMEM_VALGRIND_MALLOCLIKE_SPACE(p, s) VALGRIND_MALLOCLIKE_BLOCK((p), (s), 0, 0)
# define JMEM_VALGRIND_RESIZE_SPACE(p, o, n) VALGRIND_RESIZEINPLACE_BLOCK((p), (o), (n), 0)
# define JMEM_VALGRIND_FREELIKE_SPACE(p) VALGRIND_FREELIKE_BLOCK((p), 0)
#else /* !JERRY_VALGRIND */
# define JMEM_VALGRIND_NOACCESS_SPACE(p, s)
# define JMEM_VALGRIND_UNDEFINED_SPACE(p, s)
# define JMEM_VALGRIND_DEFINED_SPACE(p, s)
# define JMEM_VALGRIND_MALLOCLIKE_SPACE(p, s)
# define JMEM_VALGRIND_RESIZE_SPACE(p, o, n)
# define JMEM_VALGRIND_FREELIKE_SPACE(p)
#endif /* JERRY_VALGRIND */
/** @} */
void jmem_heap_init (void);
void jmem_heap_finalize (void);
bool jmem_is_heap_pointer (const void *pointer);
void *jmem_heap_alloc_block_internal (const size_t size);
void jmem_heap_free_block_internal (void *ptr, const size_t size);
/**
* \addtogroup poolman Memory pool manager
* @{
*/
void jmem_pools_finalize (void);
/**
* @}
* @}
*/
/**
* @{
* Jerry mem-stat definitions
*/
#if JERRY_MEM_STATS
void jmem_heap_stat_init (void);
void jmem_heap_stat_alloc (size_t num);
void jmem_heap_stat_free (size_t num);
#define JMEM_HEAP_STAT_INIT() jmem_heap_stat_init ()
#define JMEM_HEAP_STAT_ALLOC(v1) jmem_heap_stat_alloc (v1)
#define JMEM_HEAP_STAT_FREE(v1) jmem_heap_stat_free (v1)
#else /* !JERRY_MEM_STATS */
#define JMEM_HEAP_STAT_INIT()
#define JMEM_HEAP_STAT_ALLOC(v1) JERRY_UNUSED (v1)
#define JMEM_HEAP_STAT_FREE(v1) JERRY_UNUSED (v1)
#endif /* JERRY_MEM_STATS */
/** @} */
#endif /* !JMEM_ALLOCATOR_INTERNAL_H */
| {
"content_hash": "e58b16e0c66992aae999bd3977d400f3",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 117,
"avg_line_length": 29.066666666666666,
"alnum_prop": 0.6954128440366972,
"repo_name": "zherczeg/jerryscript",
"id": "a3bc57ee9d439069d3b330b71de30515b618e257",
"size": "2812",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jerry-core/jmem/jmem-allocator-internal.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3218"
},
{
"name": "Batchfile",
"bytes": "2635"
},
{
"name": "C",
"bytes": "6133384"
},
{
"name": "C++",
"bytes": "63603"
},
{
"name": "CMake",
"bytes": "81618"
},
{
"name": "JavaScript",
"bytes": "2143645"
},
{
"name": "Makefile",
"bytes": "12690"
},
{
"name": "Python",
"bytes": "254714"
},
{
"name": "Riot",
"bytes": "2164"
},
{
"name": "Shell",
"bytes": "47479"
},
{
"name": "Tcl",
"bytes": "47442"
}
],
"symlink_target": ""
} |
package edu.psu.compbio.seqcode.gse.tools.fragdist;
import edu.psu.compbio.seqcode.gse.datasets.chipchip.*;
import edu.psu.compbio.seqcode.gse.tools.utils.Args;
import edu.psu.compbio.seqcode.gse.utils.database.*;
public class DumpFragDist {
public static void main(String args[]) throws Exception {
String fd = Args.parseString(args,"fragdist",(String)null);
if (fd == null) {
throw new IllegalArgumentException("Must supply --fragdist 'name;version' on the command line");
}
String pieces[] = fd.split(";");
if (pieces.length != 2) {
throw new IllegalArgumentException("Must supply --fragdist 'name;version' on the command line");
}
ChipChipMetadataLoader loader = new ChipChipMetadataLoader();
FragDist dist = loader.loadFragDist(pieces[0],pieces[1]);
for (int i = 0; i < dist.getLength(); i++) {
System.out.println(i + "\t" + dist.getValue(i));
}
}
} | {
"content_hash": "7797832952f7c92692fa1e22455a04a2",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 120,
"avg_line_length": 41.375,
"alnum_prop": 0.6374622356495468,
"repo_name": "shaunmahony/seqcode",
"id": "10e3d9d1eaa41934cfe54c5de44bd8f8b52d76bf",
"size": "993",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/edu/psu/compbio/seqcode/gse/tools/fragdist/DumpFragDist.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "8117382"
},
{
"name": "Perl",
"bytes": "14435"
},
{
"name": "Scheme",
"bytes": "10245"
},
{
"name": "Shell",
"bytes": "3462"
}
],
"symlink_target": ""
} |
package org.jetbrains.plugins.gradle.ui;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.ActionToolbarPosition;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.externalSystem.ExternalSystemUiAware;
import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.*;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSet;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings;
import org.jetbrains.plugins.gradle.settings.GradleSettings;
import org.jetbrains.plugins.gradle.util.GradleConstants;
import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import java.util.List;
import java.util.Set;
/**
* @author Vladislav.Soroka
* @since 10/6/2016
*/
public class GradleProjectCompositeSelectorDialog extends DialogWrapper {
private static final int MAX_PATH_LENGTH = 40;
@NotNull
private final Project myProject;
private final GradleProjectSettings myCompositeRootSettings;
private JPanel mainPanel;
private JPanel contentPanel;
@SuppressWarnings("unused")
private JBLabel myDescriptionLbl;
private ExternalSystemUiAware myExternalSystemUiAware;
private CheckboxTree myTree;
public GradleProjectCompositeSelectorDialog(@NotNull Project project, String compositeRootProjectPath) {
super(project, true);
myProject = project;
myCompositeRootSettings = GradleSettings.getInstance(myProject).getLinkedProjectSettings(compositeRootProjectPath);
myExternalSystemUiAware = ExternalSystemUiUtil.getUiAware(GradleConstants.SYSTEM_ID);
myTree = createTree();
setTitle(String.format("%s Project Build Composite", GradleConstants.SYSTEM_ID.getReadableName()));
init();
}
@Nullable
@Override
protected JComponent createCenterPanel() {
ToolbarDecorator decorator = ToolbarDecorator.createDecorator(myTree).
addExtraAction(new SelectAllButton()).
addExtraAction(new UnselectAllButton()).
setToolbarPosition(ActionToolbarPosition.BOTTOM).
setToolbarBorder(IdeBorderFactory.createEmptyBorder());
contentPanel.add(decorator.createPanel());
return mainPanel;
}
@Override
protected void doOKAction() {
Pair[] pairs = myTree.getCheckedNodes(Pair.class, null);
Set<String> compositeParticipants = new HashSet<>();
for (Pair pair : pairs) {
compositeParticipants.add(pair.second.toString());
}
myCompositeRootSettings.setCompositeParticipants(compositeParticipants.isEmpty() ? null : compositeParticipants);
super.doOKAction();
}
@Override
public void doCancelAction() {
super.doCancelAction();
}
@Override
public void dispose() {
super.dispose();
}
private CheckboxTree createTree() {
final CheckedTreeNode root = new CheckedTreeNode();
List<TreeNode> nodes = ContainerUtil.newArrayList();
for (GradleProjectSettings projectSettings : GradleSettings.getInstance(myProject).getLinkedProjectsSettings()) {
if (projectSettings == myCompositeRootSettings) continue;
boolean added = myCompositeRootSettings.getCompositeParticipants().contains(projectSettings.getExternalProjectPath());
String representationName = myExternalSystemUiAware.getProjectRepresentationName(
projectSettings.getExternalProjectPath(), projectSettings.getExternalProjectPath());
CheckedTreeNode treeNode = new CheckedTreeNode(Pair.create(representationName, projectSettings.getExternalProjectPath()));
treeNode.setChecked(added);
nodes.add(treeNode);
}
TreeUtil.addChildrenTo(root, nodes);
final CheckboxTree tree = new CheckboxTree(new CheckboxTree.CheckboxTreeCellRenderer(true, false) {
@Override
public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (!(value instanceof CheckedTreeNode)) return;
CheckedTreeNode node = (CheckedTreeNode)value;
if (!(node.getUserObject() instanceof Pair)) return;
Pair pair = (Pair)node.getUserObject();
ColoredTreeCellRenderer renderer = getTextRenderer();
renderer.setIcon(myExternalSystemUiAware.getProjectIcon());
String projectName = (String)pair.first;
renderer.append(projectName, SimpleTextAttributes.REGULAR_ATTRIBUTES);
String projectPath = StringUtil.trimMiddle((String)pair.second, MAX_PATH_LENGTH);
renderer.append(" (" + projectPath + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
setToolTipText((String)pair.second);
}
}, root);
TreeUtil.expand(tree, 1);
return tree;
}
private void walkTree(Consumer<CheckedTreeNode> consumer) {
final TreeModel treeModel = myTree.getModel();
final Object root = treeModel.getRoot();
if (!(root instanceof CheckedTreeNode)) return;
for (TreeNode node : TreeUtil.childrenToArray((CheckedTreeNode)root)) {
if (!(node instanceof CheckedTreeNode)) continue;
consumer.consume(((CheckedTreeNode)node));
}
}
private class SelectAllButton extends AnActionButton {
public SelectAllButton() {
super("Select All", AllIcons.Actions.Selectall);
}
@Override
public void actionPerformed(AnActionEvent e) {
walkTree(node -> node.setChecked(true));
((DefaultTreeModel)myTree.getModel()).reload();
}
}
private class UnselectAllButton extends AnActionButton {
public UnselectAllButton() {
super("Unselect All", AllIcons.Actions.Unselectall);
}
@Override
public void actionPerformed(AnActionEvent e) {
walkTree(node -> node.setChecked(false));
((DefaultTreeModel)myTree.getModel()).reload();
}
}
}
| {
"content_hash": "312afc3ed0e1a9f2c6b23b541e99721d",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 140,
"avg_line_length": 36.851190476190474,
"alnum_prop": 0.7554514617993862,
"repo_name": "idea4bsd/idea4bsd",
"id": "71370cecd4729b10240c158a4d616f69b8e98c79",
"size": "6791",
"binary": false,
"copies": "1",
"ref": "refs/heads/idea4bsd-master",
"path": "plugins/gradle/src/org/jetbrains/plugins/gradle/ui/GradleProjectCompositeSelectorDialog.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "59458"
},
{
"name": "C",
"bytes": "224097"
},
{
"name": "C#",
"bytes": "1538"
},
{
"name": "C++",
"bytes": "197012"
},
{
"name": "CSS",
"bytes": "197224"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Cucumber",
"bytes": "14382"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Groff",
"bytes": "35232"
},
{
"name": "Groovy",
"bytes": "2971715"
},
{
"name": "HLSL",
"bytes": "57"
},
{
"name": "HTML",
"bytes": "1829102"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "158117117"
},
{
"name": "JavaScript",
"bytes": "563135"
},
{
"name": "Jupyter Notebook",
"bytes": "93222"
},
{
"name": "Kotlin",
"bytes": "2208983"
},
{
"name": "Lex",
"bytes": "179058"
},
{
"name": "Makefile",
"bytes": "3018"
},
{
"name": "NSIS",
"bytes": "49952"
},
{
"name": "Objective-C",
"bytes": "28750"
},
{
"name": "Perl",
"bytes": "903"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6607"
},
{
"name": "Python",
"bytes": "23911290"
},
{
"name": "Ruby",
"bytes": "1217"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "63460"
},
{
"name": "Smalltalk",
"bytes": "64"
},
{
"name": "TeX",
"bytes": "25473"
},
{
"name": "Thrift",
"bytes": "1846"
},
{
"name": "TypeScript",
"bytes": "9469"
},
{
"name": "Visual Basic",
"bytes": "77"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Revue Mycol. , Paris 11: 66 (1946)
#### Original name
Leptosphaeria grignonnensis A.L. Guyot
### Remarks
null | {
"content_hash": "9307ac82eb37fc5b61e950daa0e096e8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 38,
"avg_line_length": 13.307692307692308,
"alnum_prop": 0.7052023121387283,
"repo_name": "mdoering/backbone",
"id": "6daf07c7bf7ffd299d884c2fb793aa87c3f9c13a",
"size": "235",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Leptosphaeriaceae/Leptosphaeria/Leptosphaeria grignonnensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.